text stringlengths 11 4.05M |
|---|
package file_service
import (
"fmt"
"github.com/akrylysov/pogreb"
"log"
"ms/sun/servises/file_service/file_common"
"ms/sun/servises/file_service/file_disk_cache"
"ms/sun/shared/helper"
"net/http"
)
type retryHttp struct {
cat file_common.FileCategory
w http.ResponseWriter
r ... |
package models
import (
"encoding/json"
"github.com/astaxie/beego/orm"
"github.com/imsilence/gocmdb/server/cloud"
)
type Asset struct {
Model
Id int `orm:"column(id);" json:"id"`
Name string `orm:"column(name);size(64);" json:"name"`
IP string `orm:"column(ip);size(256);" json:"... |
// Copyright 2013 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//Echo writes its arguments separated by blanks and terminated by a newline on the standard output.
package main
import (
"flag"
"fmt"
"io"
"os"
"strin... |
package solo
import (
"github.com/iotaledger/wasp/packages/coretypes/requestargs"
"github.com/iotaledger/wasp/packages/hashing"
"github.com/stretchr/testify/require"
"testing"
)
func TestPutBlobData(t *testing.T) {
env := New(t, false, false)
data := []byte("data-datadatadatadatadatadatadatadata")
h := env.Put... |
package database
import (
"go.mongodb.org/mongo-driver/mongo"
)
var Client *mongo.Client
|
package main
import (
"fmt"
"time"
)
//单向通道多用于函数参数里
var ch1 chan<- int //表示通道ch1只可以用来写的,只可以往ch1放值
var ch2 <-chan int //表示通道ch2只可以用来读的,只可以往ch2取值
func worker(id int,jobs<-chan int,result chan<- int){
for j:=range jobs{ //遍历用于读取数据的通道
fmt.Printf("WORKER:%d start job:%d\n",id,j)
time.Sleep(time.Second)
f... |
/*
An interface is an abstract type.
It is a set of method signatures.
A value of interface type can hold any value that implements thos methods
A type implements an interface by implementing its methods.
There is no explicit declaration of intent, no "implements" keyword.
Under the hood, interface values can be thoug... |
package main
import "fmt"
func main() {
var n = 100
//打印类型
fmt.Printf("%T\n", n)
//打印值
fmt.Printf("%v\n", n)
//打印转换为二进制
fmt.Printf("%b\n", n)
//打印数字
fmt.Printf("%d\n", n)
//打印转换为八进制
fmt.Printf("%o\n", n)
//打印转换为十六进制
fmt.Printf("%x\n", n)
var s = "helo world!"
//打印字符串
fmt.Printf("%s\n", s)
//打印值
fmt.... |
package utils
import (
"testing"
)
func TestIsPalindromeString(t *testing.T) {
var tests = []struct {
input string
want bool
}{
{"eatae", true},
{"tea", false},
{"tat", true},
}
for _, test := range tests {
got := IsPalindromeString(test.input)
if got != test.want {
t.Errorf("Got not same as ... |
// Copyright 2021 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
package mobiles
import ()
type Mobile struct {
}
func New() *Mobile {
return &Mobile{}
}
|
package controllers
import (
"io"
"os"
"strconv"
"time"
"Perekoter/models"
"Perekoter/utility"
"github.com/gin-gonic/gin"
)
func GetAllThreads(c *gin.Context) {
var threads []models.Thread
db := models.DB()
defer db.Close()
db.Preload("Board").Find(&threads)
c.JSON(200, gin.H{
"status": 0,
"body"... |
package navigator_test
import (
"testing"
"github.com/olliephillips/gofencer/navigator"
)
func TestSetOrigin(t *testing.T) {
n := new(navigator.Navigator)
// Create Geofence with this data
n.AddPoint(33.53625, -111.92674)
n.AddPoint(33.53038, -111.95352)
n.AddPoint(33.52416, -111.94408)
n.AddPoint(33.51049,... |
package request
import "net/http"
// AddHeader Add header to Request
func (options) AddHeader(k, v string) Option {
return func(r *Request) {
if r.requestHeader == nil {
r.requestHeader = http.Header{}
}
r.requestHeader.Add(k, v)
}
}
// SetHeader Set header to Request
func (options) SetHeader(k, v string)... |
package main
import "fmt"
/* Go supports methods defined on structs */
type rect struct {
width, height int
}
/* The area method has a receiver type of rect */
func (r *rect) area() int{
return r.width * r.height
}
/* Methods can be defined for either pointer or value receiver types. Here's an example of value re... |
package main
import "leetcode/dushengchen"
func main() {
//dushengchen.LargestRectangleArea([]int{12,11,10,9,8,7,6,5,4,3,2,1})、
head := &dushengchen.ListNode{}
cur := head
for _, v := range []int{1,4,3,2,5,2} {
cur.Next = &dushengchen.ListNode{Val: v}
cur = cur.Next
}
dushengchen.Partition(head.Next, 3)
}
|
package accesstoken
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestGetNewAccessToken(t *testing.T) {
at := GetNewAccessToken(1)
assert.Equal(t, false, at.IsExpired(), "new access token should not be expired")
assert.Equal(t, "", at.AccessToken, "new access token should not have defin... |
package memory_cache
import (
"time"
)
func New() *Cache {
return &Cache{cacheMap: map[string]*cacheData{}}
}
type Cache struct {
cacheMap map[string]*cacheData
}
func (c *Cache) Set(key string, data interface{}, sec ...int) {
var expire *time.Time
if len(sec) == 1 && sec[0] > 0 {
t := time.Now().Add(time.Du... |
package main
import (
"testing"
)
func TestToCFriend(t *testing.T) {
ts := []struct {
f Friend
} {
{ f: Friend{ ID: 1, Age: 10, }, },
{ f: Friend{ ID: 2, Age: 20, }, },
}
for _, tc := range ts {
f := tc.f
cf := toCFriend(f)
goID, cID := f.ID, cf.id
if goID != int(cID) {
t.Errorf("go id=%d c i... |
package autobatch
import (
"bytes"
"fmt"
"testing"
ds "gx/ipfs/Qmf4xQhNomPNhrtZc67qSnfJSjxjXs9LWvknJtSXwimPrM/go-datastore"
dstest "gx/ipfs/Qmf4xQhNomPNhrtZc67qSnfJSjxjXs9LWvknJtSXwimPrM/go-datastore/test"
)
func TestAutobatch(t *testing.T) {
dstest.SubtestAll(t, NewAutoBatching(ds.NewMapDatastore(), 16))
}
f... |
package models
import (
"fmt"
"strings"
"time"
"github.com/google/uuid"
"github.com/lib/pq"
)
type APIKey struct {
ID uuid.UUID `json:"id"`
Created time.Time `json:"created"`
LastUsed pq.NullTime `json:"last_used"`
PermissionLevel PermissionLevel `json:"permission... |
//go:build test
// +build test
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package engine
import (
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/Azure/go-autorest/autorest/to"
"github.com/kelseyhightower/envconfig"
"gi... |
package main
import (
"fmt"
"github.com/gorilla/mux"
"golang-http-server/config"
"golang-http-server/controller"
"golang-http-server/models"
"net/http"
"os"
)
func main() {
db := config.Init()
db.Debug().AutoMigrate(&models.Employee{})
router := mux.NewRouter()
router.HandleFunc("/api/employee/create", con... |
package main
import (
"fmt"
"github.com/google/uuid"
)
func main() {
x := uuid.New().URN()
fmt.Println("UUID ", x)
}
|
package redisRepository
import (
"time"
"github.com/go-redis/redis"
)
type RedisRepository struct {
db *redis.Client
}
func tryConnect(addr, password string) (*RedisRepository, error) {
client := redis.NewClient(&redis.Options{
Addr: addr,
Password: password,
DialTimeout: 10 * time.Second,
... |
package common
import (
"github.com/micro/go-micro/client"
"mix/test/utils/dispatcher"
)
var Dispatcher *dispatcher.Dispatcher
func initDispatcher(cli client.Client) {
Dispatcher = dispatcher.NewDispatcher(cli)
}
|
package password
import (
"reflect"
"strings"
"github.com/aghape/auth"
"github.com/aghape/auth/auth_identity"
"github.com/aghape/auth/claims"
"github.com/aghape/core/utils"
"github.com/aghape/session"
)
// DefaultAuthorizeHandler default authorize handler
var DefaultAuthorizeHandler = func(context *auth.Conte... |
package parser
import (
"encoding/xml"
"fmt"
"io/ioutil"
"os"
"strings"
)
// the root <mule> tags
type Mule struct {
XMLName xml.Name `xml:"mule"` // <mule> defined as root to structure
TestList []Test `xml:"test"` // <munit:test>s add an instance to TestList
}
// each <munit:test> tag
// test's naming con... |
package main
import (
//"log"
"net/http"
"regexp"
"strings"
"github.com/codegangsta/martini"
"github.com/coopernurse/gorp"
"github.com/zachlatta/southbayfession/misc"
"github.com/zachlatta/southbayfession/models"
"github.com/zachlatta/southbayfession/routes"
)
// The one and only martini instance.
var m *ma... |
package v1alpha1
type KafkaAutoCommit struct {
Enable bool `json:"enable" protobuf:"varint,1,opt,name=enable"`
}
|
package main
import "fmt"
func main() {
var answer1, answer2, answer3 string
fmt.Println("Your Name: ")
_, err := fmt.Scan(&answer1)
if err != nil {
fmt.Println(err)
}
fmt.Println("Favourite Food: ")
_, err = fmt.Scan(&answer2)
if err != nil {
fmt.Println(err)
}
fmt.Println("Favourite drink: ")
_, err... |
/*
Given 2 int values, return True if one is negative and one is positive. Except if the parameter "negative" is True, then return True only if both are negative.
*/
package main
import (
"fmt"
)
func pos_neg(a int, b int, negative bool) bool {
/* multiplication of a negative and positive number will always return ... |
package bbir
type Callback func(*CallbackOptions)
func NewDefaultCallbackOptions() *CallbackOptions {
return &CallbackOptions{
Each: func() {},
Before: func() {},
After: func() {},
}
}
type CallbackOptions struct {
Each func()
Before func()
After func()
}
func Before(f func()) Callback {
return fu... |
package main
import (
"net/http"
"net/http/httptest"
"testing"
"fmt"
"encoding/json"
"gopkg.in/h2non/gock.v1"
"io/ioutil"
"github.com/Bobochka/thumbnail_service/lib/service"
. "github.com/onsi/ginkgo"
. "github.com/onsi/ginkgo/extensions/table"
. "github.com/onsi/gomega"
)
func Test(t *testing.T) {
R... |
package models
import (
"time"
)
//GetGraphByHostID by id
func GetGraphByHostID(hostid int, start, end int64) ([]GraphInfo, int64, error) {
rep, err := API.CallWithError("graph.get", Params{"output": "extend",
"hostids": hostid, "sortfiled": "name"})
if err != nil {
return []GraphInfo{}, 0, err
}
hba, err :=... |
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
type Instruction struct {
operation int
value int
visited bool
}
func main() {
file, _ := os.Open("input/day08.txt")
defer file.Close()
scanner := bufio.NewScanner(file)
executable := make([]Instruction, 0)
jumps := make([]int, 0)
i ... |
package parser
import (
"errors"
"fmt"
"strings"
"github.com/josa42/go-xcode-project/pbxproj/ast"
"github.com/josa42/go-xcode-project/pbxproj/lexer"
"github.com/josa42/go-xcode-project/pbxproj/token"
)
type Parser struct {
l *lexer.Lexer
curToken token.Token
peekToken token.Token
}
func New(l *lexer.Lexe... |
package connector
import (
"sync"
)
type Statistics interface {
Requests() uint
TokenCacheHitsAtApiLevel() uint
TokenCacheMissesAtApiLevel() uint
TokenCacheFailsAtApiLevel() uint
TokenCacheHitsAtAuthLevel() uint
TokenCacheMissesAtAuthLevel() uint
TokenCacheFailsAtAuthLevel() uint
}
type statistics struct {
... |
package main
import (
"fmt"
"log"
"os"
"sync"
)
// CacheEvent
type CacheEvent struct {
Key string
File string
Op CacheOp
}
type CacheOp uint8
const (
UPDATE = 1
DELETE = 2
)
func (event CacheEvent) String() string {
switch (event.Op) {
case UPDATE:
return fmt.Sprintf("[Event] UPDATE \n\tFile: %s\n\... |
package template
import (
"github.com/TuiBianWuLu/samplewechat/config"
"github.com/TuiBianWuLu/samplewechat/token"
"fmt"
"github.com/TuiBianWuLu/samplewechat/util/request"
"encoding/json"
"github.com/TuiBianWuLu/samplewechat/util/response"
)
const (
SendTemplateUrl = "https://api.weixin.qq.com/cgi-bin/message... |
package main
type VictoryState int
const (
Ongoing = VictoryState(iota)
Lost
Won
)
|
package basic
import "fmt"
// 声明一个包含10个元素的int类型数组,数组不能改变大小
var a [10]int
func ArrayDemo() {
a[0] = 1
a[1] = 2
a[3] = 3
a[4] = 4
fmt.Println(a)
// 初始化数组,注意:数组的初始化需要指定大小或者通过 ... 让编译器推断大小(大小根据初始化的元素确定)
array := [3]int{1, 2, 3}
array2 := [...]int{1, 2, 3, 4, 5}
array3 := [...]int{4: 2} // 长度为5,原因是最后一个元素的下标为4,... |
package cli
import (
"encoding/json"
"path/filepath"
"github.com/cosmos/cosmos-sdk/x/genutil"
"github.com/cosmos/cosmos-sdk/x/genutil/types"
"github.com/gookit/gcli/v3"
"github.com/ovrclk/akcmd/client"
"github.com/ovrclk/akcmd/flags"
"github.com/pkg/errors"
tmtypes "github.com/tendermint/tendermint/types"
)
... |
package main
import (
"bytes"
"go-postgres/middleware"
"net/http"
"net/http/httptest"
"strings"
"testing"
_ "github.com/lib/pq"
)
func TestSetUp(t *testing.T) {
//Deletes all entries in book table and resets primary key sequence
middleware.PrepForTesting()
}
func TestCreateBook(t *testing.T) {
//tests addi... |
package main
import (
"time"
"log"
//"errors"
//"sync/atomic"
"github.com/liujianping/consumer"
)
type context struct{
main chan bool
count int32
}
func (c *context) Do(req interface{}) error {
r, _ := req.(*MyProduct)
return r.Do(c)
}
func (c *context) Encode(request interface{}) ([]byte, error) {
return... |
/**
* constants
* @author liuzhen
* @Description
* @version 1.0.0 2021/1/28 16:56
*/
package utils
import "testing"
func TestGeneratePrivateAndPublicKey(t *testing.T) {
}
func TestParsingRsaPublicKey(t *testing.T) {
}
func TestParsingRsaPrivateKey(t *testing.T) {
}
|
package widget
import (
"image"
"image/color"
"gioui.org/f32"
"gioui.org/layout"
"gioui.org/op"
"gioui.org/op/clip"
"gioui.org/op/paint"
"gioui.org/text"
"gioui.org/unit"
)
// SliderStyle is a multi-slider widget.
type SliderStyle struct {
Shaper text.Shaper
Font text.Font
ThumbRadius unit.Value
Trac... |
package hash
import (
"crypto/md5"
"io/ioutil"
"network"
"os"
"reflect"
"strings"
)
func InitializeUserAuthenticationMap(filePathToUserAuthenticationTxt string) (userAuthenticationMap map[string][16]byte) {
content, err := ioutil.ReadFile(filePathToUserAuthenticationTxt)
if network.ErrorHandler(err, "Error en... |
package config
const LastCommitLog = " "
const BuildDate = "Sun Apr 5 05:41:34 2020"
const Version = "0.0.1_SNAPSHOT"
|
package main
import (
"flag"
"fmt"
"log"
"math"
"os/exec"
"runtime"
"strconv"
"time"
"github.com/alex023/clock"
"github.com/ghostiam/systray"
"github.com/webview/webview"
)
func makeTimestamp() int64 {
return time.Now().UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
}
func fmtDuration(d... |
package main
type Secret struct {
Secret string
Passphrase string
TTL string
Recipient string
}
|
package gateway
import (
"context"
"errors"
"time"
"github.com/MagalixCorp/magalix-agent/v3/agent"
"github.com/MagalixCorp/magalix-agent/v3/client"
"github.com/MagalixTechnologies/core/logger"
"github.com/MagalixTechnologies/uuid-go"
"go.uber.org/zap/zapcore"
)
const auditResultsBatchSize = 1000
type Magali... |
package collectors
import (
"time"
"github.com/cloudfoundry-community/go-cfclient"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/log"
)
type ServicesCollector struct {
namespace string
environment string
deployment ... |
package handler
import (
"path/filepath"
"testing"
proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/core/v1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)
// SubmitMeasurementStatusTestSuite 是 SubmitMeasurementStatus rpc 的单元测试的 Test Suite
type SubmitMeasurementStatusT... |
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
query()
}
func check(err error) {
if err != nil {
fmt.Println(err)
panic(err)
}
}
func query() {
db, err := sql.Open("mysql", "root:!QAZ2wsx@tcp(127.0.0.1:3306)/jdbc")
check(err)
rows, err := db.Query("select * ... |
package controllers
import (
"BitcoinWeb/models/user"
"github.com/astaxie/beego"
)
type MainController struct {
beego.Controller
}
type RegisterController struct {
beego.Controller
}
func (c *MainController) Get() {
c.TplName = "login_and_register.html"
}
func (c *MainController) Post(){
c.TplName = "login_an... |
package main
import "fmt"
func main() {
printEveryDivisibleRange(10, 35, 3)
}
func printEveryDivisibleRange(n int, m int, x int) {
for i := n ; i <= m ; i++ {
if i % x == 0 {
fmt.Println(i)
}
}
} |
package slashing
import (
"testing"
"github.com/stretchr/testify/require"
sdk "github.com/cosmos/cosmos-sdk/types"
)
func TestHookOnValidatorBonded(t *testing.T) {
ctx, _, _, _, keeper := createTestInput(t, DefaultParams())
addr := sdk.ConsAddress(addrs[0])
keeper.onValidatorBonded(ctx, addr, nil)
period := ... |
package main
import (
"fmt"
)
func main() {
dst := []int{1, 2, 3, 4}
src := []int{5, 6, 7}
count := copy(dst[2:], src)
fmt.Println(dst, count)
}
|
/**
* Copyright (c) 2018 ZTE Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and the Apache License 2.0 which both accompany this distribution,
* and are available at http://www.eclipse.org/legal/epl-v10.html
... |
package main
import (
"io/ioutil"
"encoding/json"
"bytes"
"flag"
"fmt"
"github.com/perriv/go-tasker"
"os"
"os/exec"
"sort"
"strings"
)
var version = "0.3.1"
func is_visible_dir(fi os.FileInfo) bool {
return fi.Mode().IsDir() && !strings.HasPrefix(fi.Name(), ".")
}
func list_visible_dirs(path string) ([]s... |
// sqliteToMysql
package main
import (
//"crypto/md5"
//"crypto/rand"
"database/sql"
"os"
"strconv"
"time"
//"encoding/base64"
//"encoding/hex"
//"encoding/json"
//"fmt"
//"io"
//"io/ioutil"
"log"
//"net/http"
//"path"
sw "sqliteToMysql/switcher"
"strings"
//xupload "xinlanAdminTest/xinlanUpload"
/... |
package dao
import (
"webapp/persistence/bolt"
"webapp/persistence/memdb"
)
const MEMORY = 1
const BOLTDB = 2
var implementation = MEMORY
func SetDAOImplementation(implem int) {
if implem == MEMORY || implem == BOLTDB {
implementation = implem
} else {
panic("Cannot set DAO implementation : invalid implemen... |
package goemetry
type BoundingBox struct {
BottomLeft Point
Height uint
Width uint
}
func (receiver *BoundingBox) IsAboveish(other BoundingBox) bool {
yDistance := receiver.BottomLeft.Y - other.BottomLeft.Y
if yDistance <= 0 {
// receiver is actually below or level with other
return false
}
if ... |
package main
import (
"encoding/json"
"flag"
"html/template"
"net/http"
"net/url"
"sort"
"time"
)
var (
addr = flag.String("addr", ":8080", "ui address")
apis = flag.String("api", "http://localhost:5000", "api address")
tout = flag.Duration("tout", time.Second, "api cache timeout")
host string // host:port... |
package main
import "sort"
const inf = 100000000000
func findMinArrowShots(points [][]int) int {
sort.Slice(points, func(i, j int) bool {
return points[i][1] < points[j][1]
})
last := -inf
count := 0
for i := 0; i < len(points); i++ {
// 无重叠区间是>=,这是>
if points[i][0] > last {
last = points[i][1]
coun... |
package main
import (
"strings"
"testing"
)
func TestGetMountSource(t *testing.T) {
mountinfo := `22 44 0:21 / /sys rw,nosuid,nodev,noexec,relatime shared:6 - sysfs sysfs rw
23 44 0:22 / /proc rw,nosuid,nodev,noexec,relatime shared:5 - proc proc rw
24 44 0:5 / /dev rw,nosuid shared:2 - devtmpfs devtmpfs rw,size=98... |
package controller
import "net/http"
type AuthController interface {
Signin(response http.ResponseWriter, request *http.Request)
Signup(response http.ResponseWriter, request *http.Request)
}
|
package util
import (
"bufio"
"io"
"os"
"strings"
)
// OverlapWriteFile is overlap write data to file once
func OverlapWriteFile(fileName, fileData string) {
dirPathSlice := strings.Split(fileName, "/")
os.MkdirAll(strings.Trim(fileName, dirPathSlice[len(dirPathSlice)-1]), 0755)
f, fErr := os.Open... |
package actions
import (
"github.com/barrydev/api-3h-shop/src/model"
)
func InsertOrderItemByOrderId(orderId int64, body *model.BodyOrderItem) (*model.OrderItem, error) {
body.OrderId = &orderId
return InsertOrderItem(body)
}
|
package git
import (
"errors"
"git-get/pkg/git/test"
"testing"
"github.com/stretchr/testify/assert"
)
func TestFinder(t *testing.T) {
tests := []struct {
name string
reposMaker func(*testing.T) string
want int
}{
{
name: "no repos",
reposMaker: makeNoRepos,
want: 0,
}... |
package model
import (
"github.com/mongodb/mongo-go-driver/bson"
"github.com/mongodb/mongo-go-driver/bson/primitive"
"github.com/mongodb/mongo-go-driver/mongo"
log "github.com/sirupsen/logrus"
)
// Log ...
type Log struct {
Model `bson:",inline"`
UserID primitive.ObjectID `bson:"user_id"`
Method s... |
package cmd
import (
"encoding/json"
"log"
"os"
"github.com/spf13/cobra"
"github.com/jmhobbs/wordpress-scanner/shared"
)
var scanArchiveCmd = &cobra.Command{
Use: "scan-archive <plugin_name> <plugin_version> <plugin_archive>",
Short: "Scans a plugin archive for corruption",
Long: "",
Run: func (cmd *cob... |
/*
* @lc app=leetcode.cn id=973 lang=golang
*
* [973] 最接近原点的 K 个点
*/
package solution
// @lc code=start
func kClosest(points [][]int, k int) [][]int {
distance := func(p int) int {
return points[p][0]*points[p][0] + points[p][1]*points[p][1]
}
qSort := func(l, r int) int {
pivot := distance(l)
for l < r ... |
// 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 cosmiccart
import (
"fmt"
"os"
"testing"
"regexp"
"sync"
"github.com/stretchr/testify/assert"
)
var md5Regex = regexp.MustCompile("^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}")
var ccApi = NewCosmicCart(
"https://staging.cosmiccart.com/api",
os.Getenv("COSMIC_CART_CLIENT_ID"... |
package redis
// Config represents the configurations for the redis driver
type Config struct {
Network string `yaml:"net"`
Addr string `yaml:"addr"`
Timeout int64 `yaml:"timeout_ms"`
Master bool `yaml:"master"`
RepairEnabled bool `yaml:"rep... |
package main
import (
"github.com/kazhuravlev/options-gen/options-gen"
)
func main() {
for _, params := range []struct {
outFname string
structName string
}{
{
outFname: "./example_out_options.go",
structName: "Options",
},
{
outFname: "./example_out_config.go",
structName: "Config",
... |
/*
I didn't invent this challenge, but I find it very interesting to solve.
For every input number, e.g.:
4
Generate a range from 1 to that number:
[1 2 3 4]
And then, for every item in that list, generate a list from 1 to that number:
[[1] [1 2] [1 2 3] [1 2 3 4]]
Then, reverse every item of that list.
[[1] [2 1... |
/*
Copyright 2017 The Kubernetes 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 main
import (
"fmt"
"strconv"
"strings"
)
// CountTheWays is a custom type that
// we'll read a flag into
type CountTheWays []int
func (c *CountTheWays) String() string {
result := ""
for _, v := range *c {
if len(result) > 0 {
result += " ... "
}
result += fmt.Sprint(v)
}
return result
}
//... |
// Copyright (c) 2022 Zededa, Inc.
// SPDX-License-Identifier: Apache-2.0
package depgraph_test
import (
"fmt"
"reflect"
"github.com/lf-edge/eve/libs/depgraph"
)
type mockItemAttrs struct {
intAttr int
strAttr string
boolAttr bool
}
type mockItem struct {
name string
itemType string
attrs mockIte... |
package public
import (
"net/http"
"tpay_backend/adminapi/internal/common"
_func "tpay_backend/adminapi/internal/handler/func"
logic "tpay_backend/adminapi/internal/logic/public"
"tpay_backend/adminapi/internal/svc"
"github.com/tal-tech/go-zero/rest/httpx"
)
func LogoutHandler(ctx *svc.ServiceContext) http.Ha... |
package fraction
import (
"math/big"
"testing"
)
func TestFraction_Reduce(t *testing.T) {
f := NewFraction(big.NewInt(22), big.NewInt(33))
f.Reduce()
expected := NewFraction(big.NewInt(2), big.NewInt(3))
if !f.Equals(expected) {
t.FailNow()
}
f = NewFraction(big.NewInt(2), big.NewInt(3))
f.Reduce()
expec... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-09-11 09:07
# @File : lt_147_Insertion_Sort_List.go
# @Description :
# @Attention :
*/
package v0
import (
"fmt"
"testing"
)
func Test_insertionSortList2(t *testing.T) {
r := &ListNode{
Val: 4,
Next: &ListNode{
Val: 2,
Next: &ListNode{
Val: ... |
package main
import (
"fmt"
"github.com/spf13/cobra"
)
func serveCommand() *cobra.Command {
return &cobra.Command{
Use: "serve [ config file ]",
Short: "Connect to the storage and begin serving requests.",
Long: ``,
Example: "dex serve config.yaml",
Run: func(cmd *cobra.Command, ar... |
package main
import (
"errors"
"fmt"
)
var errInvalidInput error = errors.New("Invalid input")
type node struct {
data int
left, right *node
}
func addToTree(root *node, val int) *node {
if root == nil {
return &node{data: val}
}
if val <= root.data {
root.left = addToTree(root.left, val)
} else... |
package main
import (
"flag"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"reflect"
"strconv"
"sync"
"gopkg.in/yaml.v2"
mtr "github.com/Shinzu/go-mtr"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/log"
"github.com/prometheus/common/version"
)
type Exporter struct {
mutex ... |
package models
import (
"fmt"
"strings"
)
//Traveler 乘客信息.....
type Traveler struct {
PersonName string
Gender string
Type string
IDCardType string
IDCardNo string
Birthday string
Nationality string
IDIssueCountry string
IDIssueDate string
IDExpireDate string
... |
package gluster
import (
//"io/ioutil"
//"reflect"
"fmt"
//"github.com/docker/distribution/context"
storagedriver "github.com/docker/distribution/registry/storage/driver"
//"string"
//"strings"
"testing"
"time"
//"github.com/gluster/gogfapi/gfapi"
//"github.com/docker/distribution/registry/storage/driver/te... |
package cntest
import (
"bufio"
"context"
"database/sql"
"errors"
"fmt"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/client"
"github.com/docker/go-connections/nat"
"io"
"net"
"os"
"path/filepath"
... |
package main
import (
"fmt"
"strings"
)
//解析反向json
var ss =map[string]interface{}{"1": "bar", "2": "foo.bar", "3": "foo.foo", "4": "baz.cloudmall.com", "5": "baz.cloudmall.ai"}
func main(){
var result = []map[string]interface{}{}
for key,item:= range ss{
result = append(result,techlist(item.(string),key))
}
... |
package main
import (
"context"
"log"
"net"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/reflection"
pb "github.com/robinjmurphy/go-grpc-example/server/proto"
)
const (
port = ":50051"
)
type server struct{}
func (s *server) Multiply(ctx context.Context, req *pb.Request)... |
/*
Note: This is a companion problem to the System Design problem: Design TinyURL.
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design a class to encode a URL and decode a tiny URL.
There is... |
package main
import (
"fmt"
)
func main() {
// ======== Assignments ========
// type goes after the variable
// int, float32, float64
var x float64 // x := 1.0
var y float64 // y := 2.0
// x, y := 1.0, 2.0
// assign values
x = 1
y = 2
// template print: %v = go obj, %T = type
fmt.Printf("x=%v, type of ... |
package stt
import (
"bytes"
"fmt"
"github.com/open-horizon/examples/cloud/sdr/data-processing/wutil"
)
// TranscribeResponse is the top level struct which Watson speech to text gives us.
type TranscribeResponse struct {
Results []Result `json:"results"`
Index int `json:"results_index"`
}
// Result is j... |
package vars
import (
"fmt"
"net/url"
"strconv"
"github.com/spf13/cobra"
"github.com/makkes/gitlab-cli/api"
)
func NewCommand(client api.Client, project *string) *cobra.Command {
return &cobra.Command{
Use: "var KEY VALUE [ENVIRONMENT_SCOPE]",
Short: "Create a project-level variable",
Long: "Create a ... |
package models
type Course struct {
Name string `json:"name" gorm:"size:255"`
Semester uint `json:"semester"`
Lect_hour uint `json:"lect_hour"`
Lab_hour uint `json:"lab_hour"`
Credits uint `json:"credits"`
DeptID uint `json:"dept_id"`
Dept Department `gorm:"con... |
package handler
import (
"context"
"errors"
"testing"
"github.com/stretchr/testify/require"
"github.com/dkorittki/loago/internal/pkg/worker/service/loadtest"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/stretchr/testify/assert"
"github.com/dkorittki/loago/pkg/api/v1"
"githu... |
package main
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"fmt"
"github.com/go-piv/piv-go/piv"
"github.com/tcastelly/try-piv-go/lib"
)
// https://github.com/go-piv/piv-go/blob/master/piv/key_test.go#L335
// https://github.com/keybase/go-crypto/blob/master/openpgp/write.go#L204-L209
// https://github.co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.