text stringlengths 11 4.05M |
|---|
package main
import (
"fmt"
)
func main() {
cities := []string{}
cities = append(cities, "San Diego", "Mountain View")
fmt.Printf("%q\n", cities)
}
|
// Package chanutil implements methods for working with channels.
package chanutil
|
package prompt
import (
"bytes"
"testing"
)
func TestVT100WriterWrite(t *testing.T) {
scenarioTable := []struct {
input []byte
expected []byte
}{
{
input: []byte{0x1b},
expected: []byte{'?'},
},
{
input: []byte{'a'},
expected: []byte{'a'},
},
}
for _, s := range scenarioTable {... |
package main
import (
"net/http"
)
type Adapter func(http.HandlerFunc) http.HandlerFunc
// InitRoutes to start up a mux router and return the routes
func InitRoutes() *http.ServeMux {
serveMux := http.NewServeMux()
//pingpong
serveMux.HandleFunc("/ping", Adapt(PingPong, ValidateRestMethod("GET")))
serveMux.Han... |
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
var message string
func main() {
message = "Hello World"
fmt.Println("Hello world")
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.String(200, message)
})
r.POST("/post", func(c *gin.Context) {
if len(c.Query("message")) > 0 {
messag... |
package sudoku
import (
"math"
"math/rand"
"testing"
)
const _NUM_RUNS_TEST_WEIGHTED_DISTRIBUTION = 10000
const _ALLOWABLE_DIFF_WEIGHTED_DISTRIBUTION = 0.01
func TestInvertingReallyReallyBigDistribution(t *testing.T) {
//In practical use, Guess technique's non-inverted value is like absurdly
//large and leads t... |
package main
// 贪心:
// 1、先将数组分别加上下标得到每个位置可以跳跃到的位置(可以省去,直接在遍历的时候计算)
// 2、要跳到的位置应尽可能远,因此要在满足约束的条件下,用max_dist记录最大可以跳跃的距离
// 3、约束条件为索引i<=max_dist,因为这样才能保证连续跳跃,即从位置0到当前位置,也即之前的元素可以跳跃到当前的位置
func canJump(nums []int) bool {
n := len(nums)
max_dist := nums[0]
for i := 0; i < n; i++ {
if i > max_dist {
return false
}
... |
package commands
import (
"log"
"sync"
"time"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"github.com/andreyvit/mongobulk"
api "github.com/michigan-com/gannett-newsfetch/gannettApi"
m "github.com/michigan-com/gannett-newsfetch/model"
)
func GetArticles(session *mgo.Session, siteCodes []string, gannettSearchAPI... |
package service
import (
"context"
pb "github.com/johnbellone/persona-service/internal/gen/persona/api/v1"
ptypes "github.com/johnbellone/persona-service/internal/gen/persona/type"
"github.com/johnbellone/persona-service/internal/server"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type Rol... |
/*
Copyright 2020 Gravitational, 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 writing, soft... |
package main
import "testing"
func TestCalculate(t *testing.T) {
var tests = []struct {
date string
frame string
handlebar string
gear int64
geargrip int64
seating int64
seatingbottle int64
wheels string
spokes int64
rim int64
tube int64
tyre string
chain string
}{... |
package cain
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document01000101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:cain.010.001.01 Document"`
Message *NetworkManagementResponse `xml:"NtwkMgmtRspn"`
}
func (d *Document01000101) Ad... |
package mappers
import (
"fmt"
"github.com/vfreex/gones/pkg/emulator/memory"
"github.com/vfreex/gones/pkg/emulator/rom/ines"
)
type NROMMapper struct {
mapperBase
prgBankMapping [2]int
}
func init() {
MapperConstructors[0] = NewNROMMapper
}
func NewNROMMapper(rom *ines.INesRom) Mapper {
p := &NROMMapper{}
p... |
/* A testing script written for backspaceCompare function */
package backspaceCompare
import "testing"
func Test(t *testing.T) {
var tests = []struct {
s, t string
want bool
}{
{"ab#c", "ad#c", true},
{"ab##", "c#d#", true},
{"a##c", "#a#c", true},
{"a#c", "b", false},
{"", "aaaaa#####", true},
{"g... |
package main
import (
"strconv"
"strings"
)
/*
* @lc app=leetcode id=257 lang=golang
*
* [257] Binary Tree Paths
*/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func binaryTreePaths(root *TreeNode) []string {
var res []... |
package api
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/julienschmidt/httprouter"
)
// RouteHandler describes objects which handle requests from specific HTTP
// endpoints.
type RouteHandler interface {
RegisterRoutes(*httprouter.Router)
}
// StartServer registers all routes for RouteHandler o... |
package main
import (
"fmt"
"bufio"
"os"
"log"
"strconv"
"strings"
"github.com/pitex/sieci-projekt/src/joinservice"
)
// Main function:
// First it creates Client and asks for address to connect to.
// After receiving address it creates a server and starts it.
func main() {
reader := bufio.NewReader(os.Stdin)... |
package operatorlister
import (
"fmt"
"sync"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"github.com/operator-framework/api/pkg/operators/v1alpha1"
listers "github.com/operator-framework/operator-lifecycle-manager/pkg/api/client/listers/operat... |
// Package header provides a request header based implementation of a
// session loader.
package header
import (
"net/http"
"strings"
"github.com/pomerium/pomerium/internal/encoding"
"github.com/pomerium/pomerium/internal/httputil"
"github.com/pomerium/pomerium/internal/sessions"
)
var _ sessions.SessionLoader ... |
package Modules
type VpsInfo struct {
Time uint
Count uint
Name string
Ip string
Backend string
}
type global struct {
Online map[string]*VpsInfo
Offline map[string]int64
}
var Global global
func (a *global) Init() {
a.Online = make(map[string]*VpsInfo, 0)
a.Offline = make(map[string]int64, 0... |
package main
import (
"github.com/beego/beego/v2/client/orm"
_ "github.com/mattn/go-sqlite3"
)
// User -
type User struct {
ID int `orm:"column(id)"`
Name string `orm:"column(name)"`
}
func init() {
// need to register models in init
orm.RegisterModel(new(User))
// need to register db driver
orm.Regist... |
package app
import (
"net/http"
"time"
"appengine/datastore"
"github.com/PinkFairyArmadillos/go-endpoints/endpoints"
)
const clientId = "755334619802-7mgbbpk6vbkmim76ov2kvi0vn607j2cu.apps.googleusercontent.com"
var (
scopes = []string{
endpoints.EmailScope,
"https://www.googleapis.com/auth/userinfo.profile"... |
package certgen
var DeploymentName string
// SetDeploymentName saves the name of the deployment
func SetDeploymentName(deploymentname string) {
DeploymentName = deploymentname
}
// GetDeploymentName - Returns the name of the current Deployment
func GetDeploymentName() string {
return DeploymentName
}
... |
// Copyright 2016 Kranz. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package base
import (
"path"
"strconv"
"strings"
)
func PathToUrl(p string) string {
p = strings.Replace(p, path.Ext(p), "", 1)
p = strings.Replace(p, "__", "#", ... |
package main
import (
"log"
"os"
"os/exec"
"os/signal"
"syscall"
)
func handleSigchld(c <-chan os.Signal) {
log.Println("process reaper launching")
for {
_ = <-c
for {
st := new(syscall.WaitStatus)
pid, err := syscall.Wait4(-1, st, syscall.WNOHANG, nil)
if pid == 0 || err == syscall.ECHILD {
b... |
package v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
)
// TraceJobSpec defines the desired state of TraceJob
type TraceJobSpec struct {
// Program is a string literal to evaluate as a bpftrace program.
Program string `json:"program"`
Hostname ... |
package validate
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
v1beta1 "k8s.io/api/admission/v1beta1"
)
func TestValidateJSON(t *testing.T) {
rawJSON := `{
"kind": "AdmissionReview",
"apiVersion": "admission.k8s.io/v1",
"request": {
"uid": "07ea6264-e624-439b-83d0-f7724106ec1... |
package main
import (
"fmt"
"jblee.net/adventofcode2018/utils"
)
func toLower(c byte) byte {
if c >= 'A' && c <= 'Z' {
return 'a' + (c - 'A')
}
return c
}
func cancelOut(a, b byte) bool {
aLower := toLower(a)
bLower := toLower(b)
return aLower == bLower && a != b
}
func main() {
line := utils.ReadLinesO... |
package middleware
import (
"github.com/gin-gonic/gin"
"go-admin/global"
"go-admin/models"
"go-admin/utils/response"
"net/http"
)
func CasbinHandler() gin.HandlerFunc {
return func(c *gin.Context) {
claims, _ := c.Get("claims")
waitUse, ok := claims.(*models.CustomClaims)
if !ok {
response.Result(http.... |
package popgun
import (
"bufio"
"fmt"
"io/ioutil"
"net"
"reflect"
"testing"
"time"
"github.com/DevelHell/popgun/backends"
)
func TestClient_handle(t *testing.T) {
s, c := net.Pipe()
defer s.Close()
defer c.Close()
backend := backends.DummyBackend{}
authorizator := backends.DummyAuthorizator{}
client :... |
package worker
import (
"FoG/src/github.com/cl/crontab/common"
"context"
"fmt"
clientv3 "go.etcd.io/etcd/client/v3"
)
type JobLock struct {
//基于etcd实现分布式锁
kv clientv3.KV
lease clientv3.Lease
jobName string
leaseId clientv3.LeaseID // 租约ID,记录之后,后续取消
cancelFunc context.CancelFunc // 取消函数 ,后续基于该函数来取消续约
isLo... |
package NFA
import (
"fmt"
"testing"
)
func TestDFA(t *testing.T) {
rulebook := DFARulebook{Rules: []DFARule{{
State: 2,
Character: 'b',
NextState: 3,
}, {
State: 2,
Character: 'a',
NextState: 3,
}, {
State: 1,
Character: 'b',
NextState: 1,
}, {
State: 1,
Character: 'a',
... |
package main
import (
"fmt"
)
func main() {
// buffer size is 2 i.e. at max 2 values can be stored(or kept) in the channel
c := make(chan int, 2)
c <- 42
c <- 43
// will not work as the channel size is 2, so before putting any new value
// atlease one value needs to be extracted from the... |
package cli
import (
"fmt"
"strings"
sdk "github.com/cosmos/cosmos-sdk/types"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
paramscutils "github.com/cosmos/cosmos-sdk/x/params/client/utils"
paramproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal"
"github.com/gookit/gcli/v3"
"github.com/ovrcl... |
package faterpg
//Game represent game
type Game struct {
Name string
Description string
GM *GM
Players []*Player
Aspects []*Aspect
}
//NewGame create new game
func NewGame() *Game {
return &Game{}
}
//IsReady return game ready to play or not
func (game *Game) IsReady() bool {
haveGM :=... |
package stmanager_test
import (
"testing"
"manager/stmanager"
)
func Test_StockHistDataManager(t *testing.T) {
m := stmanager.NewStockHistDataManager()
m.Process()
}
|
package enfins
import (
"testing"
"fmt"
"net/http"
)
var cfg *Configuration
var client *APIClient
func init() {
cfg = &Configuration{
"http",
"62.80.163.18:9000",
"GEpcqDRSwB",
"gF-GnQZMayC1PJ0rvAU5",
"v1",
nil,
}
var err error
client = &APIClient{
cfg,
http.DefaultClient,
}
if err != nil {... |
package main
import (
"bufio"
"flag"
"fmt"
"os"
)
func main() {
filePath := flag.String("p", "input.txt", "Input's file path")
flag.Parse()
f, err := os.Open(*filePath)
if err != nil {
fmt.Fprintf(os.Stderr, "Opening input file: %v\n", err)
os.Exit(1)
}
defer f.Close()
scanner := bufio.NewScanner(f)
... |
/*
Background
A linear recurrence relation is a description of a sequence, defined as one or more initial terms and a linear formula on last k terms to calculate the next term.
(For the sake of simplicity, we only consider homogeneous relations, i.e. the ones without a constant term in the formula.)
A formal definit... |
package resto
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"time"
"github.com/rs/zerolog/log"
"github.com/ryanuber/go-glob"
"github.com/saucelabs/saucectl/internal/config"
"github.com/saucelabs/saucectl/internal/job"
"github.com/sa... |
/*
* Copyright (c) 2018 Juniper Networks, Inc. All rights reserved.
*
* file: ipfix_dm.go
* details: IPFIX packet handler for Data Manager
*
*/
package msghandler
import (
"bytes"
"encoding/json"
opts "github.com/Juniper/collector/flow-translator/options"
)
// Message represents IPFIX message
type IPFIXDM... |
package executor
import "fmt"
type Config struct {
Host string
Port int
User string
Password string
DB string
Options string
}
func (c *Config) DSN() string {
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?%s", c.User, c.Password, c.Host, c.Port, c.DB, c.Options)
}
func (c *Config) Address() stri... |
package utils
import (
"bytes"
)
// StringsInsertRuneStep ...
func StringsInsertRuneStep(s string, step int, sep string) string {
buffer := bytes.Buffer{}
before := step - 1
last := len(s) - 1
for i, char := range s {
buffer.WriteRune(char)
if i%step == before && i != last {
buffer.WriteString(sep)
}
}... |
package benchmarks
import (
"net/url"
"testing"
"github.com/go-playground/form/v4"
)
// Simple Benchmarks
type User struct {
FirstName string `form:"fname" schema:"fname" formam:"fname"`
LastName string `form:"lname" schema:"lname" formam:"lname"`
Email string `form:"email" schema:"email" formam:"email"`... |
package agent
import (
"encoding/json"
"time"
"dudu/models"
"dudu/modules/collector"
_ "dudu/modules/collector/collect"
)
// 初始化采集管理器
func (app *AgentNode) initCollect() error {
app.collectorMag = collector.NewCollectorManager(app.logger, app.cfg.Agent.Collects)
return nil
}
// 开始采集
func (app *AgentNode) sta... |
package server
import (
"net/http"
"github.com/UnnecessaryRain/ironway-core/pkg/network/client"
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func... |
// Copyright © 2019 Banzai Cloud
//
// 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 ... |
package main
import "fmt"
func nonempty(strings []string) []string {
i := 0
for _, s := range strings {
if s != "" {
strings[i] = s
i++
}
}
return strings[:i]
}
func nonempty2(strings []string) []string {
out := strings[:0]
for _, s := range strings {
if s != "" {
out = append(out, s)
}
... |
package local_test
import (
"bytes"
"compress/gzip"
"context"
"io"
"io/ioutil"
"math/rand"
"os"
"reflect"
"strings"
"testing"
"time"
"github.com/fishy/fsdb"
"github.com/fishy/fsdb/local"
)
const lorem = `Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore ... |
// app
package core
import (
"context"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"os/signal"
"strings"
"time"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/rpc"
"caige/componnet"
"caige/database"
"caige/schedule-service"
"comment/constant"
"comment/job"
"github.co... |
package main
import "fmt"
func main() {
mySlice := make([]int, 0, 3)
fmt.Println("-----------------")
fmt.Println(mySlice)
fmt.Println(len(mySlice))
fmt.Println(cap(mySlice))
fmt.Println("-----------------")
for i := 0; i < 80; i++ {
mySlice = append(mySlice, i)
fmt.Println("Len:", len(mySlice), "Capaci... |
package mosquito
import (
"net/http"
)
var server *Server
type Method string
type Server struct {
middlewares []Middleware
routes []*Route
}
func (server *Server) Use(middleware Middleware) *Server {
server.middlewares = append(server.middlewares, middleware)
return server
}
func (server *Server) Get(... |
package proxy
import (
"net/http"
"net/http/httputil"
"net/url"
"strings"
)
func HTTP(target *url.URL) http.Handler {
return &httputil.ReverseProxy{
Director: func(req *http.Request) {
req.Host = target.Host
req.URL.Host = target.Host
req.URL.Scheme = target.Scheme
req.URL.Path = singleJoiningSlash... |
package controller
import (
"encoding/json"
"net/http"
"strconv"
"github.com/fernandoporazzi/yak-shop/app/entity"
"github.com/fernandoporazzi/yak-shop/app/errors"
"github.com/fernandoporazzi/yak-shop/app/service"
"github.com/go-chi/chi/v5"
)
type StockController interface {
GetData(response http.ResponseWrit... |
package http_server
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"github.com/jsagl/go-from-scratch/models"
"github.com/jsagl/go-from-scratch/usecase"
"go.uber.org/zap"
"net/http"
"strconv"
)
type RecipeHandler struct {
logger *zap.SugaredLogger
usecase usecase.RecipeUseCaseInterface
}
func NewRe... |
package main
// import (
// "encoding/json"
// "errors"
// "log"
// "net/url"
// "strings"
// "time"
// )
// // "title": "L'avantage d'innover \u00e0 l'\u00e9tat pur",
// // "uri": "http://www.hood.net/about.html",
// // "date": "March 30 1985"
// func (it *Item) UnmarshalJSON(j []byte) error {
// var timeFo... |
package main
import (
"fmt"
)
func (b *Brain) InputNeurons() map[string]*Neuron {
r := map[string]*Neuron{}
for _, n := range b.Neurons {
if n.Role == Role_input {
r[n.Id] = n
}
}
return r
}
func (b *Brain) OutputNeurons() map[string]*Neuron {
r := map[string]*Neuron{}
for _, n := range b.Neurons {
i... |
package setr
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document01200102 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:setr.012.001.02 Document"`
Message *SubscriptionMultipleOrderConfirmationV02 `xml:"setr.012.001.02"`... |
package main
import "fmt"
import "math"
func main() {
for n := 1; n < 500; n++ {
for m := (n + 1); m < 500; m++ {
a := int(math.Pow(float64(m), 2) - math.Pow(float64(n), 2))
b := 2 * m * n
c := int(math.Pow(float64(m), 2) + math.Pow(float64(n), 2))
if a+b+c == 1000 {
product := a * b * c
fmt.Pr... |
package main
import (
"fmt"
"net/http"
"time"
)
// Program to check website status. Make http request and print if site is up or down.
func main() {
links := []string {
"http://google.com",
"http://facebook.com",
"http://stackoverflow.com",
"http://golang.org",
"http://amazon.com",
}
// Create a chan... |
package main
// dp[i][t] 表示从(0,0)走到(i,t)的不同路径数
// 状态转移方程:
// i == 0 && t == 0: dp[i][t] = 1 (初始状态)
// i == 0 && t != 0: dp[i][t] = dp[0][t-1] (表示只能从上边走到该点)
// i != 0 && t == 0: dp[i][t] = dp[i-1][0] (表示只能从左边走到该点)
// i >= 1 && t >= 1: dp[i][t] = dp[i-1][t] + dp[i][t-1] (表示只能从左边或上边走到该点)
func uniq... |
//一些注意事项
//测试程序文件名以_test结尾
//import测试包testing
//测试函数以Test开头
package main
import (
"testing"
)
func Test_Division(t *testing.T) { //test.T记录错误或测试状态
i, err := Division(6, 2)
if i != 3 || err != nil {
t.Error("除法测试没通过!")
} else {
t.Log("第一个测试通过了!")
}
}
func Benchmark_Divisionb(b *testing.B) { //testing.B数据很有用
... |
package chunk_test
import (
"bytes"
"io"
"testing"
"github.com/tombell/go-serato/serato/chunk"
)
func TestNewVrsnChunk(t *testing.T) {
data := generateBytes(t, "7672736E0000003C0031002E0030002F00530065007200610074006F002000530063007200610074006300680020004C0049005600450020005200650076006900650077")
buf := byte... |
package model
import (
"testing"
"tpay_backend/test"
)
func TestUpstreamModel_FindOneByUpstreamMerchantNo(t *testing.T) {
upstreamModel := NewUpstreamModel(test.DbEngine)
upMerchantNo := "3d2f9bb9-f370-412e-91fb-d011f76706f3"
got, err := upstreamModel.FindOneByUpstreamMerchantNo(upMerchantNo)
t.Logf("err:%v"... |
package controllers
import (
"message/models"
"strconv"
"github.com/astaxie/beego"
"github.com/astaxie/beego/session"
)
// Operations about Users
type UserController struct {
beego.Controller
}
// Cookie
var globalSessions *session.Manager
func init() {
globalSessions, _ = session.NewManager("memory", `{"coo... |
package leetcode
/*Given head which is a reference node to a singly-linked list.
The value of each node in the linked list is either 0 or 1.
The linked list holds the binary representation of a number.
Return the decimal value of the number in the linked list.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/con... |
package config
import (
"github.com/Azer0s/quacktors/logging"
)
//SetLogger sets the Logger implementation used by quacktors.
//(LogrusLogger by default)
func SetLogger(l logging.Logger) {
logger = l
}
//GetLogger gets the configured Logger implementation.
func GetLogger() logging.Logger {
return logger
}
//SetQ... |
package config
import (
"fmt"
"database/sql"
"reflect"
"unsafe"
"strconv"
"errors"
"strings"
)
type ConfigDB struct {
DriverName string
Dbhost string
Dbport string
Dbuser string
Dbpassword string
Dbname string
Tblname string
}
func (c *ConfigDB) GetParameters(ic Parameter) error {
... |
package scache
import (
"sync/atomic"
)
type timer struct {
value *uint32
}
func newTimer() *timer {
var value uint32
return &timer{value: &value}
}
func (t *timer) Tick() (v uint32) {
v = atomic.AddUint32(t.value, 1)
return
}
func (t *timer) Value() (v uint32) {
v = atomic.LoadUint32(t.value)
return
}
|
package queries
import (
"log"
"github.com/jmoiron/sqlx"
"gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/configuration"
"gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/energy_resources/models"
)
const GET_ENERGY_RESOURCES_SQL = `
SELECT
*
FROM
energy_resources."EnergyResour... |
package infra
import "fmt"
func init() {
Register(&ConfStarter{})
}
type ConfStarter struct {
BaseStarter
}
func (c *ConfStarter)Init(ctx StarterContext) {
fmt.Println("配置初始化")
}
func (c *ConfStarter)Setup(ctx StarterContext) {
fmt.Println("配置安装")
}
func (c *ConfStarter)Start(ctx StarterContext) {
fmt.Prin... |
package db
import (
"errors"
"time"
"github.com/jackc/pgx"
"github.com/brianvoe/gofakeit/v5"
)
type Club struct {
ID uint `db:"id"`
InsertedAt *time.Time `db:"inserted_at"`
UpdatedAt *time.Time `db:"updated_at"`
OwnerID string `db:"owner_id"`
RoleID *string `db:"role_id"`
... |
package repos
import (
"fmt"
"os"
"path/filepath"
"testing"
"time"
"github.com/au/com/cybernostics/crowdscore/server/services"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
var (
DB *gorm.DB
)
func init() {
user := services.User{}
var err error
DB, err = gorm.Open("sqlite3", file... |
package passwordcombiner
import (
"fmt"
"github.com/cloudfoundry-incubator/cloud-service-broker/internal/encryption/gcmencryptor"
)
// CanaryInput is the value that is encrypted with the key and stored in the database
// to check that the key has not changed. Because we encrypt with a nonce, it's not
// possible t... |
package funciones
import (
"fmt"
)
// Saludar .
func Saludar(name string) {
fmt.Println("Hola", name)
}
// Despedirse .
func Despedirse(name string) {
fmt.Println("Adios", name)
}
|
package main
import (
"context"
"os"
"regexp"
"time"
"github.com/SentientTechnologies/studio-go-runner/internal/runner"
"github.com/SentientTechnologies/studio-go-runner/internal/types"
"github.com/go-stack/stack"
"github.com/prometheus/client_golang/prometheus"
)
// This file contains the implementation of ... |
package app
import (
"fmt"
"github.com/callumj/weave/core"
"github.com/callumj/weave/remote"
"github.com/callumj/weave/remote/uptypes"
"github.com/callumj/weave/tools"
"log"
"os"
"path/filepath"
)
func performCompilation(configPath string, options option_set) {
fullPath := filepath.Dir(configPath)
// ensur... |
package dynamic
import "fmt"
func ChangeStr(src, des []byte) int {
// 两个字符串间的编辑距离
res := [100][100]int{}
n, m := len(src), len(des)
for i := 1; i <= n; i ++ {
res[i][0] = i
}
for i := 1; i <= m; i ++ {
res[0][i] = i
}
for i := 0; i < n; i ++ {
for j := 0; j < ... |
package main
import (
"sync/atomic"
)
// RR is struct for naive round robin balance algorithm
type RR struct {
upstream []Backend
index uint64
}
// NewRR return a brand new naive round robin balancer
func NewRR(backends ...Backend) *RR {
return &RR{backends, 0}
}
// Select return a backend randomly
func (r *... |
package service
import (
"fmt"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
"github.com/google/uuid"
"github.com/sanguohot/medichain/chain"
"github.com/sanguohot/medichain/datacenter"
"github.com/sanguohot/medichain/etc"
"gi... |
package go_workerpool
import "log"
type Job interface {
Do() error
}
//job 队列
var JobChannel = make(chan Job)
type Worker struct {
WorkerPool chan chan Job
JobChannel chan Job
done chan bool
}
func NewWorker(pool chan chan Job) *Worker {
return &Worker{
WorkerPool: pool,
JobChannel: make(chan Job),
... |
package main
import "fmt"
func main() {
nums := []int{3, 5, 1, 2, 7, 8}
fmt.Println(merge(nums))
}
func mergeSort(nums1, nums2 []int) []int {
n, m := len(nums1), len(nums2)
i, j := 0, 0
res := []int{}
for i < n && j < m {
if nums1[i] < nums2[j] {
res = append(res, nums1[i])
i++
} else {
res = app... |
package main
import "fmt"
type Stud struct {
name string
age int
score float32
}
//定义结构体的方法
func (this *Stud) init(name string, age int, score float32){
//this不是指针的话,传入的是拷贝,无法真正改变原来的值
this.name = name
this.age = age
this.score = score
fmt.Println(this)
}
func (this Stud) get() Stud{
return this
}
func (p ... |
package entity
type UmsIntegrationConsumeSetting struct {
Id int64 `json:"id" xorm:"pk autoincr BIGINT(20) 'id'"`
DeductionPerAmount int `json:"deduction_per_amount" xorm:"default NULL comment('每一元需要抵扣的积分数量') INT(11) 'deduction_per_amount'"`
MaxPercentPerOrder int `json:"max_percent_per_order" x... |
package main
type Rectangle struct {
Width float64
Height float64
}
// func (recevierName ReceiverType) MethodName(arguments)
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
|
package data
import (
"db"
"fmt"
"os"
"twitter"
)
func ExampleCheckTweet() {
os.Setenv("Juli-ENV", "test")
db.Clear()
tweets := []twitter.Tweet{
twitter.Tweet{"hi I'm new!", 1},
twitter.Tweet{"سلام من جدیدم", 2},
twitter.Tweet{"خدافظ", 3},
twitter.Tweet{"ایت یم تویت تست است", 4},
twitter.Tweet{"قشن... |
package main
import (
"github.com/ethereum/go-ethereum/common"
"fmt"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/sanguohot/medichain/util"
"log"
"github.com/ethereum/go-ethereum/crypto"
)
func main() {
two := [2][32]byte{}
two[0] = common.HexToHash("8ec34f461212f6bbfd759f400b5a80679ecd56f4961... |
/*
* @lc app=leetcode.cn id=830 lang=golang
*
* [830] 较大分组的位置
*/
package main
// @lc code=start
func largeGroupPositions(s string) [][]int {
ret := [][]int{}
for start := 0; start < len(s); {
end := start + 1
for end < len(s) && s[end] == s[start] {
end++
}
if end-start >= 3 {
ret = append(ret, []i... |
package config
//only used to determine if we start the hardware or run on simulator
type ElevatorType int
const (
ET_Comedi ElevatorType = 0
ET_Simulation = 1
)
type MotorDirection int
const (
MD_Up MotorDirection = 1
MD_Down = -1
MD_Stop = 0
)
type ... |
package problem0217
import (
"github.com/stretchr/testify/assert"
"leetcode-go/pkg/test"
"testing"
)
func Test_containsDuplicate(t *testing.T) {
tcs := []test.TCSB{
{
Input: []int{1, 2, 3, 1},
Expected: true,
},
{
Input: []int{1, 2, 3, 4},
Expected: false,
},
{
Input: []int{1, 1,... |
package response
type CommonError struct {
ErrorCode int64 `json:"errcode"`
ErrorMessage string `json:"errmsg"`
} |
package linebeacon
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestFrameData(t *testing.T) {
expect := []byte{0x02, 0x01, 0x06, 0x03, 0x03, 0x6f, 0xfe, 0x0b, 0x16, 0x6f, 0xfe, 0x02, 0xfd, 0x5e, 0xa0, 0xad, 0x1e, 0x7f, 0x00}
real := CreateLineSimpleBeaconAdvertisingPDU([]byte{0xfd, 0x5e, 0xa0, ... |
package vote
import "github.com/google/uuid"
type UseCase interface {
Store(v Vote) (uuid.UUID,error)
}
type Service struct {}
func NewService() *Service {
return &Service{}
}
func (s *Service) Store(v Vote) (uuid.UUID,error) {
//@TODO create store rules, using databases or something else
return uuid.New(),nil
... |
package main
import (
"os"
"fmt"
"bufio"
)
func main() {
//os.O_APPEND 追加到文件末尾,否则都会覆盖
file, err := os.OpenFile("output.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
fmt.Println("open file failed:",err)
return
}
defer file.Close()
writer := bufio.NewWriter(file)
str := "hello heylink\n"... |
// Package backend implements the Hakkero Project's API server.
// The server will handle all connections from the Hakkero Project's
// front-end interface, providing needed data through JSON responses
// and websocket calls.
// The server consists of 2 parts, the Room Provider and the Match Provider.
package backend
|
// Copyright 2016 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 rpcimpl
import (
"io"
"log"
"strconv"
"time"
pb "github.com/yjiang-dev/simplemath/api"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"golang.org/x/net/context"
)
const (
timestampFormat = time.StampNano
)
// SimpleMathServer a struct type
type SimpleMathServer struct{}
// GreatCommon... |
package pwm_profile
import (
"testing"
"time"
)
func TestInterval(t *testing.T) {
conf := `
{
"start":"10:00:00",
"end": "19:30:00",
"interval": 3600,
"values": [0,10,30,40,50,60,80,40,20,10]
}
`
i, err := Interval([]byte(conf), 13, 100)
if err != nil {
t.Fatal(err)
}
t1, err := time.Parse(tFormat, "10:3... |
package olm
import (
"context"
"fmt"
"testing"
"github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/a... |
package leetcode
import "math"
func reverse(x int) int {
if x == 0 {
return 0
}
ret := 0
const max = math.MaxInt32 / 10
const min = math.MinInt32 / 10
for x != 0 {
t := x % 10
if ret > max || (ret == max && t > 7) {
return 0
} else if ret < min || (ret == min && t < -8) {
return 0
}
ret = re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.