text stringlengths 11 4.05M |
|---|
package inspect
import (
"go/ast"
"fmt"
"github.com/sky0621/go-testcode-autogen/inspect/result"
)
type CommentInspector struct{}
func (i *CommentInspector) IsTarget(node ast.Node) bool {
switch node.(type) {
case *ast.Comment:
return true
}
return false
}
func (i *CommentInspector) Inspect(node ast.Node,... |
package job
import (
"bufio"
"bytes"
"compress/gzip"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"time"
"common"
ds "poseidon/datastruct"
sj "github.com/bitly/go-simplejson"
"github... |
// Copyright 2017 Walter Schulze
//
// 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 assigns
var (
// invkID
assignments = make(map[string]assign)
)
type assign struct {
id string // ID of the assignment
holder chan interface{} // channel to pass result
}
|
package gpsd
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"sync"
"time"
)
type NMEAMode int
const (
ModeUnknown NMEAMode = iota
ModeNoFix
Mode2D
Mode3D
)
var ErrUnsupportedProtocolVersion = errors.New("unsupported protocol version")
// Positioner implementations provide geographic positio... |
package spellbook
import (
"cloud.google.com/go/datastore"
"context"
"decodica.com/flamel"
"errors"
"fmt"
"github.com/jinzhu/gorm"
"google.golang.org/appengine/log"
"net/http"
"strconv"
"strings"
)
type ReadHandler interface {
HandleGet(context context.Context, key string, out *flamel.ResponseOutput) flame... |
package rbt
import (
"fmt"
)
type node struct {
color color
key interface{}
value interface{}
children [2]*node
}
var fakeBlackNode = &node{color: black}
func newNode(key, value interface{}) *node {
return &node{key: key, value: value}
}
func (n *node) insert(key, value interface{}, comparer Compa... |
package parser
import (
"strings"
)
type TupleMap struct{
Word string
Url string
}
type ParserContent interface {
Parse(content string,url string) error
Close()
}
type whileSpaceSeparatorParser struct{
producer chan TupleMap
}
//we can create seperate parse based on anchor tags
func NewWhileSpaceSeparatorPar... |
/*
The challenge is to assign people to tasks randomly~.
From stdin you get 2 lines.
Line one is a comma-separated list of names.
Line 2 is a comma-separated list of jobs.
The output required is one line per task person combo.
The line should be formatted as Name:task.
If there are not enough people for jobs or vice v... |
package main
import (
"fmt"
. "github.com/little-go/learn-go/basic"
)
func main() {
fmt.Println(Eval(1, 2, "-"))
Aa()
fmt.Println(Convert2Bin(5)) // 101
fmt.Println(Convert2Bin(13)) // 1101
fmt.Println(Convert2Bin(2315)) // 100100001011
fmt.Println(Convert2Bin(0)) // 0
PrintFile("str.go")
//fmt.Prin... |
////////////////////////////////////////////////////////////////////////////////
// //
// Copyright 2021 Broadcom. The term Broadcom refers to Broadcom Inc. and/or //
// its subsidiaries. ... |
package main
import(
"github.com/griddb/go_client"
"fmt"
"strconv"
"time"
"os"
)
func main() {
factory := griddb_go.StoreFactoryGetInstance()
update := false
// Get GridStore object
port, err := strconv.Atoi(os.Args[2])
if err != nil {
fmt.Println(err)
os.Exit(2)
}
gridstore := factory.GetStore(map[s... |
package fs
import (
"os"
)
type osfile struct {
*os.File
data []byte
}
type osfs struct{}
// OS is a file system backed by the os package.
var OS = &osfs{}
func (fs *osfs) OpenFile(name string, flag int, perm os.FileMode) (MmapFile, error) {
f, err := os.OpenFile(name, flag, perm)
if err != nil {
return nil... |
package ondemand
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
type OnDemand struct {
BaseURL string
APIKey string
Debug bool
}
func New(apiKey string, debug bool) (od *OnDemand) {
od = &OnDemand{
BaseURL: "http://ondemand.websol.barchart.com/",
APIKey: apiKey,
Debug: debug,
}
... |
package _3_Longest_Substring_Without_Repeating_Characters
func lengthOfLongestSubstring(s string) int {
if len(s) == 0 {
return 0
}
if len(s) == 1 {
return 1
}
bstr := []byte(s)
max := 0
for i := range bstr {
ventor := []byte{bstr[i]}
if max >= len(bstr)-i {
break
}
for j := i + 1; j <= len(bstr)... |
// Copyright (c) 2014-2017 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package walletdbtest
import (
"bytes"
"fmt"
"reflect"
"sync"
"github.com/btcsuite/btcwallet/walletdb"
)
// errSubTestFail is used to signal that a sub test retur... |
/*
* @lc app=leetcode.cn id=1678 lang=golang
*
* [1678] 设计 Goal 解析器
*/
// @lc code=start
package main
func interpret(command string) string {
b := []byte{}
for i := 0; i < len(command); i++ {
if command[i] == ')' {
if command[i-1] == '(' {
b = append(b, 'o')
}
} else {
if command[i] != '(' {
... |
package main
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
func main() {
head := ListNode{4, &ListNode{5, &ListNode{6,nil}}}
re := removeNthFromEnd(&head, 2)
fmt.Println(re,re.Next)
}
func removeNthFromEnd(head *ListNode, n int) *ListNode {
a := new(ListNode)
a.Next = head
first := head
... |
package skiplist
import (
"fmt"
"testing"
)
func TestInsertSearch(t *testing.T) {
sl := NewSkipList(10)
for i := 0; i < 10; i++ {
if err := sl.Insert(fmt.Sprintf("hello%d", i), fmt.Sprintf("world%d", i)); err != nil {
t.Fatal(err)
}
}
for i := 0; i < 10; i++ {
key := fmt.Sprintf("hello%d", i)
if _, o... |
package common
import (
"encoding/json"
"logger"
"net/http"
)
func GetBuffer(req *http.Request, buf []byte) {
for {
_, err := req.Body.Read(buf)
if err != nil {
break
}
}
}
func Unmarshal(buf []byte, i interface{}) bool {
err := json.Unmarshal(buf, i)
if err != nil {
logger.PRINTLINE("Unmarshal err... |
package main
func nextPermutation(nums []int) {
bigIndex := 0
smallIndex := 0
for i := len(nums) - 1; i > 0; i-- {
if nums[i] > nums[i-1] {
bigIndex = i
smallIndex = i - 1
break
}
}
if bigIndex != 0 {
for i := len(nums) - 1; i >= bigIndex; i-- {
if nums[i] > nums[smallIndex] {
nums[i], nums[... |
package main
import (
"bufio"
"fmt"
"io"
"os"
"strings"
)
// Copied from https://github.com/juliangruber/go-intersect
// Hash has complexity: O(n * x) where x is a factor of hash function efficiency (between 1 and 2)
func Hash(a []rune, b []rune) []rune {
set := make([]rune, 0)
hash := make(map[rune]bool)
fo... |
package matrix
import (
"reflect"
"github.com/seemenkina/go-ntskem/ff"
"github.com/seemenkina/go-ntskem/poly"
)
type MatrixFF struct {
nRows uint32
nColumns uint32
m [][]uint16
}
func (mff *MatrixFF) New(nr, nc uint32) {
mff.nRows = nr
mff.nColumns = nc
mff.ZeroMatrix()
}
func (mff *MatrixFF) Ze... |
package admin
import (
"github.com/labstack/echo"
coreTransaction "mix/test/api/admin/controller/core.transaction"
)
func SetRoutes(e *echo.Echo) {
coreTransactionGroup := e.Group("/core/transaction")
coreTransactionGroup.GET("/getAccount", coreTransaction.GetAccount)
coreTransactionGroup.GET("/getAccountList",... |
package middlewares
import (
"strconv"
"strings"
"time"
"github.com/valyala/fasthttp"
"github.com/authelia/authelia/v4/internal/metrics"
)
// NewMetricsRequest returns a middleware if provided with a metrics.Recorder, otherwise it returns nil.
func NewMetricsRequest(metrics metrics.Recorder) (middleware Basic)... |
package appdynamics
import (
"github.com/HarryEMartland/terraform-provider-appdynamics/appdynamics/client"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"strconv"
)
func resourceHealthRule() *schema.Resource {
return &schema.Resource{
Create: resourceHealthRuleCreate,
Read: resourceHealthRuleRea... |
package main
import (
"time"
)
// what you will see, Hello and world will print in the order that the go routines were created,
// you should see a bunch of hellos then a bunch of worlds
func main() {
// anonamous function
go func() {
for i := 0; i < 100; i++ {
println("Hello")
}
}()
// anonamous funct... |
package handlers
import (
"net/http"
"github.com/root-gg/plik/server/common"
"github.com/root-gg/plik/server/context"
)
// GetUpload return upload metadata
func GetUpload(ctx *context.Context, resp http.ResponseWriter, req *http.Request) {
config := ctx.GetConfig()
// Get upload from context
upload := ctx.Ge... |
/*
Given a string s and a string t, check if s is subsequence of t.
You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).
A subsequence of a string is a new string which is formed from the original str... |
package transportador
import (
"time"
"github.com/google/uuid"
)
type Voucher struct{
NumeroEntrega uuid.UUID `json:"numeroEntrega"`
PrevisaoParaEntrega time.Time `json:"previsaoParaEntrega"`
} |
package cli
import (
"context"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strconv"
"github.com/btcsuite/btcutil/base58"
"github.com/koinos/koinos-cli/internal/cliutil"
"github.com/koinos/koinos-proto-golang/encoding/text"
"github.com/koinos/koinos-proto-golang/koinos"
"githu... |
package models
import (
"fmt"
"time"
"github.com/colinrs/ffly-plus/internal/config"
"github.com/colinrs/pkgx/logger"
"gorm.io/driver/mysql"
"gorm.io/gorm"
glogger "gorm.io/gorm/logger"
)
// DB ...
var DB *gorm.DB
// Database ...
func Database(mysqlConfig config.MySQLConfig) error {
logger.Info("mysql {%#v}... |
package controllor
import (
"encoding/json"
"os"
"strconv"
"strings"
"time"
"xiaodaimeng/models"
"xiaodaimeng/public"
)
type Lucky struct {
Key string `json:"key"`
Number string `json:"number"`
Content []string `json:"content"`
}
type LuckyData struct {
GuanYin []Lucky `json:"guan_yin"`
YueLao ... |
package qnamegen
import "math/rand"
var tldList WeightedList
func init() {
tldList = DefaultTLDList.ToWeightedList()
}
type TLDList map[string]uint
type WeightedList []string
func (w WeightedList) Shuffle(rounds int) {
for i := 0; i < rounds; i++ {
pos := rand.Intn(len(w))
w[i], w[pos] = w[pos], w[i]
}
}
f... |
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
"net/http"
"strconv"
)
type Customer struct {
Id int `json:"id"`
FirstName string `json:"firstName"`
MiddleName string `json:"middleName"`
LastName string `json:"lastName"`
DateOfBirth string `j... |
package commands
import (
"encoding/json"
"os"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"github.com/argoproj/pkg/cli"
kubecli "github.com/argoproj/pkg/kube/cli"
"github.com/argoproj/argo"
"github.com/argoproj/argo/util"
"gi... |
package main
import (
"net/http"
"log"
"encoding/json"
"fmt"
)
type Codes struct {
Name string `json:"n"`
Code int `json:"c"`
}
func main() {
searchCity("МОСКВА")
}
func searchCity(city string) {
foo1 := new([]Codes)
url := fmt.Sprintf("http://www.rzd.ru/suggester?compactMode=y&stationNamePart=%s&lang=... |
package db
import (
"time"
"universe/data"
"github.com/andy-zhangtao/golog"
)
// GetLanguage 返回需要查询的语言列表
func GetLanguage() (map[int]data.DLanguage, error) {
stmtOut, err := db.Query("SELECT ID, Name, `Keys`, Date FROM universe.language ")
if err != nil {
golog.Error(err.Error())
return nil, err
}
defer s... |
package admin
type IndexController struct {
BaseController
}
func (c *IndexController) Index() {
c.Islogin()
c.Redirect("/admin/dashboard", 302)
}
func (c *IndexController) Login(){
c.SetSession("admin_login", int(1))
c.Redirect("/admin/dashboard", 302)
} |
package drivestream
import (
"github.com/scjalliance/drivestream/fileversion"
"github.com/scjalliance/drivestream/fileview"
"github.com/scjalliance/drivestream/resource"
)
// FileReference is a reference to a drivestream file.
type FileReference interface {
// FileID returns the resource ID of the file.
FileID()... |
package metrics
import (
"fmt"
"io/ioutil"
"plugins"
"strings"
)
func (u *UptimeStats) createPayload(r *plugins.Result) error {
content, err := ioutil.ReadFile("/proc/uptime")
if nil != err {
return err
}
uptime_idle := strings.Split(strings.Trim(string(content), " \n"), " ")
r.Add(fmt.Sprintf("uptime %s"... |
package broker
import "net"
import "fmt"
import "log"
import . "../packet"
import . "../message"
type Server struct {
//TODO checar esse socket aqui
//MyServerSocket net.Conn
Listener net.Listener
NextHandlerId int
Handlers map[int]*ConnectionHandler
Senders map[string]*ConnectionHandler
Receivers map[strin... |
package main
import (
"fmt"
)
/*
与C++、Java等完整支持面向对象的语言不同,Golang没有显式的继承,而是通过组合实现继承
定义一个基类Person,提供姓名和年龄两个属性,以及SayHi一个方法(Init类似于构造函数)
*/
type Person struct {
name string
age int
}
/*
如果函数需要更新一个变量,或者如果一个实参太大而我们希望避免复制整个实参,必须使用指针来传递变量的地址
*/
func (p *Person) Init(name string, age int) {
p.name = name
p.age = age
}... |
package targetselector
import (
"strings"
"github.com/devspace-cloud/devspace/pkg/devspace/config/versions/latest"
"github.com/devspace-cloud/devspace/pkg/devspace/kubectl"
)
// SelectorParameter holds the information from the config and the command overrides
type SelectorParameter struct {
ConfigParameter Confi... |
package notice
import (
"io/ioutil"
"net/http"
"net/url"
)
type SmsNoticer struct {
config *SmsConfig
}
func (this *SmsNoticer) SendSms(num string, content string) (string, error) {
payload := this.newPayload(num, content)
resp, err := http.PostForm(this.config.Addr, payload)
if err != nil {
return "", err
... |
package middlewares
import (
"ginDemo/utils"
"github.com/gin-gonic/gin"
"net/http"
)
func JWTAuth() gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
claims, _ := utils.ParseToken(authHeader)
if claims == nil {
c.AbortWithStatus(http.StatusUnauthorized)
} else {... |
package main
import (
"fmt"
"time"
)
func main() {
DONE:
for {
fmt.Println("for")
select {
case <-time.After(5 * time.Second):
//goto DONE
break DONE
}
}
fmt.Println("DONE")
}
|
package main
import (
"fmt"
)
func main() {
mySlices := []int{2, 4, 6, 8, 10}
fmt.Println(mySlices)
fmt.Println(mySlices[1:4])
fmt.Println(mySlices[:3])
fmt.Println(mySlices[4:])
}
|
/*
Chef has just started watching Game of Thrones, and he wants to first calculate the exact time (in minutes) that it'll take him to complete the series.
The series has S seasons, and the ith season has Ei episodes, each of which are Li,1,Li,2,…,Li,Ei minutes long.
Note that these Li,j include the duration of the be... |
package main
import (
"fmt"
"github.com/garyburd/redigo/redis"
"log"
"time"
)
func main() {
//normal()
//args()
//fbool()
//sortset()
//sortset1()
expireTime()
}
func normal() {
conn, err := redis.Dial("tcp", "127.0.0.1:6379")
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
resp, err := conn.... |
package redis
import (
"context"
"github.com/go-redis/redis/v8"
"github.com/pkg/errors"
)
type RedisConfig struct {
Ctx context.Context
ConnString string
}
func (c *RedisConfig) Connect() *Redis {
return &Redis{
ctx: c.Ctx,
rdb: redis.NewClient(&redis.Options{
Addr: c.ConnS... |
package config
import (
"gopkg.in/gcfg.v1"
"io/ioutil"
"log"
"os"
)
type Product struct {
Url string
Timeout int //millisecond
}
type ProductList struct {
Url string
Timeout int //millisecond
}
type ProductCache struct {
CacheResetTimeOut int64 //second
Timeout int64 //second
}
type Con... |
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
dbUser := "docker"
dbPassword := "docker"
dbDatabase := "sampledb"
dbConn := fmt.Sprintf("%s:%s@tcp(127.0.0.1:3306)/%s?parseTime=true", dbUser, dbPassword, dbDatabase)
db, err := sql.Open("mysql", dbConn)
if err !... |
package fileshandler
import(
"path/filepath"
"log"
"fmt"
"io/ioutil"
"os"
"strings"
)
func GetPath(htmlPath ...string) string {
var path string
if len(htmlPath) == 0{
abs,err := filepath.Abs("./demos/")
if err != nil {
log.Fatal(err)
}
path = abs
} else {... |
package chanqueue
import (
"sync"
"testing"
"github.com/textnode/gringo"
)
func BenchmarkChan(b *testing.B) {
c := make(chan struct{}, 10)
b.StartTimer()
go func() {
for i := 0; i < b.N; i++ {
c <- struct{}{}
}
close(c)
}()
for _ = range c {
}
}
func BenchmarkQueue(b *testing.B) {
q := NewQueue()... |
package hpke
import (
"net/url"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestEncryptURLValues(t *testing.T) {
t.Parallel()
k1, err := GeneratePrivateKey()
require.NoError(t, err)
k2, err := GeneratePrivateKey()
require.NoError(t, err)
t.Run("v... |
/**
*@Author: haoxiongxiao
*@Date: 2019/3/18
*@Description: CREATE GO FILE repositories
*/
package repositories
import (
"bysj/models"
"fmt"
"github.com/jinzhu/gorm"
"log"
)
type OrderRepositories struct {
db *gorm.DB
}
func NewOrderRepositories() *OrderRepositories {
return &OrderRepositories{db: models.DB.M... |
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package models
import (
"encoding/json"
"github.com/trustbloc/sidetree-core-go/pkg/api/operation"
"github.com/trustbloc/sidetree-core-go/pkg/versions/0_1/model"
)
// ChunkFile defines chunk file schema.
type Chu... |
package api
import "net/mail"
// Email contains the information about email
type Email struct {
From *mail.Address
To *mail.Address
Subject string
Body string
}
// EmailService ...
type EmailService interface {
UseTemplate(e *Email, data interface{}, template string) error
Send(e *Email) error
}
|
package kafka
import (
"context"
"time"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
"github.com/containers-ai/alameda/datahub/pkg/entities"
autoscalingv1alpha1 "github.com/containers-ai/alameda/operator/api/v1alpha1"
datahubpkg "github.com/containers-ai/alameda/pkg/datahub"
k8sutils "github.com/cont... |
package slack
import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
)
func getTeamList(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Content-Type", "application/json")
response := []byte(`{
"ok": true,
"teams": [
{
"name": "Shinichi's workspace",
... |
package main
import (
"fmt"
studentSMS "sms/str-sms"
)
type student struct {
id int
name string
}
var students = make(map[int]*student)
func main() {
/*var (
input int
inputName string
inputId int
)
fmt.Println("欢迎使用学生管理系统:")
for {
fmt.Println("请输入数字选择:1.查看全部学生 2.添加学生(输入name 和 id)3.根据id 删除学生... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-07-09 09:31
# @File : _110_Balanced_Binary_Tree.go
# @Description : 判断是否是一颗平衡二叉树
1. 左右子树高度差不超过1
// 左边需要平衡 && 右边需要平衡
# @Attention :
注意 ,当为nil的时候, 是平衡的,意味着是true
*/
package v0
func isBalanced(root *TreeNode) bool {
b, _ := balanced(root)
return b
}
func ... |
package account
import (
"github.com/stretchr/testify/assert"
application "go_gin_gonic/core/application/account"
infrastructue "go_gin_gonic/core/infrastructure/account"
"testing"
)
func TestCreateAccount(t *testing.T) {
accountId := "123"
customerId := "456"
accountRepository := infrastructue.NewInMemoryAcc... |
package cmd
import (
"database/sql"
_ "embed"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/spf13/cobra"
"go.uber.org/zap"
"log"
"os"
"strings"
"text/template"
)
const (
schemaTable = "information_schema"
outputFolderModel = "models"
outputFolderRepo = "repositories"
outputFolderService = "... |
package persistence_test
import (
"strconv"
"testing"
"github.com/alicebob/miniredis"
"github.com/rafael84/shortener/persistence"
)
func TestRedis(t *testing.T) {
s, err := miniredis.Run()
if err != nil {
t.Fatal(err)
}
defer s.Close()
redis := persistence.NewRedis(s.Addr(), "", 0)
type KeyValue struc... |
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"os"
)
func getSignature(query string) string {
key := []byte(os.Getenv("SECRET_KEY"))
h := hmac.New(sha256.New, key)
h.Write([]byte(query))
return hex.EncodeToString(h.Sum(nil))
}
|
package intToRoman
import "testing"
func Test_intToRoman(t *testing.T) {
type args struct {
num int
}
tests := []struct {
name string
args args
want string
}{
// TODO: Add test cases.
{
name: "first",
args: args{
num: 1,
},
want: "I",
},
{
name: "second",
args: args{
num:... |
/*
Copyright 2017 The Kubernetes Authors.
Copyright 2021 The TiChi 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 applic... |
package main
import (
"encoding/json"
"text/template"
"github.com/seletskiy/godiff"
"github.com/seletskiy/tplutil"
)
var updatedHeaderTpl = template.Must(
template.New(`updated`).Parse(tplutil.Strip(`
Update at [{{.Date}}]{{"\n"}}
==={{"\n\n"}}
`)))
var rescopedTpl = template.Must(
template.New(`rescoped`).Fu... |
// Copyright 2023 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 leetcode
// 斐波那契数列
func climbStairs(n int) int {
p, q := 0, 1
for i := 0; i < n; i++ {
p, q = q, p+q
}
return q
}
// 递归
func climbStairs2(n int) int {
h := map[int]int{0: 0, 1: 1, 2: 2}
return _climbStairs(n, h)
}
func _climbStairs(n int, h map[int]int) int {
if v, ok := h[n]; ok {
return v
}
h[... |
package main
import (
"fmt"
"hack-assember/code"
"hack-assember/parser"
"hack-assember/symbol"
"io"
"os"
"strconv"
"strings"
)
func main() {
f, err := os.Open(os.Args[1])
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
p := parser.New(f)
var line int
var lineRom int64
for p.HasMoreComman... |
package main
import (
"fmt"
"strconv"
"math"
)
func reverse(num int) int {
str := strconv.Itoa(num)
runes := []rune(str)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
i, _ := strconv.Atoi(string(runes))
return i
}
func main() {
start, end, div, beauties :... |
package app
import (
"github.com/mjibson/goon"
"appengine"
"appengine/datastore"
)
type Child struct {
ID string `goon:"id" datastore:"-" json:"-"`
Parent *datastore.Key `goon:"parent" datastore:"-"`
Text string
}
func (src *Child) Save(c appengine.Context, p *Person) error {
g := goon.FromCont... |
package drivers
import "testing"
func TestSQLColDefinitions(t *testing.T) {
t.Parallel()
cols := []Column{
{Name: "one", Type: "int64"},
{Name: "two", Type: "string"},
{Name: "three", Type: "string"},
}
defs := SQLColDefinitions(cols, []string{"one"})
if len(defs) != 1 {
t.Error("wrong number of defs:"... |
package leetcode
/*You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
来源:力扣(LeetCode)
链接:https://leetcode-c... |
package tude
import (
"math"
)
const (
R = 6371000
)
type Shape interface {
Contains(point *Point) bool
}
type Point struct {
lng, lat float64
}
func Radians(x float64) float64 {
return x * math.Pi / 180
}
func Distance(p1, p2 *Point) float64 {
avgLat := Radians(p1.lat+p2.lat) / 2
disLat := R * math.Cos(av... |
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2020 Intel Corporation
package daemon
import (
"io/ioutil"
"os"
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
const (
nvmupdateOutput = `<?xml version="1.0" encoding="UTF-8"?>
<DeviceUpdate lang="en">
<Instance vendor="8086" devi... |
package types
// IndicatorsAndStatistics holds indicators and statistics data for Telco companies in Greece.
type IndicatorsAndStatistics struct {
Category string `json:"category" fake:"{randomstring:[General,Landlines,Mobile]}"`
Indicator string `json:"indicator" fake:"{randomstring:[Σταθερές,Κινητές,ΕΕ,Ελλάδα]}... |
package ginja
import (
"encoding/json"
"log"
"net/http"
"reflect"
"strings"
"sync"
"github.com/gin-gonic/gin"
)
type GinApi struct {
*gin.RouterGroup
Api
}
// New returns a new ginja.Api struct
func New(server *gin.Engine, config Config, middleware ...gin.HandlerFunc) *GinApi {
config.ApplyDefaults()
api... |
package nmsapi
import (
"github.com/Centny/gwf/log"
"github.com/Centny/gwf/routing"
"github.com/Centny/gwf/util"
"github.com/Centny/nms/nmsdb"
"html/template"
"path/filepath"
"strings"
)
var WWW = ""
var Alias = util.Map{}
func LoadAlias(fcfg *util.Fcfg) {
for key, _ := range fcfg.Map {
if !strings.HasPref... |
package translator
//go:generate mockgen -source=$GOFILE -destination=mock/mock_$GOFILE -package=mock
import (
"errors"
"fmt"
"github.com/goropikari/psqlittle/backend"
"github.com/goropikari/psqlittle/core"
)
// RelationalAlgebraNode is interface of RelationalAlgebraNode
type RelationalAlgebraNode interface {
... |
package db
import (
"encoding/json"
"errors"
"fmt"
"log"
pb "gopkg.in/cheggaaa/pb.v1"
"github.com/boltdb/bolt"
)
//NewBucketNotFoundError formatting for missing bucket
func NewBucketNotFoundError(bucketName string) error {
msg := fmt.Sprintf("Bucket not found: %s", bucketName)
return errors.New(msg)
}
//Ne... |
package git
import (
"git-get/pkg/run"
)
// ConfigGlobal represents a global gitconfig file.
type ConfigGlobal struct{}
// Get reads a value from global gitconfig file. Returns empty string when key is missing.
func (c *ConfigGlobal) Get(key string) string {
out, err := run.Git("config", "--global", key).AndCaptur... |
// Copyright 2018 Kuei-chun Chen. All rights reserved.
package sim
import (
"context"
"os"
"testing"
)
func TestGetSchema(t *testing.T) {
var err error
os.Setenv("DATABASE_URL", "mongodb://user:password@localhost/")
var client = getMongoClient()
defer client.Disconnect(context.Background())
collection := cl... |
package db
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"time"
)
func NewDatabase(env, user, password, hostname, dbname string) (*mongo.Database, error) {
server := mountServerConnection(env, user, password, hostname, dbname)
clientOptions := options... |
package accesslog
import (
"bufio"
"bytes"
"errors"
"net"
"net/http"
)
type ResponseProxy interface {
http.ResponseWriter
Status() int
ResponseBytes() []byte
}
type responseRecorder struct {
writer http.ResponseWriter
statusCode int
recordResponse bool
Body *bytes.Buffer
}
func New... |
package engine
import (
"io"
"mime/multipart"
"os"
)
// the main 'scan' function, will basically be a wrapper around the other functionalities
func (a *analysisService) Scan(FileName string) (*Report, error) {
a.logger.Debug("Skade Entrypoint")
var err error
//start by opening the file
suspiciousF... |
package generator
import (
"crypto/rand"
"log"
)
const char_spec = "(){}[]<>?!`~*#$^%;:'\"\\/"
const char_alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
const char_number = "0123456789"
type (
PassInfo struct {
CharacterSet string
Length int64
}
)
func getDictionary(characterSet string) stri... |
package bazi
import "fmt"
// NewSiZhu 新四柱
func NewSiZhu(pSolarDate *TSolarDate, pBaziDate *TBaziDate) *TSiZhu {
p := &TSiZhu{
pYearZhu: NewZhu(),
pMonthZhu: NewZhu(),
pDayZhu: NewZhu(),
pHourZhu: NewZhu(),
pSolarDate: pSolarDate,
pBaziDate: pBaziDate,
}
p.init()
return p
}
... |
package lcd
import (
"github.com/gorilla/mux"
"github.com/irisnet/irishub/client/context"
"github.com/irisnet/irishub/client/utils"
"github.com/irisnet/irishub/codec"
)
// RegisterRoutes - Central function to define routes that get registered by the main application
func RegisterRoutes(cliCtx context.CLIContext, ... |
package hlf
import (
"fmt"
"time"
)
//Logger log mechanism interface
type Logger interface {
Child(string) Logger
To(string) Logger
Ntf(string, ...interface{})
Inf(string, ...interface{})
Err(string, ...interface{})
Wrn(string, ...interface{})
Dbg(string, ...interface{})
Trc(string, ...interface{})
}
func ... |
package routers
import (
"github.com/byrnedo/apibase/controllers"
"github.com/byrnedo/oauthsvc/controllers/mq"
"github.com/byrnedo/oauthsvc/osinserver"
"github.com/byrnedo/apibase/natsio/defaultnats"
)
func init() {
controllers.SubscribeNatsRoutes(defaultnats.Conn, "oauth_svc_worker", mq.NewOauthController(defa... |
package delivery
import (
"testing"
"github.com/stretchr/testify/suite"
)
type accountServiceTestSuite struct {
baseTestSuite
}
func TestAccountService(t *testing.T) {
suite.Run(t, new(accountServiceTestSuite))
}
func (s *accountServiceTestSuite) TestetBalance() {
data := []byte(`[
{
"accountAlias": "Sgs... |
package main
// 两数之和
func twoSum(nums []int, target int) []int {
numMap := make(map[int]int)
for index, num := range nums {
numMap[num] = index
}
for index, num := range nums {
if otherIndex, ok := numMap[target-num]; ok && otherIndex != index {
return []int{index, otherIndex}
}
}
return nil
}
|
package db
import (
"database/sql"
)
var Db *sql.DB
func init() {
}
|
package main
// Lab 5. Order (Collections, and iterating)
// Requirements:
// As a lonely person, I would like to have a way to classify the store recipes in a cookbook
//
// Objective:
// 01 - Understand Iterating over collection
// 02 - Understand Package References
// 03 - Understand For loops
//
// Steps:
// 01 -... |
package pgsql
import (
"testing"
)
func TestInt4RangeArray(t *testing.T) {
testlist2{{
valuer: Int4RangeArrayFromIntArray2Slice,
scanner: Int4RangeArrayToIntArray2Slice,
data: []testdata{
{
input: [][2]int{{-2147483648, 2147483647}, {0, 21}},
output: [][2]int{{-2147483648, 2147483647}, {0, 21}}},... |
package main
import (
"fmt"
"math"
)
// 410. 分割数组的最大值
// 给定一个非负整数数组和一个整数 m,你需要将这个数组分成 m 个非空的连续子数组。设计一个算法使得这 m 个子数组各自和的最大值最小。
// 注意:
// 数组长度 n 满足以下条件:
// 1 ≤ n ≤ 1000
// 1 ≤ m ≤ min(50, n)
// https://leetcode-cn.com/problems/split-array-largest-sum/
func main() {
fmt.Println(splitArray2([]int{7, 2, 5, 10, 8... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.