text stringlengths 11 4.05M |
|---|
package redis
import (
"bytes"
"errors"
"net"
"sync"
)
// RN \r\n standart ending for redis
const RN string = "\r\n"
// Client struct client
type Client struct {
addres string
conn net.Conn
//amount = pending response
amount int
mu sync.Mutex
}
// Start return client struct
func Start(addres string... |
// declaring main package
package main
// importing fmt package
import "fmt"
// declaring main function
func main(){
noOfCards := countCards()
card := selectedCard()
piValue := getPiValue()
fmt.Println("No of Cards = ",noOfCards," and the selected card is ",card)
fmt.Println("Value of Pi = ",piValue)
}
// func ... |
package main
import (
"context"
"flag"
"fmt"
"log"
"math/rand"
"net"
"net/rpc"
"os"
"os/signal"
"runtime"
"syscall"
"time"
"github.com/disq/werify"
wrpc "github.com/disq/werify/rpc"
)
func main() {
env := flag.String("env", werify.DefaultEnv, "Env tag")
port := flag.Int("port", werify.DefaultPort, "L... |
package main
import (
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strconv"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/fake"
)
func TestOption... |
package arangodb
import (
"fmt"
"strings"
"github.com/thedanielforum/arangodb/types"
"encoding/json"
"github.com/pkg/errors"
"github.com/thedanielforum/arangodb/errc"
)
type Query struct {
aql string
bindParams map[string]interface{}
cache bool
batchSize int
conn *Connection
}
func (c ... |
package moitessier
import (
"github.com/likestripes/pacific"
"time"
)
type Listener struct {
Context *pacific.Context `datastore:"-" sql:"-" json:"-"`
ActingPersonId int64 `datastore:"-" sql:"-" json:"-"`
PersonId int64
ListenerType int
ListenerId string
ScopeString string
}
... |
package dbhandlers
import (
"bytes"
"errors"
"github.com/jackc/pgx"
"strconv"
"technodb-final/app/db"
"technodb-final/app/models"
"time"
)
var ThreadErrors = map[string]error{
"conflict": errors.New("Thread already exists"),
"none": errors.New("Thread not found"),
}
const TMPTEMPLATE = "2006-01-02T15:04:05.... |
/*
* @lc app=leetcode.cn id=300 lang=golang
*
* [300] 最长递增子序列
*/
package main
import (
"fmt"
)
// @lc code=start
func max(a, b int) int {
if a > b {
return a
}
return b
}
func lengthOfLIS(nums []int) int {
numsLen := len(nums)
dp := make([]int, numsLen)
ans := 0
for i := range dp {
dp[i] = 1
}
for ... |
package main
import (
"github.com/gin-gonic/gin"
"github.com/juanamari94/ginmvc/controller"
"github.com/juanamari94/ginmvc/model"
)
func main() {
router := gin.Default()
router.GET("/", controller.GetIndex)
router.GET("/GetClientes", controller.GetClientes)
router.GET("/GetCliente/:id", controller.GetCliente)... |
package tikv
import (
"context"
"sync"
"sync/atomic"
"time"
"github.com/coocood/badger"
"github.com/juju/errors"
"github.com/pingcap-incubator/tinykv/kv/pd"
"github.com/pingcap-incubator/tinykv/kv/rowcodec"
"github.com/pingcap-incubator/tinykv/kv/tikv/dbreader"
"github.com/pingcap-incubator/tinykv/kv/tikv/i... |
// +build ignore
package client
import (
"net/http"
"github.com/iotaledger/wasp/packages/coretypes"
"github.com/iotaledger/wasp/packages/webapi/model/statequery"
"github.com/iotaledger/wasp/packages/webapi/routes"
)
// StateQuery queries the chain state, and returns the result of the query.
func (c *WaspClient)... |
package context
import (
"strings"
"github.com/kumahq/kuma/app/kumactl/pkg/install/data"
"github.com/kumahq/kuma/deployments"
)
type InstallCrdsArgs struct {
OnlyMissing bool
}
type InstallCrdsContext struct {
Args InstallCrdsArgs
InstallCrdTemplateFiles func(InstallCrdsArgs) (data.FileList... |
package main
import "fmt"
const (
a = iota
b // 1
n = 42
c = iota * 10 // 3 * 10
p = "I am a constant string"
q //same as above
)
const (
_ = iota //no use for zero
KB = 1 << (iota * 10) //bitwise shift to the left by 10
MB = 1 << (iota * 10) //bitwise shift to the left by 20
)
func main() {
fmt.Printl... |
package user
import (
"context"
"gocloud.dev/docstore"
"log"
"os"
)
func userCollection() *docstore.Collection {
ctx := context.Background()
url := lookupEnv("SITOMAT_COLLECTION_USER", "mem://user/name")
coll, err := docstore.OpenCollection(ctx, url)
if err != nil {
panic(err)
}
return coll
}
func looku... |
package main
import (
"bufio"
"bytes"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"text/template"
"time"
)
const (
loadDir string = "data"
writeDir string = "build"
userURLBase string = "https://twitter.com/intent/user?user_id="
tweetURLBase str... |
package bitbucket
// TODO(ttacon): change name of Owner to user or something similar
type Owner struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Links Links `json:"links"`
}
type Links struct {
Self Link `json:"self,omitempty"`
Avatar Link ... |
package main
import (
"crypto/tls"
"fmt"
"log"
"net"
"os"
"strings"
"time"
"github.com/mickep76/auth"
"github.com/mickep76/auth/jwt"
_ "github.com/mickep76/auth/ldap"
"github.com/pborman/uuid"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/gr... |
package datalayer
import (
"context"
"fmt"
"sync"
"time"
"github.com/dollarshaveclub/furan/generated/lib"
"github.com/gocql/gocql"
)
type eventStreams struct {
BuildEvents, PushEvents []lib.BuildEvent
}
type FakeDataLayer struct {
mtx sync.RWMutex
d map[gocql.UUID]*lib.BuildStatusResponse
bo map[gocql.... |
package conclusion
func floodFill(image [][]int, sr int, sc int, newColor int) [][]int {
// copy image
var img = make([][]int, len(image))
for i := range image {
img[i] = make([]int, len(image[i]))
for j := range image[i] {
img[i][j] = image[i][j]
}
}
fill(img, sr, sc, img[sr][sc], newColor)
return img... |
package main
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/json"
"fmt"
"io/ioutil"
"math"
"../pack"
)
type User struct {
PrivateKey *rsa.PrivateKey
Add [32]byte
Balancer int64
}
func CreatUser() User {
// var rand io.Reader
private, err := rsa.GenerateKey(rand.Reader,... |
/*
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
*/
package main
import (
"flag"
"fmt"
"strconv"
)
func main() {
N := 20
flag.Parse(... |
package spec
import "strings"
type Layout string
func (l *Layout) Parse(s string) error {
*l = Layout(ConvertTimeLayout(s))
return nil
}
func ConvertTimeLayout(s string) string {
s = strings.Replace(s, "yyyy", "2006", -1)
s = strings.Replace(s, "yy", "06", -1)
s = strings.Replace(s, "MM", "01", -1)
s = string... |
package main
import (
"fmt"
)
var i int = 0
func t1(c chan bool) {
for j := 0; j < 100000; j++ {
i++
}
c <- true
}
func t2(c chan bool) {
for j := 0; j < 1000000; j++ {
i--
}
c <- true
}
func main() {
var c1 = make(chan bool)
var c2 = make(chan bool)
go t1(c1)
go t2(c2)
<-c1
<-c2... |
package models
import (
"time"
)
// Model represents gorm.Model but with hidden json
type Model struct {
ID uint `gorm:"primary_key" json:"-"`
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
DeletedAt *time.Time `sql:"index" json:"-"`
}
// EnvConstants represents constants provided ... |
/*
* Copyright 2020-present Open Networking Foundation
* 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 ... |
package scss
import (
"bytes"
compilers2 "go.ybk.im/homepage/internal/app/skins/res/compilers"
"github.com/wellington/go-libsass"
)
type Compiler struct {
basePath string
}
func NewCompiler(basePath string) compilers2.Compiler {
return &Compiler{
basePath: basePath,
}
}
func (*Compiler) ContentType() stri... |
package app
import "github.com/dalloriam/websynth/app/audio"
// Config wraps all synthesizer configuration.
type Config struct {
Audio audio.Config `mapstructure:"AUDIO"`
GQLRoute string
Host string
SchemaDirectory string
}
|
/*
Copyright 2011 Google 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, software
di... |
package server
import (
"net/http"
"os"
"regexp"
"strings"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
loggermiddleware "github.com/meateam/api-gateway/logger"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"go.elastic.co/apm/module/apmgin"
"go.elastic.co/apm/module/apmhttp"
"google.go... |
package formatter
import (
"bytes"
"fmt"
"github.com/octavore/delta/lib"
)
func ColoredText(d *delta.DiffSolution) string {
buf := &bytes.Buffer{}
for _, l := range d.Lines {
if l[2] == "=" && l[0] == l[1] {
fmt.Fprintf(buf, " %s \n", l[0])
continue
}
if l[0] != "" {
fmt.Fprintf(buf, "\x1b[31m-%s... |
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
)
type Urls struct {
MyspaceUrl string `json:"myspace_url,omitempty"`
LastfmUrl string `json:"lastfm_url,omitempty"`
MbUrl string `json:"mb_url,omitempty"`
WikipediaUrl string `json:"wikipedia_url,omitempty"`
OfficialUrl stri... |
package main
import (
"fmt"
"net/http"
"os"
"net/http/pprof"
_ "net/http/pprof"
"runtime"
"time"
)
const (
port = ":9999"
)
var calls = 0
func sayHello(w http.ResponseWriter, r *http.Request) {
h, _ := os.Hostname()
calls++
fmt.Fprintf(... |
package web_test
import (
"context"
"testing"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"
"github.com/atlassian/gostatsd/pkg/web"
)
func TestHttpServerShutsdown(t *testing.T) {
testCtx, completed := testContext(t)
defer completed()
hs, err := web.NewHttpServer(
logrus.StandardLogge... |
package sample
import (
"github.com/ijidan/jgo/jgo/jdatabase"
"github.com/ijidan/jgo/model"
)
//事务样本
func SampleTransaction() bool{
query := jdatabase.Query{}
err := query.Transaction("", func() bool {
//获取数据库连接
connection := query.GetConnection()
//AR
ar := jdatabase.ActiveRecord{}
ar.SetIsDebug(true)... |
package release_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/cloudfoundry/bosh-micro-cli/release"
bmrel "github.com/cloudfoundry/bosh-micro-cli/release"
)
var _ = Describe("FindJobByName", func() {
Context("when the job exists", func() {
var release Release
var expectedJ... |
package main
import (
"log"
"context"
"firebase.google.com/go"
"google.golang.org/api/option"
)
type Todo struct {
title string
description string
}
func main() {
opt := option.WithCredentialsFile("secrets/serviceAccountKey.json")
app, err := firebase.NewApp(context.Background(), nil, opt)
c... |
package r2
import "io"
// Body sets the post body on the request.
func Body(contents io.ReadCloser) Option {
return func(r *Request) {
r.Body = contents
}
}
|
package main
import (
"encoding/json"
"fmt"
)
/*
@Time : 2020/6/26 3:18 下午
@Author : audiRS7
@File : 3使用map切片转json
@Software: GoLand
*/
//3、使用map[string]interface{} 描述于谦小姨子并转json
func main() {
dataMap1 := make(map[string]interface{})
dataMap1["name"] = "王钢蛋"
dataMap1["hobby"] = []string{"抽中华", "喝牛栏山", "烫花卷头"}
... |
// 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 main
import (
"os"
"github.com/r3code/go-useful-snippets/log"
kitlog "github.com/go-kit/kit/log"
)
func main() {
logger := kitlog.NewLogfmtLogger(os.Stdout)
for depth := 0; depth <= 5; depth++ {
l := log.With(logger, "caller", kitlog.Caller(depth))
l.Log("depth", depth) // line 13
}
... |
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"time"
)
func main() {
http.HandleFunc("/time", mainPage)
port := ":8795"
fmt.Println("Starting server on port", port)
err := http.ListenAndServe(port, nil)
if err != nil {
log.Fatal("listen and serve", err)
}
}
type ResTime struct {
TimeVa... |
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this fi... |
package frontend
//outgoing calls to other services
import (
"encoding/json"
"bytes"
"net/http"
)
func (s *Server) callBankService(route string, data map[string]interface{}) (int, map[string]interface{}, error) {
data["password"] = s.bankService.Password
return doPostRequest(s.bankService.Addr + route, dat... |
package utils
var QuoteArgs = []string{"--cat=", "--suggest", "--help"}
var QuoteCategory = []string{
"inspire",
"management",
"life",
"love",
"art",
"students",
}
func IsCmdValid(argsMap map[string]string) bool {
if len(argsMap) == 0 {
return true
}
for _, validArg := range QuoteArgs {
for arg := rang... |
//Package convert is the special one
package convert
import (
"fmt"
"image"
"image/jpeg"
"image/png"
"os"
"path/filepath"
"strings"
)
//MyImage is image type
type MyImage struct {
image.Image
}
//Do is Change Ext
func Do(dst, src string) error {
//読み込み用ファイル
sf, err := os.Open(src)
if... |
package main
import (
"os"
"testing"
)
func TestGetFiles(t *testing.T) {
path, err := os.Getwd()
if err != nil {
t.Fatal("could not get cwd", err.Error())
}
files := getFiles(path)
mainFile := path + "/main.go"
mainTest := path + "/main_test.go"
for _, f := range files {
if f != mainFile && f != mainTe... |
package users
import (
"testing"
"golang.org/x/crypto/bcrypt"
)
func TestValidate(t *testing.T) {
cases := []struct {
name string
user *NewUser
expectError bool
}{
{
"Basic case",
&NewUser{
"mail@newuser.com",
"password",
"password",
"Username",
"firstname",
"la... |
package main
import "fmt"
func main() {
//PrintArgs(1, 2)
//PrintArgs(1, 2, "3", "4")
PrintArgs(1, 2, []string{"3", "4", "5"}...)
args := []string{"6", "7", "8", "9"}
PrintArgs(1, 2, args...)
PrintArgs(1, 2, args[:3]...) //左包含右不包含
}
func PrintArgs(n1, n2 int, args ...string) {
//fmt.Printf("%T... |
package handlers
import (
"github.com/gin-gonic/gin"
ginSwagger "github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
)
// SetRoutes set the app engine and its routing.
func (h *Handler) SetRoutes(e *gin.Engine) *gin.Engine {
e = gin.New()
// middlewares
e.Use(gin.Recovery())
e.Use(gin.... |
/*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obta... |
package integers
import (
"fmt"
"testing"
)
func TestAdder(t *testing.T) {
sum := Add(2, 2)
expected := 4
if sum != expected {
t.Errorf("expected '%d' but got '%d'", expected, sum)
}
}
func TestRepeat(t *testing.T) {
repeated := Repeat("a")
expected := "aaaaa"
if repeated != expected {
t.Errorf("expecte... |
package engine
import (
"github.com/d5/tengo/v2"
"github.com/pkg/errors"
)
/*
输入
input (from domain)
输出
to domain 构造函数的入参
example:
output = {user_id: factor(this, "consumer_id")}
*/
type bridgeScriptExecutor struct {
c *tengo.Compiled
}
func newBridgeScriptExecutor(script string) (bridgeScriptExecutor, error... |
package linters
// Tests for linters.
import (
"path/filepath"
"runtime"
"testing"
"github.com/stretchr/testify/suite"
"golang.org/x/tools/go/analysis/analysistest"
)
type linterSuite struct {
suite.Suite
}
func (suite *linterSuite) TestContextLinter() {
analysistest.Run(suite.T(), TestdataDir(),
TodoAnal... |
package reader
import (
types "github.com/queueup-dev/qup-types"
"io"
"strings"
)
func NewJsonReader(stream io.Reader) *jsonReader {
return &jsonReader{input: stream}
}
func NewXmlReader(stream io.Reader) *xmlReader {
return &xmlReader{input: stream}
}
func NewRawReader(stream io.Reader) *rawReader {
return &... |
package calendarsender
import (
"github.com/sirupsen/logrus"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
type config struct {
URL string
Exchange string
QueueName string
QOS int
}
var Conf *config
func init() {
configPath := pflag.String("config", "", "path to sender config")
pflag.Par... |
// Benchmark test for file content encoding
// timestamp: 1526523292
// go test -v -bench=. ./colly -run=BenchmarkFileContent
// goos: linux
// goarch: amd64
// pkg: github.com/smileboywtu/FileColly/colly
// BenchmarkFileContentEncoder_Encode10-8 10000 204298 ns/op
// BenchmarkFileContentEncoder_Encode20-8 ... |
package oic
import (
log "github.com/Sirupsen/logrus"
"github.com/runtimeco/go-coap"
)
type Receiver struct {
reassembler *Reassembler
}
func NewReceiver(isTcp bool) Receiver {
r := Receiver{}
if isTcp {
r.reassembler = NewReassembler()
}
return r
}
func (r *Receiver) Rx(data []byte) coap.Message {
if r... |
package gormsql_test
import (
"github.com/atymkiv/echo_frame_learning/blog/cmd/api/post/platform/gormsql"
"github.com/atymkiv/echo_frame_learning/blog/model"
"github.com/atymkiv/echo_frame_learning/blog/pkg/utl/mock/mockdb"
"github.com/stretchr/testify/assert"
"testing"
)
func TestCreate(t *testing.T) {
db := m... |
package common
import (
"os"
"os/exec"
"runtime"
)
var goos = func() string { return runtime.GOOS }
// initClear is used to initialize the clear
// map of functions for clearing the console
// in the desired operating systems.
func initClear() {
clear = make(map[string]func())
clear["linux"] = func() {
cmd :=... |
package stats
import (
"time"
"github.com/juju/errors"
statsd "gopkg.in/alexcesaro/statsd.v2"
"github.com/9seconds/mtg/config"
)
const (
statsdConnectionsAbridgedV4 = "connections.abridged.ipv4"
statsdConnectionsAbridgedV6 = "connections.abridged.ipv6"
statsdConnectionsIntermediateV4 = "connections.intermed... |
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use ... |
package main
import "net/http"
func main() {
http.HandleFunc("/hello", func(writer http.ResponseWriter, request *http.Request) {
str := `<h1 style="color:red;">今天天气不错</h1>`
writer.Write([]byte(str))
})
http.ListenAndServe("localhost:8000", nil)
}
|
package main
func main(){
const MAX = 25
//MAX++
}
|
package logger
import (
"fmt"
"os"
"sync"
log "github.com/sirupsen/logrus"
)
var (
instance *log.Logger
loggerOnce sync.Once
)
type Tuples map[string]interface{}
func Logger() *log.Logger {
loggerOnce.Do(func () {
instance = log.New()
instance.SetFormatter(&log.JSONFormatter{})
instance.SetOutput(os.S... |
package main
import (
"github.com/kohirens/tmpltoapp/internal/cli"
"os"
"os/exec"
"runtime"
)
func isSevenZipInstalled() (string, error) {
cmdPath := ""
cmd := exec.Command("7z", "-i")
out1, err1 := cmd.CombinedOutput()
// get exit code.
ec := cmd.ProcessState.ExitCode()
if err1 != nil {
dbugf("stdout: %... |
package pdexv3
const (
BaseAmplifier = 10000
)
const (
RequestAcceptedChainStatus = "accepted"
RequestRejectedChainStatus = "rejected"
ParamsModifyingFailedStatus = 0
ParamsModifyingSuccessStatus = 1
)
// trade status
const (
TradeAcceptedStatus = 1
TradeRefundedStatus = 0
OrderAcceptedStatus = 1
OrderRef... |
package ciolite
// Api functions that support: users/email_accounts/connect_tokens
import (
"fmt"
)
// GetUserEmailAccountConnectTokens gets a list of connect tokens created for a user email account.
func (cioLite CioLite) GetUserEmailAccountConnectTokens(userID string, label string) ([]GetConnectTokenResponse, err... |
package monitorcontroller
import (
"github.com/astaxie/beego"
)
type MonitorController struct {
beego.Controller
}
|
package main
import (
"fmt"
"os/exec"
"strings"
"encoding/json"
"log"
)
const (
MAX_OS_PACKAGES = 1500
)
type OSPackage struct {
Name string `json:"name"`
Version string `json:"version"`
License string `json:"license"`
Url string `json:"u... |
// SPDX-License-Identifier: MIT
// Copyright (c) 2019 Stephan Gerhold
package main
import (
"flag"
"fmt"
"hlsdump/hls"
"log"
"os"
"os/signal"
"path"
"strings"
"syscall"
)
type listFlag []string
func (l *listFlag) String() string {
return strings.Join(*l, "\n")
}
func (l *listFlag) Set(value string) error ... |
package main
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/devinmarder/go-qa-service/event"
"github.com/devinmarder/go-qa-service/repository"
)
func Test_updateHandler(t *testing.T) {
repo = &repository.LocalRepository{}
eventChan := make(chan string)
go event.RunEven... |
package merkle
import (
"fmt"
"strings"
"testing"
)
func TestNodeSums(t *testing.T) {
var (
nodes []*Node
h = DefaultHashMaker()
words = `Who were expelled from the academy for crazy & publishing obscene odes on the windows of the skull`
expectedChecksum = "819fe8fed7a... |
package mst_user
import (
"fmt"
"go/internal/pkg/api/app/request"
"go/internal/pkg/helper"
"go/internal/pkg/model"
"log"
"regexp"
"time"
"golang.org/x/crypto/bcrypt"
)
var emailRegex = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-... |
package main
import (
"log"
"github.com/gobuffalo/envy"
"github.com/gobuffalo/toodo/actions"
)
func main() {
port := envy.Get("PORT", "3000")
log.Printf("Starting toodo on port %s\n", port)
log.Fatal(actions.App().Start(port))
}
|
// This file is subject to a 1-clause BSD license.
// Its contents can be found in the enclosed LICENSE file.
package evdev
import (
"testing"
)
func TestBitset(t *testing.T) {
bs := NewBitset(80)
bs.Set(-1)
bs.Set(0)
bs.Set(2)
bs.Set(4)
bs.Set(13)
bs.Set(76)
want := []struct {
Index int
Value bool
}{... |
package main
import (
"fmt"
"io/ioutil"
"path/filepath"
"reflect"
"strings"
"testing"
)
var DIR = filepath.Join("testdata")
func TestGetAttrVals(t *testing.T) {
type file struct {
html string
config string
exp string
}
var files []file
fis, err := ioutil.ReadDir(DIR)
if err != nil {
t.Fatal(e... |
package domain
import (
"time"
"github.com/google/uuid"
)
type Matrix struct {
ID uint `json:"id"`
UUID uuid.UUID `json:"uuid"`
Code string `json:"code"`
Name string `json:"name"`
Description string `json:"description"`
CourseID uuid.UUID `db:"course_id" j... |
package services
type Ping interface {
Get() string
}
func NewPing() Ping {
return &PingService{}
}
type PingService struct {}
func(* PingService) Get() string {
return "pong"
}
|
package server
import (
"fmt"
"net"
log "../log"
"../proto"
)
// Handle Each client request
func connectionHandler(conn net.Conn) {
connFrom := conn.RemoteAddr().String()
log.Info("Connection from: %s", connFrom)
m := func(conn net.Conn) {
err := conn.Close()
log.Info("Closing connection: %s\n", connFrom... |
package k8sml
import (
"gopkg.in/yaml.v3"
"reflect"
"strings"
terraform "KubeArch/kubearch/proletarian/terraform"
)
type TargetGroup struct {
ID string
Protocol string
Port string
RuntimeVariables map[string]string
Target *Role
LoadBalancer *NetworkLoadBalancer
VirtualFirewall VirtualFirewall
}
type tmpTa... |
package main
import (
"fmt"
"time"
)
func main() {
// Testing basic switch
for i := 1; i <= 3; i++ {
switch i {
case 1:
fmt.Println("3")
case 2:
fmt.Println("2")
case 3:
fmt.Println("1")
}
}
// Testing switch usage with time
date := time.Now().Weekday()
switch date {
case time.Saturday:
... |
package node
type AppFlags struct {
ConfigPath string
Verbose bool
}
|
package fracker
import (
"github.com/coreos/go-etcd/etcd"
)
type Node interface {
Each(func(string, string))
}
func NewNode(n *etcd.Node) Node {
return &node{n}
}
type node struct {
*etcd.Node
}
func (self *node) Each(fn func(string, string)) {
if self.Dir {
for _, child := range self.Nodes {
n := &node{... |
package main
import (
"fmt"
"time"
)
var worker_num int
type Pool struct {
worker chan func()
size chan bool
}
func New(size int) *Pool {
return &Pool{
worker: make(chan func()),
size: make(chan bool, size),
}
}
func (pool *Pool) workerStart(worker_num int, task func()) {
defer func() { <-pool.size ... |
package io
import (
"bytes"
"errors"
"io"
"testing"
)
func TestSingleRead(t *testing.T) {
var br bufReader
r := bytes.NewBuffer([]byte{0, 1, 1, 2, 3, 5})
if err := br.ExtendTo(r, 4); err != nil {
t.Errorf("bad read: got %v, want nil", err)
}
if got, want := br.Data(), []byte{0, 1, 1, 2}; !bytes.Equal(got, ... |
/*
Copyright IBM Corporation 2020
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
di... |
package musictheory
// Scale is a series of Transposers
type Scale []Transposer
// Transpose transposes a scale by the specified Interval
func (s Scale) Transpose(i Interval) Transposer {
scale := Scale{}
for _, transposer := range s {
scale = append(scale, transposer.Transpose(i))
}
return scale
}
// NewScale... |
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
pattern := "abba"
str := "dog dog dog dog"
patternStr := ""
strBuild := ""
count := 1
strArr := strings.Split(str, " ")
patternMap := make(map[string]int)
strMap := make(map[string]int)
for _, x := range pattern {
_, ok := patternMap[str... |
// +build darwin freebsd netbsd openbsd linux
package main
import (
"fmt"
"os"
"golang.org/x/crypto/ssh/terminal"
)
type unix_passer struct {
}
func (u *unix_passer) ReadPassword() (string, error) {
fmt.Print("Password: ")
b, err := terminal.ReadPassword(int(os.Stdin.Fd()))
return string(b), err
}
func init... |
package chapter6
import (
"search-engine/chapter6/analysis/analyzer"
"testing"
)
// 解决复杂问题最行之有效的办法往往就是 分解,
func TestToken(t *testing.T) {
myAnalyzer, _ := analyzer.SimpleAnalyzer()
tokenStream := myAnalyzer.Analyze([]byte("程咬金"))
for _, token := range tokenStream {
t.Log(token.String())
}
}
func TestSearch... |
package models
import (
"database/sql"
"github.com/keveaux/go_CRUD_application/entities"
)
type ProductModel struct {
Db *sql.DB
}
func (productmodel ProductModel) FindAll() (product []entities.Product, err error) {
rows, err := productmodel.Db.Query("select * from example")
if err != nil {
return nil, err... |
package main //可运行才能是main包
import (
"fmt"
"math"
_ "structs/exportStruct" // _ 包引入但是不用,不加_会报错,go对没用到的包报错,减少不必要的引入,减少编译时间和包大小
)
/*
* 返回单个值
*/
func calculatBill(price int, no int) int {
var totalPrice = price * no
return totalPrice
}
/*
* 返回多个值
*/
func testReturnMultiValue(a, b int)(int, int) {
var sum = a + b... |
package problem0145
//TreeNode 树节点
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func postorderTraversal(root *TreeNode) []int {
if root == nil {
return []int{}
}
result := postorderTraversal(root.Left)
result = append(result, postorderTraversal(root.Right)...)
result = append(result, r... |
package leetcode
import (
"strings"
)
func isPalindrome(s string) bool {
s = strings.ToLower(s)
i, j := 0, len(s)-1
for i < j {
for !isAN(s[i]) && i < j {
i++
}
for !isAN(s[j]) && i < j {
j--
}
if i < j {
if s[i] != s[j] {
return false
}
i++
j--
}
}
return true
}
func isAN(b... |
package controllers
import (
"cwengo.com/models"
"github.com/astaxie/beego"
/*"strconv"*/
"strings"
)
type TopicController struct {
beego.Controller
}
type MyLabel struct {
Name string
Id string
}
func (this *TopicController) Get() {
topicId := this.Input().Get("topicId")
if topicId == "" {
this.TplNa... |
package pie
import (
"golang.org/x/exp/constraints"
)
// Ints transforms each element to an integer.
func Ints[T constraints.Ordered](ss []T) []int {
return Map(ss, Int[T])
}
|
package rsync
import (
"os"
"sync/atomic"
"time"
"github.com/cpusoft/goutil/belogs"
"github.com/cpusoft/goutil/conf"
"github.com/cpusoft/goutil/httpclient"
"github.com/cpusoft/goutil/jsonutil"
model "rpstir2-model"
"rpstir2-sync-core/rsync"
)
var rpQueue *RsyncParseQueue
// start to rsync
func rsyncRequest... |
package mikrotik
import "time"
import "errors"
import "net"
import "fmt"
import "strings"
import "encoding/hex"
import "crypto/md5"
type MkDev struct {
conn net.Conn
Connected bool
ip string
port string
timeout time.Duration
stop_ch chan string
Debug bool
Bytes_in uint64
Bytes_out uint64
Bytes_sin... |
package users
import (
"io"
"io/ioutil"
. "2019_2_IBAT/pkg/pkg/models"
"github.com/google/uuid"
"github.com/pkg/errors"
)
func (h *UserService) CreateSeeker(body io.ReadCloser) (uuid.UUID, error) {
bytes, err := ioutil.ReadAll(body)
if err != nil {
return uuid.UUID{}, errors.New(BadRequestMsg)
}
var new... |
package main
import (
"reflect"
"testing"
)
func Test_generateDNSMasqConfig(t *testing.T) {
testResult := `## WARNING: THIS IS AN AUTOGENERATED FILE
## AND SHOULD NOT BE EDITED MANUALLY AS IT
## LIKELY TO AUTOMATICALLY BE REPLACED.
strict-order
local=/foobar.org/
domain=foobar.org
expand-hosts
pid-file=/run/contai... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.