text stringlengths 11 4.05M |
|---|
package arrayslice
import (
"reflect"
"testing"
)
func TestSum(t *testing.T){
t.Run("collection of any size", func(t *testing.T) {
numbers := []int{1,2,3}
got := Sum(numbers)
want := 6
if want != got {
t.Errorf("got %d want %d given, %v", got, want, numbers)
}
})
}
func TestSumAll(t *testing.T){
... |
package service_test
import (
"os"
"sync"
"testing"
authConfig "github.com/go-ocf/cloud/authorization/service"
authService "github.com/go-ocf/cloud/authorization/test/service"
"github.com/go-ocf/cloud/coap-gateway/refImpl"
"github.com/go-ocf/cloud/coap-gateway/uri"
refImplRA "github.com/go-ocf/cloud/resource-... |
package module
import (
"fmt"
"sort"
)
var registry = map[string]InitFunc{}
// Config is the conduit for providing initialization information to a module
type Config map[string]interface{}
// InitFunc is a factory function that returns a module
type InitFunc func(Config) (Patcher, error)
// Lookup retrieves a mo... |
package main
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"time"
)
func getFormatNow(tpl string) string {
tpls := map[string]string{
"zh": "%v年%d月%v %v:%v:%v",
"num": "%v-%d-%v %v:%v:%v",
}
now := time.Now()
year := now.Year()
month := now.Month()
day := now.Day()
hour := no... |
package funcframework
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"testing"
"time"
"cloud.google.com/go/functions/metadata"
cloudevents "github.com/cloudevents/sdk-go/v2"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
)
func TestValidateEventFunction(t *... |
package parser
import (
"fmt"
"io"
"os"
"reflect"
)
var snipConstTrue = []byte("const(true)")
var snipConstFalse = []byte("const(false)")
var snipOr = []byte("or{")
var snipAnd = []byte("and{")
var snipNeg = []byte("neg{")
var snipPar = []byte("par{")
var snipBlkEnd = []byte("}")
var snipLineBreak... |
package responses
type Response struct {
Message string `json:"message"`
}
func test() {
r := &Response{}
r.MarshalJSON()
}
|
package main
import(
"io/ioutil"
"encoding/json"
"net/http"
"fmt"
)
type User struct{
Id int `json:"identificador"` //Mudar nome da estrutura
Name string
}
var dataUser []User = []User{
User{
Id: 1,
Name: "Clayton",
},
User{
Id: 2,
Name: "Samanta",
},
}
//GET
func route... |
package session
import (
"go/internal/pkg/api/app/request"
"go/internal/pkg/response"
"net/http"
"github.com/gin-gonic/gin"
)
func (h *sessionHandler) UpdateHandler(ctx *gin.Context) {
var req request.SessionRequest
// claimId, _ := ctx.Get("userInfo")
claimemail := ctx.GetString("userEmail")
// req.UserID ... |
package main
import "log"
type IVisitor interface {
Visit()
}
type ProductionVisitor struct {
}
func (v ProductionVisitor)Visit(){
log.Printf("生成环境\n")
}
type TestingVisitor struct {
}
func (t TestingVisitor)Visit(){
log.Printf("测试环境\n")
}
type IElement interface {
Accept(visitor IVisitor)
}
type Element str... |
package services
import (
"context"
"github.com/tppgit/we_service/core"
"github.com/tppgit/we_service/entity/cloudmessage"
"github.com/tppgit/we_service/entity/order"
"github.com/tppgit/we_service/entity/payment"
"github.com/tppgit/we_service/entity/transformer"
"github.com/tppgit/we_service/entity/user"
"gith... |
package feed
import (
"camp/feed/service"
"camp/lib"
"github.com/simplejia/clog/api"
"net/http"
)
// @prefilter("Cors")
func (feed *Feed) GetAll(w http.ResponseWriter, r *http.Request) {
fun := "feed.Feed.GetAll"
feeds, err := service.NewFeed().GetAll()
if err != nil {
clog.Error("%s feed.Add err: %v", fun,... |
package main
import (
"flag"
"log"
"./logger"
)
type MyClass struct {
Logger logger.LoggerInterface
}
func (this *MyClass) SetLogger(logger logger.LoggerInterface) {
this.Logger = logger
}
func (this *MyClass) Log(message string) error {
return this.Logger.Log(message)
}
func main() {
logType := flag.Strin... |
package keeper_test
import (
"encoding/json"
"math/big"
"testing"
"github.com/stretchr/testify/suite"
"github.com/tendermint/tendermint/crypto"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/irisne... |
package models
import (
"time"
)
// ChatPost : chat_postテーブルモデル
type ChatPost struct {
ID int64
Room int64
User int64
Message string
CreatedAt time.Time
}
|
package doom
import (
"context"
"io"
)
type ioreturn struct {
n int
err error
}
type CtxReader struct {
ctx context.Context
r io.Reader
}
func NewReader(ctx context.Context, r io.Reader) *CtxReader {
return &CtxReader{ctx: ctx, r: r}
}
func (c *CtxReader) Read(buf []byte) (int, error) {
buf2 := make([]... |
package leetcode
/*Describe how you could use a single array to implement three stacks.
Yout should implement push(stackNum, value)、pop(stackNum)、isEmpty(stackNum)、peek(stackNum) methods. stackNum is the index of the stack. value is the value that pushed to the stack.
The constructor requires a stackSize parameter, ... |
package main
import (
"flag"
"fmt"
"log"
"os"
"os/user"
)
var (
help_text = `Usage: whoami [OPTION]...
Print the user name associated with the current effective user ID.
Same as id -un.
--help display this help and exit
--version output version information and exit`
version_text = `go-whoami... |
/*
* Minio Cloud Storage, (C) 2016 Minio, 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 la... |
package main
import (
"log"
"github.com/akrylysov/pogreb"
"ms/sun/shared/helper"
"fmt"
)
func main() {
db, err := pogreb.Open("pogreb.test1", nil)
if err != nil {
log.Fatal(err)
return
}
write := func() {
for i := 0; i < 100000; i++ {
err := db.Put(... |
package db
import (
"github.com/jinzhu/gorm"
m "github.com/thedevelopnik/netplan/pkg/models"
)
type NetplanRepository interface {
CreateNetworkMap(*m.NetworkMap) error
GetNetworkMap(uint) (*m.NetworkMap, error)
GetAllNetworkMaps() ([]m.NetworkMap, error)
UpdateNetworkMap(*m.NetworkMap) (*m.NetworkMap, error)
D... |
package gortex
import (
"fmt"
//"log"
)
// Long Short Term Memory cell
type TemporalConvolution struct {
Kernels []*Matrix // keep kernels as set of column vectors for calc speed
Biases *Matrix
Pads []*Matrix // learnable pads !!
KernelSize int
KernelShift int
}
func MakeTemporalConvolution(... |
package queue
const (
// Client will set the queue type to be able to push data
Client ConnectionType = iota
// Consumer will set the queue type to be able to pop data
Consumer ConnectionType = iota
)
// ConnectionType holds whether the connection is a Client or Consumer
type ConnectionType int
// Queue is the ... |
package models
import (
"encoding/json"
"fmt"
"github.com/firewut/go-json-map"
"project/modules/helpers"
"reflect"
"sync"
"time"
)
type Document struct {
Id string `json:"id"`
cache *Cache `json:"-"`
quit_channel chan bool `json:"-"`
quit_holder chan bool `json:"-"`
dat... |
package api
import (
"context"
"log"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/bradenbass/echo/proto"
)
func NewEchoServer() *EchoServer {
return &EchoServer{}
}
type EchoServer struct {
}
func (e *EchoServer) Echo(ctx context.Context, req *echopb.EchoRequest) (*echopb.EchoR... |
// Copyright (c) 2018 Palantir Technologies. 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 require... |
package models
type Comment struct {
BaseModel
Content string `json:"content"`
UserID string `json:"user_id"`
User User `gorm:"foreign_key:UserID" json:"user_id"`
ArticleID string `gorm:"not null" json:"user_id"`
}
|
package main
import (
"fmt"
"time"
// "reflect"
)
type tree struct {
value int
left, right *tree
}
type Employee struct {
//首字母大写的都可以导出
//全部小写不可以导出到其他的包
ID int
Name string
Address string
DoB time.Time
Position string
Saclary float64
Managerid int
test int
}
type Circl... |
package handler
import (
"context"
"net/http"
"time"
)
const CheckNetUrl = "https://clients3.google.com/generate_204"
const CheckInetJobPeriod = time.Second * 30
const CheckInetTimeOut = time.Second * 10
func (h *Handler) CheckInetJob() {
for {
start := time.Now()
ctx, cancel := context.WithTimeout(context.B... |
package main
import (
"hash/fnv"
"log"
)
func main() {
hashAlgo := fnv.New32a()
key := "dicky"
hashAlgo.Write([]byte(key))
log.Printf("hash value: %v", hashAlgo.Sum32())
value := 0x7fffffff
log.Printf("value: %v", value)
}
|
package types
import (
"bytes"
"encoding/hex"
"fmt"
"time"
"github.com/wealdtech/go-merkletree"
"github.com/ethereum/go-ethereum/crypto"
)
type Transaction struct {
Hash []byte
MerkleProof merkletree.Proof // sets when transaction is added to block
Timestamp time.Time
Data []byte
}
func C... |
package repositories
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"time"
)
type User struct {
ID string `gorm:"primary_key"`
Name string
Age int
Birthday *time.Time
Email string `gorm:"type:varchar(100);unique_index"`
Role s... |
package resource
import (
"net/http"
// "portal/model"
"portal/service"
"github.com/gin-gonic/gin"
)
func GetResource(c *gin.Context) {
data, msg := service.GetResource()
c.JSON(http.StatusOK, gin.H{
"code": 0,
"error": gin.H{
"msg": msg,
},
"data": data,
})
} |
package classfile
// CodeAttribute
/**
Code_attribute {
u2 attribute_name_index; CONSTANT_Utf8_info型常量索引,定值为"Code"
u4 attribute_length; length
u2 max_stack; 操作数栈的最大深度
u2 max_locals; 局部变量的存储空间(单位:Slot,槽,uint32)
u4 code_length; 字节码指令长度
u1 code[code_length]; java... |
package request
import (
//"fmt"
"gopkg.in/mgo.v2/bson"
)
type Condition interface {
IsQueryCondi() bool
Cond2QueryObj(cate string) bson.M
IsUpdateCondi() bool
Cond2UpdateObj(cate string) bson.M
}
|
package test
import (
"fmt"
"gengine/builder"
"gengine/context"
"gengine/engine"
"reflect"
"testing"
)
//in golang, you can't println(nil)
const nil_test_rule = `
rule "1" "test return nil"
begin
s = live.GetStringPtr()
live.SetStringPtr(s)
s1 = live.GetString()
b = live.GetBoolPtr()
live.SetBoolPtr(b)
i = ... |
package slackbot
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"time"
cloudbuild "google.golang.org/api/cloudbuild/v1"
)
// Notify posts a notification to Slack that the build is complete.
func Notify(b *cloudbuild.Build, webhook string, project string) {
url := fmt.Sprintf("https://console.cloud.goo... |
package pg
import (
"github.com/kyleconroy/sqlc/internal/sql/ast"
)
type CaseExpr struct {
Xpr ast.Node
Casetype Oid
Casecollid Oid
Arg ast.Node
Args *ast.List
Defresult ast.Node
Location int
}
func (n *CaseExpr) Pos() int {
return n.Location
}
|
package Problem0211
// WordDictionary 是字典
type WordDictionary struct {
dict []string
}
// Constructor 构建 WordDictionary
// Initialize your data structure here.
func Constructor() WordDictionary {
return WordDictionary{}
}
// AddWord 往 WordDictionary 中添加 word
// Adds a word into the data structure.
func (d *WordDic... |
//
// client.go
// Copyright (C) 2019 Grigorii Sokolik <g.sokol99@g-sokol.info>
//
// Distributed under terms of the MIT license.
//
package storage
import (
"sync"
"github.com/GSokol/go-aviasales-task/pkg/aviasales/places/client"
jsoniter "github.com/json-iterator/go"
)
var responsePool sync.Pool
var json = js... |
package chess
import (
"crypto/md5"
"fmt"
"strconv"
"strings"
"unicode"
)
// Side represents a side of the board.
type Side int
const (
// KingSide is the right side of the board from white's perspective.
KingSide Side = iota + 1
// QueenSide is the left side of the board from white's perspective.
QueenSide... |
package types
type Model struct {
Name string
Package string
}
|
// Copyright 2014 Marc-Antoine Ruel. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.
package main
import (
"errors"
"fmt"
"github.com/maruel/subcommands"
)
var cmdAskBeer = &subcommands.Command{
UsageLine: "beer <options... |
// 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 handlers
import (
"bytes"
"encoding/json"
"github.com/DATA-DOG/go-sqlmock"
"github.com/RecleverLogger/logger"
"github.com/RecleverLogger/logger/repository"
"github.com/jmoiron/sqlx"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func initTestDb() (*sqlx.DB, s... |
package invitation
import (
"github.com/go-pg/pg/v9"
"github.com/jpurdie/authapi"
authUtil "github.com/jpurdie/authapi/pkg/utl/Auth"
email "github.com/jpurdie/authapi/pkg/utl/mail"
"github.com/labstack/echo"
"os"
"strconv"
"time"
)
func (i Invitation) Create(c echo.Context, invite authapi.Invitation) error {
... |
package tools
import (
"github.com/example-inc/zuul-operator/cmd/manager/tools/zuul"
cachev1alpha1 "github.com/example-inc/zuul-operator/pkg/apis/cache/v1alpha1"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// Tools structure... |
package main
/*
* @lc app=leetcode id=111 lang=golang
*
* [111] Minimum Depth of Binary Tree
*/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func minDepth(root *TreeNode) int {
if root == nil {
return 0
}
l := minDepth... |
package models
import (
"fmt"
u "plmg/utils"
)
//структура для персонажа
type Character struct {
LitItem `gorm:"embedded"`
Name string `json:"name"`
About string `json:"about"`
Excerpt string `json:"excerpt"`
UserID uint `gorm:"default:0"`
}
func (character *Character) Create() map[string]interface{} ... |
package testdata
import (
"github.com/frk/gosql/internal/testdata/common"
)
type SelectWithAfterScanSliceQuery struct {
Users []*common.User2 `rel:"test_user:u"`
}
|
package main
import (
"encoding/json"
"fmt"
"log"
"os"
)
func main() {
//json_base()
json_stream()
//json_unknown()
}
/*****************************************************************************************************
JSON的基本编解码
******************************************************************************... |
package products
// PriceType is enumerates price type category
type PriceType string
const (
// Discount is discount on price percentage
Discount PriceType = "DISCOUNT"
// Quantity is discount on quantity
Quantity PriceType = "Quantity"
)
// String is a toString method for enums
func (s PriceType) String() stri... |
package common
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"golang-rest/models"
)
func Initialize() (*gorm.DB, error) {
db, err := gorm.Open("mysql", "root:12541254@tcp(127.0.0.1:3306)/installer?charset=utf8&parseTime=True&loc=Local")
db.LogMode(... |
package flow
import (
"testing"
. "github.com/BaritoLog/go-boilerplate/testkit"
)
func TestDummyRateLimiter(t *testing.T) {
var v interface{} = NewDummyRateLimiter()
limiter, ok := v.(RateLimiter)
FatalIf(t, !ok, "listener must be implemnet of RateLimiter")
bucket := limiter.Bucket("topic")
FatalIf(t, bucket... |
package main
fmt
// . represent simply import ,can use Println than fmt.Println
const PI = 3.14
var name = "gopher"
type newType int
type gopher struct{}
type golang interface {
}
func main() {
fmt.Print("a", "b", 1, 2, 3, "c", "d", "\n")
fmt.Println("a", "b", 1, 2, 3, "c", "d")
fmt.Printf("ab %d %d %d cd\n"... |
// +build compat_test
package secretstream
import (
"testing"
)
func TestToSodium(t *testing.T) {
common_test(t, NewEncryptor, NewSodiumRecvStream)
}
func TestFromSodium(t *testing.T) {
common_test(t, NewSodiumSendStream, NewDecryptor)
}
func TestSodium2Sodium(t *testing.T) {
common_test(t, NewSodiumSendStream... |
package shp
import (
"archive/zip"
"fmt"
"io"
"path"
"strings"
)
type zipShapeFileSet map[string]*zip.File
type zipFileSet map[string]zipShapeFileSet
// ZipReader provides an interface for reading Shapefiles that are compressed in a ZIP archive.
type ZipReader struct {
sr SequentialReader
z *zip.ReadCloser
... |
/*
* Copyright © 2018-2022 Software AG, Darmstadt, Germany and/or its licensors
*
* SPDX-License-Identifier: Apache-2.0
*
* 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://... |
/*
Copyright 2022 The KubeVela 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 writing,... |
package gitlab
import (
"net/http"
"time"
"github.com/sirupsen/logrus"
gitlab "github.com/xanzy/go-gitlab"
)
const (
pathAPI string = "/api/v3"
pathSession string = pathAPI + "/session"
)
// gitlabConfig provides parameters to access Gitlab API
type gitlabConfig struct {
endpoint string
login string
... |
package abnf
import (
"github.com/lioneagle/goutil/src/buffer"
)
type Pos = uint
type ByteBuffer = buffer.ByteBuffer
func NewByteBuffer(buf []byte) *ByteBuffer {
return buffer.NewByteBuffer(buf)
}
|
package friend
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
pbFriend "Open_IM/pkg/proto/friend"
"Open_IM/pkg/utils"
"context"
"fmt"
"strconv"
)
func (s *friendServer) GetFriendApplyList(ctx context.Context, req *pbFriend.GetFriendApplyReq) (*... |
package 博弈
const INF = 1000000000
var prefixSum []int
var hasVisit map[int]int
func stoneGameII(piles []int) int {
hasVisit = make(map[int]int)
prefixSum = getPrefixSumArray(piles)
return getMaxGoalWhenFirstPick(0, len(piles)-1, 1)
}
func getPrefixSumArray(baseArray []int) []int {
if len(baseArray) == 0 {
ret... |
package toolbox
import (
"fmt"
"os"
)
// PrintError prints an error message to stderr
func PrintError(fmtString string, opts ...interface{}) {
if opts == nil {
fmt.Fprintf(os.Stderr, "reto: %s\n", fmt.Sprintf(fmtString, opts...))
return
}
fmt.Fprintf(os.Stderr, "reto: %s\n", fmt.Sprintf(fmtString, opts...))
... |
package seeders
import (
"github.com/jinzhu/gorm"
uuid "github.com/satori/go.uuid"
"github.com/tespo/satya/v2/types"
)
var pods = types.Pods{
{
ID: uuid.FromStringOrNil("16ea71db-2adb-45fe-a3fe-9e9ad6dcabd3"),
Name: "Men's Complete",
Slug: "mens-complete",
Color: "#2665A5",
Cells: ... |
package main
import (
"net/http"
"github.com/gorilla/mux"
"github.com/go-redis/redis"
"html/template"
)
var client *redis.Client
var templates *template.Template
func main() {
client = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
templates = template.Must(template.ParseGlob("templates/*.html")... |
package main
import (
"flag"
"fmt"
"os"
"time"
"github.com/gentlemanautomaton/bindflag"
)
const (
// DefaultDataFile is the default redirection map data file.
DefaultDataFile = "redirect.json"
// DefaultCertificateCacheDir is the default certificate cache directory.
DefaultCertificateCacheDir = "cert-cache"... |
// Copyright 2019 The Xorm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package language
import (
"html/template"
"xorm.io/reverse/pkg/conf"
"xorm.io/xorm/schemas"
)
// Language represents a languages supported when reverse ... |
package config
import (
"bufio"
"fmt"
"os"
)
func loadWords(e *Env) (*Texts, error) {
texts := &Texts{}
wd, err := os.Getwd()
if err != nil {
return nil, err
}
f, err := os.Open(fmt.Sprintf("%s/%s", wd, e.WordsFilePath))
if err != nil {
return nil, err
}
lines := make([]string, 0, 0)
scanner := bufio.... |
package controller
import (
"errors"
"github.com/bearname/videohost/internal/common/infrarstructure/transport/controller"
"github.com/bearname/videohost/internal/videoserver/domain"
"net/http"
)
func TranslateError(err error) controller.TransportError {
if errors.Is(err, controller.ErrRouteNotFound) {
return c... |
/*
* Copyright 2018, CS Systemes d'Information, http://www.c-s.fr
*
* 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 requir... |
// Package policy contains an implementation of the Pomerium Policy Language.
package policy
import (
"io"
"github.com/open-policy-agent/opa/format"
"github.com/pomerium/pomerium/pkg/policy/criteria"
"github.com/pomerium/pomerium/pkg/policy/generator"
"github.com/pomerium/pomerium/pkg/policy/parser"
)
// re-ex... |
package model
import (
"github.com/fberrez/forum/datastore"
"time"
)
type Category struct {
Id int `json:"id" db:"category_id"`
Title string `json:"title" db:"category_title"`
Description string `json:"description" db:"category_description"`
Date time.Time `json:"date" db:"cate... |
package mempool
import (
"fmt"
"github.com/meshplus/bitxhub-kit/types"
"github.com/meshplus/bitxhub-model/pb"
)
// batchStore persists batch into DB, only be called by leader.
func (mpi *mempoolImpl) batchStore(txList []*pb.Transaction) {
batch := mpi.storage.NewBatch()
for _, tx := range txList {
txKey := co... |
package main
import (
"fmt"
"time"
)
func player1(table chan int) {
for {
ball := <-table
ball = 1 - ball
fmt.Println("Player 1: ", ball)
time.Sleep(100 * time.Millisecond)
table <- ball
}
}
func player2(table chan int) {
for {
ball := <-table
ball = 1 - ball
fmt.Println("Player 2: ", ball)
ti... |
package helper
import "github.com/gin-gonic/gin"
func Ok(ctx *gin.Context,data interface{}) {
ctx.JSON(200,gin.H{
"code":2000,
"msg":"ok",
"data":data,
})
}
func Err(ctx *gin.Context,code int ,msg string ) {
ctx.JSON(200,gin.H{
"code":code,
"msg":msg,
})
}
|
package client
import (
"fmt"
"testing"
)
func TestWechatMoneyFeeToString(t *testing.T) {
for i := 0.00; i < 10; i = i + 0.01 {
fmt.Println(WechatMoneyFeeToString(i))
}
}
|
package html
const (
TagH1 = "h1"
TagH2 = "h2"
TagH4 = "h4"
TagA = "a"
TagHREF = "href"
TagStrong = "strong"
)
|
package main
import (
"fmt"
)
//39.
//给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的
// 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
//
// candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
//
// 对于给定的输入,保证和为 target 的不同组合数少于 150 个。
//
//
//
// 示例 1:
//
//
//输入:candidates = [2,3,6,7], ... |
package binary_tree
import (
"fmt"
"testing"
)
func TestPreOrderTraversal(t *testing.T) {
n1 := &TreeNode{Val: 10}
n2 := &TreeNode{Val: 3}
n3 := &TreeNode{Val: 5}
n4 := &TreeNode{Val: 55}
n5 := &TreeNode{Val: -4}
n6 := &TreeNode{Val: -2}
n7 := &TreeNode{Val: 190}
n1.Left = n2
n1.Right = n3
n2.Left = n5
n... |
package csrf
import (
"net/http/httptest"
"strings"
"testing"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/utils"
"github.com/valyala/fasthttp"
)
func Test_CSRF(t *testing.T) {
app := fiber.New()
app.Use(New())
app.Post("/", func(c *fiber.Ctx) error {
return c.SendStatus(fiber.StatusOK)
}... |
package solutions
/*
* @lc app=leetcode id=28 lang=golang
*
* [28] Find the Index of the First Occurrence in a String
*/
/*
Your runtime beats 100 % of golang submissions
Your memory usage beats 47.07 % of golang submissions (2 MB)
*/
// @lc code=start
func strStr(haystack string, needle string) int {
index := ... |
package main
import "testing"
func TestParseTag(t *testing.T) {
testCases := []struct {
input, name, options string
}{
{"bad-prefix\"`", "", ""},
{"json:\"bad-suffix", "", ""},
{"json:\"name\"", "name", ""},
{"json:\"name,option\"", "name", "option"},
}
for _, tc := range testCases {
t.Run(tc.input, f... |
package main
import (
"fmt"
)
func addOne(a int) int {
return a + 1
}
func square(a int) int {
return a * a
}
func double(slice []int) {
slice = append(slice, slice...)
}
func mapSlice(f func(a int) int, slice []int) {
for i, n := range slice {
slice[i] = f(n)
}
}
func mapArray(f func(a int) int, array [3... |
package main
//Creating for loops, trying nesting them
//The plan was to create a vague representation of a chess board,
//but I do not yet know how to create a string-containing iterable in Go...
//TODO: learn how to crate lists/list-like structures and iterate over them
import "fmt"
func main() {
for num := 1; nu... |
package main
import "fmt"
func numSlices() (s []int) {
s = append(s, 1, 2)
return
}
func nilSlices() []int {
return nil
}
func main() {
fmt.Println(numSlices())
s := nilSlices()
fmt.Println(s)
if s != nil {
fmt.Println("not nil")
}
s = append(s, 1)
fmt.Println(s)
s = make([]int, 0)
fmt.Println(s)
... |
/*
Copyright 2022 The KubeVela 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 writing, softw... |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
package main
import (
"context"
"os"
"github.com/bongnv/gokit/internal/command"
)
func main() {
ctx := context.Background()
os.Exit(command.Execute(ctx))
}
|
package podagent
import (
"context"
"crypto/sha256"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/devopstoday11/tarian/pkg/tarianpb"
psutil "github.com/shirou/gopsutil/process"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/protobuf/type... |
// Copyright © 2017 Aeneas Rekkas <aeneas+oss@aeneas.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
//
// Unless required by appl... |
// Copyright 2017 Google Inc. 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 applicable... |
package pie
// Map will return a new slice where each element has been mapped (transformed).
// The number of elements returned will always be the same as the input.
//
// Be careful when using this with slices of pointers. If you modify the input
// value it will affect the original slice. Be sure to return a new all... |
package keva
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
)
func TestBucketCache(t *testing.T) {
t.Run("Clear() removes all cached values", func(t *testing.T) {
b1 := newBucket("bucket1")
b1.path = "ab"
b2 := newBucket("bucket2")
b2.path = "ab"
c := newBucketCache(DefaultMaxBucketsCach... |
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package utils_test
import (
"context"
"io"
"testing"
"time"
berrors "github.com/pingcap/tidb/br/pkg/errors"
"github.com/pingcap/tidb/br/pkg/utils"
"github.com/stretchr/testify/require"
"go.uber.org/multierr"
"google.golang.org/grpc/codes"
"google.g... |
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/kohirens/stdlib"
"github.com/kohirens/tmpltoapp/internal/cli"
"github.com/kohirens/tmpltoapp/internal/test"
"os"
"os/exec"
"strings"
"testing"
)
const (
FixtureDir = "testdata"
TmpDir = "tmp"
)
func TestMain(m *testing.M) {
// Only runs... |
package arrays
func imageSmoother(M [][]int) [][]int {
if M == nil || len(M) == 0 {
return nil
}
m := len(M)
newM := make([][]int, m)
for i := 0; i < m; i++ {
n := len(M[i])
newN := make([]int, n)
for j := 0; j < n; j++ {
sum := 0
count := 0
for k1 := i - 1; k1 <= i+1; k1++ {
for k2 := j - 1;... |
package http
type Handler interface {
ServeHTTP(w ResponseWriter, r *Request)
}
func ListenAndServe(address string, h Handler) error
|
package main
import "fmt"
func numWays(n int) int {
if n < 2 {
return 1
}
fib1 := 1
fib2 := 1
fibN := 0
for i := 2; i <= n; i++ {
fibN = (fib1 + fib2) % 1000000007
fib1 = fib2
fib2 = fibN
}
return fibN
}
func main() {
fmt.Println(numWays(1))
}
|
package app
import (
"time"
"unicode"
"github.com/pkg/errors"
)
// nolint: gochecknoglobals
var (
name = "app" // app name
version = "0.0.0-0-gmaster" // see https://semver.org/ to have a description of the format
buildAtRaw = "1970-01-01T00:00:00Z" // build dat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.