text stringlengths 11 4.05M |
|---|
package problem0190
import "testing"
func TestSolve(t *testing.T) {
t.Log(reverseBits(0))
t.Log(reverseBits(0b00000010100101000001111010011100))
}
|
// Adapter contains the functions and objects to convert vulcan library specific interfaces that are more generic
// into vulcan daemon specific interfaces and data structures.
package adapter
import (
"github.com/mailgun/vulcan"
"github.com/mailgun/vulcan/limit/connlimit"
"github.com/mailgun/vulcan/limit/tokenbuck... |
package libModel
import (
"fmt"
)
const (
errSchemaFormat = "Schema Error:[%s]\n"
errUnknownTypeFormat = "unknown datatype: columnName:%s, columnType:[%s]"
)
func errSchema(errMsg string) error {
return fmt.Errorf(errSchemaFormat, errMsg)
}
func errUnknownType(columnName, columnType string) error {
return... |
package controller
import (
"walletApi/src/common"
"walletApi/src/model"
"github.com/astaxie/beego"
"github.com/dchest/captcha"
)
type MainController struct {
beego.Controller
}
func (c *MainController) Get() {
//需要先获取一下session,以免c.CruSession未空
if c.CruSession == nil {
c.GetSession(common.USER_INFO)
}
u,... |
package nanokontrol2
import (
"github.com/telyn/midi/korg/korgsysex/format4"
"github.com/telyn/midi/sysex"
)
func ParseSysEx(in format4.Message) (out sysex.SysExer, err error) {
msgType := in.Data[0]
switch msgType {
case DataDumpRequestID:
msg := DataDumpRequest{}
err = msg.Parse(in.Data[1:])
out = msg
c... |
package models
import (
"crypto/md5"
"fmt"
"github.com/astaxie/beego/orm"
"strconv"
"strings"
)
// TableName 设置BackendUser表名
func (a *AdminBackendUser) TableName() string {
return AdminBackendUserTBName()
}
// AdminBackendUserQueryParam 用于查询的类
type AdminBackendUserQueryParam struct {
BaseQueryParam
UserName ... |
package main
import (
"fmt"
"log"
"os"
"time"
"github.com/faiface/beep"
"github.com/faiface/beep/effects"
"github.com/faiface/beep/mp3"
"github.com/faiface/beep/speaker"
)
func main() {
f, err := os.Open("../Miami_Slice_-_04_-_Step_Into_Me.mp3")
if err != nil {
log.Fatal(err)
}
streamer, format, err :... |
package models
import "github.com/jinzhu/gorm"
type GoodsType struct {
gorm.Model
Name string
}
|
package exphttp
import (
"context"
"net/http"
)
func newContext(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
addr := r.RemoteAddr
newCtx := context.WithValue(r.Context(), "remote-addr", addr)
next.ServeHTTP(w, r.WithContext(newCtx))
})
}
|
package main
import (
"io/ioutil"
"log"
"net/http"
"reflect"
"sort"
"strings"
"github.com/labstack/echo"
"github.com/naoina/toml"
)
// 路由的处理器
type routeHandler struct {
handlerName string
httpMethod string
method reflect.Value
}
// 路由的中间件
type validator struct {
routePrefix string
handlerName... |
package main
import (
"fmt"
"os"
)
const (
goroutines = 10
)
func main() {
counter := make(chan int, 1)
for i := 0; i < goroutines; i++ {
go func(counter chan int) {
val := <-counter
val++
fmt.Println("counter:", val)
if val == goroutines {
os.Exit(0)
}
counter <- val
}(counter)
... |
package actions
import (
"fmt"
"log"
"syscall"
"time"
)
//not to self - syscall reboot magic numbers reference: https://golang.org/pkg/syscall/?GOOS=linux&GOARCH=mips64le
func SystemPower(action string)(actionResp Power, error error){
if err := validatePowerAction(action); err != nil{
return Power{},err
}
s... |
package stub
import (
api "github.com/operator-framework/operator-sdk-samples/vault-operator/pkg/apis/vault/v1alpha1"
"github.com/operator-framework/operator-sdk-samples/vault-operator/pkg/vault"
"github.com/operator-framework/operator-sdk/pkg/sdk/handler"
"github.com/operator-framework/operator-sdk/pkg/sdk/types... |
/*
Copyright 2021 RadonDB.
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, software
distri... |
package handler
import (
"../domain/model"
"../domain/service"
user "../proto/user"
"context"
)
type User struct {
UserDataService service.IUserDataService
}
func (u *User) Register(ctx context.Context, userRegisterRequest *user.UserRegisterRequest, userRegisterResponse *user.UserRegisterResponse) error {
user... |
package htmlHeadings
import (
"log"
"net/http"
"testing"
"github.com/PuerkitoBio/goquery"
)
func TestHtmlHeadings(t *testing.T) {
testUrl := "https://www.htmldog.com/guides/html/beginner/headings/"
expectedResult := map[string]int{"h1": 1, "h2": 4, "h3": 2, "h4": 0, "h5": 0, "h6": 0}
doc, err := pingURL(te... |
package mysql
type TableRow struct {
Name string
Engine string
Collation string
}
type FieldRow struct {
Field string
Type string
Collation string
Null string
Default string
Extra string
Comment string
}
type IndexRow struct {
Name string `xorm:"Key_name"`
NonUnique boo... |
// Package timesafeguard collects the time of other nodes and ensures the
// remote times are not diverging too much from the local time. This is useful
// to ensure the following situation does not happen:
//
// 1. In a network of 3 nodes, node 1 goes down.
//
// 2. Node A comes back up, but with a 1-hour clock drift ... |
package app
import (
"github.com/cosmos/cosmos-sdk/baseapp"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types"
markertypes "github.com/provenance-io/provenance/x/marker/types"
)
var (
noopHandler = func(ctx ... |
package 数
// climbStairs 获取爬到第n阶的方法数,一次可以爬 1步 or 2步。
func climbStairs(n int) int {
// 1. 定义。
dp := make([]int, 50) // dp[i] 表示爬到第i阶的方法数。
// 2. 初始化。
dp[1] = 1
dp[2] = 2
// 3. 动态规划。
for i := 3; i <= n; i++ {
dp[i] = dp[i-1] + dp[i-2]
}
// 4. 返回。
return dp[n]
}
|
package connection
type Connector interface {
Dial() (ConnectorReadWriter, error)
}
type ConnectorReadWriter interface {
Close() error
Write(command string) error
Read() ([]byte, error)
} |
/*
* @lc app=leetcode.cn id=509 lang=golang
*
* [509] 斐波那契数
*/
package solution
// @lc code=start
func fib(N int) int {
if N <= 1 {
return N
}
N1, N2 := 0, 1
var res int
for i := 2; i <= N; i++ {
res = N1 + N2
N1 = N2
N2 = res
}
return res
}
// @lc code=end
|
package znr_test
import (
"fmt"
"reflect"
"strings"
"testing"
znr "github.com/billglover/zn-reader"
)
func TestKnownPhrases(t *testing.T) {
vl := znr.VocabList{
znr.Vocab{Writing: "你"},
znr.Vocab{Writing: "是"},
znr.Vocab{Writing: "好"},
znr.Vocab{Writing: "友"},
znr.Vocab{Writing: "你好"},
}
tr := znr... |
package review
import (
"fmt"
"html"
"html/template"
"regexp"
"strings"
)
// ProductReview represents a client's product review
type ProductReview struct {
ProductID int `json:"productid"`
Review string `json:"review"`
ReviewerName string `json:"name"`
EmailAddress string `json:"email"`
Rating ... |
package main
import "fmt"
func sum(s []int, c chan int) {
sum := 0
for _, v := range s {
sum += v
}
c <- sum
}
func fib(n int, c chan int) {
x, y := 0, 1
for i := 0; i < n; i++ {
c <- x
x, y = y, x+y
}
close(c)
}
func main() {
s := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(s[:len(s)/2], c... |
package exer9
const Message = "Hello world!" |
package repository
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"time"
)
type Ouin struct {
Heading string `json:"heading"`
Text string `json:"text"`
Page int `json:"page"`
Offset int `json:"offset"`
}
func GetOuinList(tango string) []Ouin {
v := url.Values{}
v.Add("api", "1")
v... |
package matcher
import (
"github.com/fmstephe/matching_engine/coordinator"
"github.com/fmstephe/matching_engine/msg"
"net"
"runtime"
"strconv"
"testing"
)
// Because we are communicating via UDP, messages could arrive out of order, in practice they travel in-order via localhost
const (
matcherOrigin = iota
c... |
package data
import "time"
type Contest struct {
ID uint `gorm:"column:id;primary_key"`
Name string
FreezeAt time.Time `gorm:"column:freezeAt"`
Start time.Time
End time.Time
}
func (Contest) TableName() string {
return "Contests"
}
type User struct {
ID ... |
// 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 db
import (
_ "github.com/mattn/go-sqlite3"
"github.com/stretchr/testify/assert"
)
func (s *StoreSuite) TestGetHarvestablePlant() {
s.store.CreatePlantTypes()
s.store.CreateModuleWithPlants(1, "Basil")
s.store.CreateModuleWithPlants(2, "Lettuce")
inputs := []*PlantType{{Name: "Basil"}, {Name: "Lettuce"... |
// generated by jsonenums -type=Privacy -suffix=_enum; DO NOT EDIT
package schema
import (
"encoding/json"
"fmt"
)
var (
_PrivacyNameToValue = map[string]Privacy{
"PrivacyPersonal": PrivacyPersonal,
"PrivacyPublic": PrivacyPublic,
"PrivacyPrivate": PrivacyPrivate,
"PrivacyProtected": PrivacyProtecte... |
package main
import "github.com/miguelhun/go-microservices/src/api/app"
func main() {
app.StartApplication()
}
|
package main
import (
"bytes"
"math"
"os"
"path/filepath"
"strings"
)
const baseStaticURL = "http://localhost:8080/v1/MyCloud/static/"
const baseFilesURL = "http://localhost:8080/v1/MyCloud/files/"
const clientsBaseDir = "/home/orestis/MyCloud"
func getPathFromURLParam(par string) string {
dirs := strings.Spli... |
package config_test
import (
"testing"
"github.com/mjpitz/highlander-proxy/internal/config"
"github.com/stretchr/testify/require"
)
func TestRouteSlice(t *testing.T) {
const goodA = "tcp://0.0.0.0:8080|tcp://localhost:8080"
const goodB = "tcp://0.0.0.0:8090|tcp://localhost:8090"
const bad = "invalid:/address/... |
package main
import "fmt"
type Tree struct {
value int
left *Tree
right *Tree
}
func buildTree() Tree {
//return &Tree{4, Tree{2, Tree{1, nil, nil}, Tree{3, nil, nil}}, Tree{7, Tree{6, nil, nil}, Tree{9, nil, nil}}}
t := Tree{4, nil, nil}
t1 := Tree{2, nil, nil}
t2 := Tree{7, nil, nil}
t.left = &t1
t.right... |
package interfaceDemo
import "fmt"
// 如果接口里面有方法的话,必须要通过结构体或自定义类型实现这个接口
// 使用结构体来实现 接口
type Phone struct {
Name string
}
// 手机要实现Usber接口的话,必须实现usb接口的所有方法
func (p Phone) start() {
fmt.Println(p.Name, "启动")
}
func (p Phone) stop() {
fmt.Println(p.Name, "关闭")
}
func main() {
var phone Usber = Phone{
"三星手机",
}
... |
package zlog
import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"os"
)
type CutConf struct {
FileName string
MaxSize int
MaxBackups int
MaxAge int
Compress bool
LocalTime bool
BufferSize int //单位为m
}
func ZapCut(c CutConf, z zapcore.EncoderConfig, l zap.AtomicLevel) zapcore.Core {
lum := &Lo... |
package main
import (
"flag"
"log"
"time"
)
var configFile string
func init() {
flag.StringVar(&configFile, "configfile", "./config.toml", "file that will be parsed for configuration")
}
func main() {
flag.Parse()
config := readConfig()
CfVars := getCloudflareObjects(config)
log.Printf("Will check DNS rec... |
package migrationfiles
import (
logging "github.com/ipfs/go-log"
"github.com/syndtr/goleveldb/leveldb"
)
var log = logging.Logger("migrate-files")
// Initial00 Does nothing
func Initial00(db *leveldb.DB) error {
log.Infof("00Initial Migration Run successfully")
return nil
}
|
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
gin.SetMode(gin.ReleaseMode)
r := gin.Default() // router
r.LoadHTMLGlob("templates/*")
// http://localhost:8080/
r.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "root",
})
})
// http://l... |
package dolbutil_test
import (
"math/rand"
"sync"
. "github.com/bryanl/dolb/dolbutil"
. "github.com/onsi/ginkgo"
)
var _ = Describe("Random", func() {
It("is concurrency safe", func() {
rnd := rand.New(NewSource())
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
rnd.Int63... |
package main
import (
"fmt"
"time"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/mem"
)
func main() {
v, _ := mem.VirtualMemory()
fmt.Printf("Total: %v, Free:%v, UsedPercent:%f%%\n", v.Total, v.Free, v.UsedPercent)
percent, _ := cpu.Percent(time.Second, true)
fmt.Println(percent)
ccSay()
i... |
package main
/*
* @lc app=leetcode id=109 lang=golang
*
* [109] Convert Sorted List to Binary Search Tree
*/
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* ... |
// test-map project doc.go
/*
test-map document
*/
package main
|
// Code for running targets directly through Please.
package run
import (
"fmt"
"os"
"os/exec"
"strings"
"sync"
"syscall"
"golang.org/x/sync/errgroup"
"gopkg.in/op/go-logging.v1"
"build"
"core"
"output"
)
var log = logging.MustGetLogger("run")
// Run implements the running part of 'plz run'.
func Run(g... |
package main
import (
"fmt"
"time"
)
func display(ch chan int) {
time.Sleep(5 * time.Second)
fmt.Println("Inside display()")
ch <- 1234
}
func main() {
ch := make(chan int)
go display(ch)
x := <-ch
fmt.Println("Inside main()")
fmt.Println("Printing x in main() after taking from channel:", x)
}
|
package http
import (
"encoding/json"
"fmt"
"github.com/paddycakes/arranmore-api/internal/sensor"
"net/http"
)
import "github.com/gorilla/mux"
// Handler - stores pointer to metrics service
type Handler struct{
Router *mux.Router
Service *sensor.Service
}
// Response - an object to store responses from the ap... |
package blowcbc
import (
"crypto/blowfish"
)
func printBytes(pb []byte) {
for i := range pb {
print(pb[i], ",")
}
println("")
}
func padd(blocks []byte, bz byte) []byte {
// blocks length
bl := len(blocks)
p := bz - (byte(bl) % bz)
if p == 0 {
p = bz
}
padded := make([]byte, bl+int(p))
copy(padded... |
package server
import (
"log"
"time"
"github.com/gomodule/redigo/redis"
)
var (
redisPool *redis.Pool
statIncrScript *redis.Script = redis.NewScript(3, `
local skey = KEYS[1]
local sfield = KEYS[2]
local sexp = KEYS[3]
redis.call('HMSET', skey, sfield, 0)
redis.call('EXPIREAT', skey, sexp)
return red... |
/*
Copyright (c) 2017-2018 Simon Schmidt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribu... |
/*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "lice... |
package main
import (
"bufio"
"fmt"
"net/http"
"github.com/Symantec/Dominator/lib/html"
)
type adminDashboardType struct {
htmlWriter html.HtmlWriter
}
func newAdminDashboard(htmlWriter html.HtmlWriter) *adminDashboardType {
return &adminDashboardType{
htmlWriter: htmlWriter,
}
}
func (dashboard *adminDas... |
package point
import (
"fmt"
"math"
"sort"
)
// Point ...
type Point struct {
X float64 `json:"x"`
Y float64 `json:"y"`
}
type sortable struct {
pts []Point
less func(Point, Point) bool
}
// Sort ...
func Sort(pts []Point, less func(Point, Point) bool) {
s := sortable{pts, less}
sort.Sort(s)
}
// Find ..... |
package metadata
import (
"strconv"
"encoding/json"
"incognito-chain/common"
metadataCommon "incognito-chain/metadata/common"
)
// PDEWithdrawalRequest - privacy dex withdrawal request
type PDEWithdrawalRequest struct {
WithdrawerAddressStr string
WithdrawalToken1IDStr string
WithdrawalToken2IDStr string
Wi... |
package controller
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/oceanpkg/ocean-backend/internal/auth"
"github.com/oceanpkg/ocean-backend/internal/database"
"github.com/oceanpkg/ocean-backend/internal/util"
)
//UserData is a struct that defines the data format for the post request for a new user... |
package controller
import (
"encoding/json"
"entity"
"github.com/gorilla/mux"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"usecase"
)
type PdaController struct {
PdaManager usecase.PDAManager
}
func (pdaController *PdaController) ListAllPDA(writer http.ResponseWriter, request *http.Request) {
nam... |
package main
import (
"fmt"
)
func main() {
upperTriangle()
bottomTriangle()
}
func upperTriangle() {
output := ""
inputValue := 5
for i := 0; i < inputValue; i++ {
for j := inputValue; j > i; j-- {
output += " "
}
for k := 0; k <= i; k++ {
output += "* "
}
for l := 0; l < i; l++ {
output ... |
package rbt
import (
"testing"
"math/rand"
"time"
)
var _,_ = rand.Seed, time.Now
// fill rbtree with random numbers as keys
func newtree(t *testing.T, iters int) *RbMap {
rand.Seed(time.Now().UnixNano())
// rb tree with integer keys
r := NewRbMap(func(k1, k2 interface{}) bool {
retur... |
package logdir
import (
"fmt"
"os"
"path/filepath"
"sync"
"github.com/wchargin/tensorboard-data-server/fs"
"github.com/wchargin/tensorboard-data-server/io/run"
)
// LoaderBuilder specifies options for a Loader.
type LoaderBuilder struct {
// FS is the filesystem to use for read operations.
FS fs.Filesystem
... |
package fstack_test
import (
"bytes"
"io/ioutil"
"os"
"testing"
"github.com/Komosa/fstack"
)
func TestNonMod(t *testing.T) {
f, err := ioutil.TempFile("", "fstack_test_file")
fatalMaybe(err, t)
defer os.Remove(f.Name())
data := []byte(`bottom
middle
top
`)
_, err = f.Write(data)
f.Close()
fatalMaybe(err... |
package profile
import (
"os"
"testing"
)
func TestWriteOne(t *testing.T) {
db := JsonFileDb{path: "/tmp/test_jsondb"}
var err error
profile := Profile{Name: "1", Email: "jsahd@as.com"}
os.Create(db.path)
if err = db.WriteProfiles([]Profile{profile}); err != nil {
t.Errorf("Can't write one profile: %s", err... |
package crawl
import (
"time"
. "./base"
)
type Tdatas struct {
Data []Tdata `json:"data"`
Typing typing_parser
Segment segment_parser
Hub hub_parser
tag string
start time.Time
min_hub_height int
base, next *Tdatas
}
func (p *typing_parser) tail(s *typing_parser, tail int) {
if l := len(p... |
package block
import (
"errors"
"time"
"bytes"
"encoding/binary"
"reflect"
"github.com/jasoncodingnow/bitcoinLiteLite/consensus"
"github.com/jasoncodingnow/bitcoinLiteLite/crypto"
"github.com/jasoncodingnow/bitcoinLiteLite/tool"
)
type TransactionHeader struct {
From []byte
To []byte
Pa... |
package config
import (
"fmt"
"io/ioutil"
"time"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/prometheus/common/promlog"
yaml "gopkg.in/yaml.v2"
graphite "github.com/criteo/graphite-remote-adapter/client/graphite/config"
"github.com/criteo/graphite-remote-adapter/utils"
)
// Lo... |
package main
import (
"net/http"
)
type NotFoundRedirectRespWr struct {
http.ResponseWriter // We embed http.ResponseWriter
status int
}
func (w *NotFoundRedirectRespWr) WriteHeader(status int) {
w.status = status // Store the status for our own use
if status != http.StatusNotFound {
w.ResponseWr... |
package main
import "fmt"
func main() {
fmt.Println("Perform String Shifts")
stringShift("abc", [][]int{{0, 4}, {1, 5}})
// stringShift("abcdefg", [][]int{{1, 1}, {1, 1}, {0, 2}, {1, 3}})
}
func stringShift(s string, shift [][]int) string {
r, l, pos := []rune(s), len(s), 0
for _, val := range shift {
val[1]... |
// Go support for Protocol Buffers RPC which compatiable with https://github.com/Baidu-ecom/Jprotobuf-rpc-socket
//
// Copyright 2002-2007 the original author or 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 ... |
package cache
import (
"time"
"github.com/patrickmn/go-cache"
)
var cacheInstance *cache.Cache = nil
func getInstance() *cache.Cache {
if cacheInstance != nil {
cacheInstance = cache.New(5*time.Minute, 30*time.Second)
}
return cacheInstance
}
func set(key string, value interface{}) {
cacheInstance.Set(key,... |
package broker
import (
"bytes"
"fmt"
"log"
"net"
"net/rpc"
"os/exec"
"sync"
"time"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/mem"
"github.com/c12o16h1/shender/pkg/models"
)
const (
MAX_CPU_LOAD float64 = 60 // Max acceptable load for CPU
MAX_MEMORY_USAGE float64 = 75 // Max acce... |
package domain
// UnbindRequest encapsulates the request payload information
// for an unbind request.
type UnbindRequest struct {
// BindingID is the ID value for the service binding
// represented by this unbind request.
BindingID string
// InstanceID is the ID value for the service instance
// to be unbound i... |
package constants
import "errors"
var (
StatusActive = 1
StatusInActive = 0
GetItemsLimit = int64(100)
ERRPRODUCTUNAVAILABLE = errors.New("sorry this product is unavailable")
)
|
package main
import (
"bufio"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/jungju/circle_manager/modules"
)
var beegoAppProcess *os.Process
func genBeegoAppResource() error {
fmt.Println("Starting app of beego")
if err := beegoBuild(); err != nil {
return err
}... |
package decorators
import (
"fmt"
"sort"
"strings"
"github.com/itchyny/gojq"
"github.com/mitchellh/mapstructure"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
... |
// Package main -
package main
import (
"bytes"
"fmt"
"sync"
"sync/atomic"
"time"
)
func main() {
fmt.Println("vim-go")
cadence := sync.NewCond(&sync.Mutex{})
go func() {
for range time.Tick(1 * time.Millisecond) {
cadence.Broadcast()
}
}()
takeStep := func() {
cadence.L.Lock()
cadence.Wait()
... |
package concurrent
import (
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestForeach(t *testing.T) {
slice := []int{1, 2, 3, 4, 5}
require.NoError(t, Foreach(slice, func(i int, v interface{}) error {
t.Logf("slice[%d]=%v start", i, v)
time.Sleep(20 * time.Millisecond)
t.Logf("slice[%d]=%v... |
// Copyright 2020 MongoDB 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 in... |
package main
import (
"log"
"net"
pb "../pb"
"../service"
"google.golang.org/grpc"
)
func main() {
listenPort, err := net.Listen("tcp", ":8888")
if err != nil {
log.Fatalln(err)
}
server := grpc.NewServer()
Service := &service.MyService{}
// 実行したい実処理をseverに登録する
pb.RegisterMyServiceServer(server, Servi... |
package main
import (
"testing"
"time"
"github.com/abiosoft/semaphore"
"github.com/eclipse/paho.mqtt.golang"
)
type FakeMQTTMessage struct {
duplicate bool
qos byte
retained bool
topic string
messageID uint16
payload []byte
}
func (m FakeMQTTMessage) Duplicate() bool {
return m.duplicate
}
... |
package main
import "encoding/json"
import "log"
import "net/http"
import "github.com/gorilla/mux"
//init
var pets []Pet
//Struct for Pet
type Pet struct {
Name string `json:"name"`
Animal string `json:"animal"`
Weight float64 `json:"weight"`
Age int `json:"age"`
Owner *Owner `json:"owner"`
}
//Struct for Ow... |
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"os"
"os/exec"
"strings"
"time"
)
func main() {
if len(os.Args) < 3 {
fmt.Println("Usage: killmyslave user pass [port]")
return
} else {
user := os.Args[1]
pass := os.Args[2]
port := "3306"
if len(os.Args) >= 4 {
por... |
package confobject
import (
"github.com/smartystreets/assertions/should"
)
type Assertion func(actual interface{}, expectedList ...interface{}) string
func Assert(actual interface{}, assert Assertion, expected ...interface{}) (bool, string) {
if result := so(actual, assert, expected...); len(result) == 0 {
retur... |
package utils
import (
"reflect"
"testing"
)
func AssertArraysEqual(t *testing.T, expected []int, result []int) {
if len(expected) != len(result) || !reflect.DeepEqual(expected, result) {
fail(t, "Arrays were not equal", expected, result)
}
}
func AssertEqual(t *testing.T, values ...interface{}) {
if (len(val... |
package main
import "fmt"
// Node 节点
type Node struct {
Val int
Left int
Right int
}
// TreeNode 二叉树
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// preorderTraversalRecusive 前序遍历递归法
func preorderTraversalRecusive(root *TreeNode) {
if root == nil || root.Val == 0 ... |
package main
import (
"database/sql"
"fmt"
"net"
"os"
"os/signal"
"syscall"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
kitoc "github.com/go-kit/kit/tracing/opencensus"
kitgrpc "github.com/go-kit/kit/transport/grpc"
"github.com/oklog/oklog/pkg/group"
"google.golang.org/grpc"
"github.co... |
package dao
import (
"fmt"
"github.com/xormplus/xorm"
"go.uber.org/zap"
"mix/test/codes"
entity "mix/test/entity/core/transaction"
mapper "mix/test/mapper/core/transaction"
"mix/test/utils/status"
)
func (p *Dao) CreateBalance(logger *zap.Logger, session *xorm.Session, item *entity.Balance) (id int64, err err... |
package totp
import (
"encoding/base32"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/authelia/authelia/v4/internal/configuration/schema"
)
func TestTOTPGenerateCustom(t *testing.T) {
testCases := []struct {
desc string
user... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2021/6/22 8:48 上午
# @File : lt_二分_搜索插入位置.go
# @Description :
# @Attention :
*/
package v2
func searchInsert(nums []int, target int) int {
start := 0
end := len(nums) - 1
for start+1 < end {
mid := start + (end-start)>>1
if nums[mid] > target {
end = mid
... |
package azure
// Metadata contains Azure metadata (e.g. for uninstalling the cluster).
type Metadata struct {
ARMEndpoint string `json:"armEndpoint"`
CloudName CloudEnvironment `json:"cloudName"`
Region string `json:"region"`
ResourceGroupN... |
package graphql_test
import (
"testing"
"github.com/graphql-go/graphql"
"github.com/graphql-go/graphql/gqlerrors"
"github.com/graphql-go/graphql/language/ast"
"github.com/graphql-go/graphql/language/location"
"github.com/graphql-go/graphql/language/parser"
"github.com/graphql-go/graphql/language/source"
"gith... |
package main
import "fmt"
type rect2 struct{
width, height int
}
func (r *rect2) area() int {
return r.width * r.height
}
func (r rect2) perim() int {
return 2*r.width + 2*r.height
}
func main() {
r := rect2{width:10, height:5}
fmt.Println("area ",r.area())
fmt.Println("perim ",r.perim())
rp := &r
fmt.Pr... |
package noopencryptor
func New() NoopEncryptor {
return NoopEncryptor{}
}
type NoopEncryptor struct{}
func (d NoopEncryptor) Encrypt(plaintext []byte) (string, error) {
return string(plaintext), nil
}
func (d NoopEncryptor) Decrypt(ciphertext string) ([]byte, error) {
return []byte(ciphertext), nil
}
|
package main
import "net/http"
import "sync"
func main() {
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {})
var servers sync.WaitGroup
servers.Add(1)
go func() {
defer servers.Done()
http.ListenAndServe(":1024", nil)
}()
servers.Add(1)
go func() {
defer servers.Done()
http.Li... |
package comment
import (
"github.com/labstack/echo"
// HOFSTADTER_START import
// HOFSTADTER_END import
)
// HOFSTADTER_START const
// HOFSTADTER_END const
// HOFSTADTER_START var
// HOFSTADTER_END var
// HOFSTADTER_START init
// HOFSTADTER_END init
func InitRouter(G *echo.Group) (err error) {
// HOFS... |
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
)
type User struct {
UserID string
Score int
}
func getUserAPI(w http.ResponseWriter, r *http.Request) {
user, err := getUser(mux.Vars(r)["user"])
if err != nil {
user = &User{
UserID: mux.Vars(r)["user"],
Score: 0,
... |
// Copyright (c) 2018 IoTeX
// This is an alpha (internal) release and is not suitable for production. This source code is provided 'as is' and no
// warranties are given as to title or non-infringement, merchantability or fitness for purpose and, to the extent
// permitted by law, all liability for your use of the cod... |
//go:generate mockgen -source interface.go -destination product_mock.go -package product
package product
import "github.com/markus-azer/products-service/pkg/entity"
//MessagesReader Reader interface
type messagesReader interface {
}
//MessagesWriter product writer
type messagesWriter interface {
SendMessage(m *ent... |
package repository
import (
"fmt"
"github.com/jmoiron/sqlx"
"github.com/rs/zerolog/log"
"sitemap/models/entity"
"time"
)
func NewSQLCompanyRepo(Conn *sqlx.DB) *DbCompanyRepo {
return &DbCompanyRepo{
Conn: Conn,
}
}
type DbCompanyRepo struct {
Conn *sqlx.DB
}
func (l *DbCompanyRepo) Count()(int, error){
t... |
package mysql
import "fmt"
type Config struct {
Host string
Port int
User string
Pass string
DB string
}
func (cfg Config) DSN() string {
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?parseTime=true&interpolateParams=true&allowNativePasswords=true",
cfg.User, cfg.Pass, cfg.Host, cfg.Port, cfg.DB)
}
|
package main
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
func main() {
db, err := gorm.Open("postgres", "user=postgres password=tp2u6jQbdM dbname=deneme sslmode=disable")
if err != nil {
panic(err.Error())
}
defer db.Close()
dbase := db.DB()
defer dbase.Close()
err = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.