text stringlengths 11 4.05M |
|---|
package commands
import (
"flag"
"fmt"
"io"
"github.com/Cloud-Foundations/Dominator/lib/log"
)
func printCommands(writer io.Writer, commands []Command) {
for _, command := range commands {
if command.Args == "" {
fmt.Fprintln(writer, " ", command.Command)
} else {
fmt.Fprintln(writer, " ", command.Com... |
package pool
import (
"fmt"
"io"
"sync"
"time"
)
//TODO: 保存所有的连接, 而不是只保存连接计数
var ErrMaxConn = fmt.Errorf("maximum connections reached")
//
type NConn interface {
io.Closer
Name() string
Closed() bool
}
type ConnPool struct {
sync.RWMutex
Name string
Address string
MaxConns int
MaxIdle int
Cnt ... |
package memstorage
import (
"strconv"
"test_server/domain"
)
type MemStorage struct{
tasks domain.Tasks
id int64
}
func NewMemStorage() *MemStorage{
return &MemStorage{}
}
func (ms *MemStorage) GetAllTasks() (domain.Tasks, error){
return ms.tasks, nil
}
func (ms *MemStorage) CreateTask(task domain.Task) (dom... |
package main
import (
"github.com/gorilla/mux"
"os"
"fmt"
"net/http"
"payserver/controllers"
)
func main() {
router := mux.NewRouter()
// 新增一个用户
// get该用户的钻石,对应 get_balance_m
// set该用户的钻石
// add该用户的钻石
// sub该用户的钻石,pay_m
// 取消支付接口,cancel_pay_m
// 直购接口,buy_goods_m
// 赠送接口,present_m
router.HandleFunc(... |
// +build !windows,!dockerless
/*
Copyright 2019 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 applicab... |
package protocol
import "golangPractice/chat_room/model"
type Message struct {
Cmd string `json:"cmd"`
Data string `json:"data"`
}
type LoginCmd struct {
Id int `json:"user_id"`
Passwd string `json:"passwd"`
}
type RegisterCmd struct {
User model.User `json:"user"`
}
type LoginCmdRes struct {
Code int `json:... |
package random
import (
"fmt"
"math/rand"
"reflect"
"github.com/bingoohuang/pump/model"
)
// Time ...
type Time struct {
allowNull bool
}
// TimeZero ...
func TimeZero() reflect.Type {
return reflect.TypeOf("")
}
// Value ...
// nolint:gomnd
func (r *Time) Value() interface{} {
if r.allowNull && rand.Int63n... |
package utils
import (
"encoding/json"
"testing"
)
func TestRandomIp(t *testing.T) {
a := GetFakeIp()
t.Logf("a=%v", a)
}
func TestRandomIp2(t *testing.T) {
a := "{\"code\":\"GP_00\",\"msg\":\"\",\"biz_code\":\"GPBIZ_00\",\"biz_msg\":\"\",\"data\":{\"sign_type\":\"RSA\",\"tf_sign\":\"1\",\"appid\":\"123\",\"bus... |
/*
* Copyright 2017 StreamSets 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... |
package redis_test
import (
"testing"
rivescript "github.com/aichaos/rivescript-go"
"github.com/aichaos/rivescript-go/sessions"
"github.com/aichaos/rivescript-go/sessions/redis"
)
// This script tests the 'integration' of the RiveScript public API with the
// RiveScript-Redis public API.
func TestIntegration(t ... |
package main
import (
"errors"
"github.com/OperatorFoundation/shapeshifter-dispatcher/common/log"
)
func validateIPCLogLevel(ipcLogLevel string) (int, error) {
switch ipcLogLevel {
case "NONE":
return log.LevelNone, nil
case "ERROR":
return log.LevelError, nil
case "WARN":
return log.LevelWarn, nil
ca... |
package app
import (
"context"
"fmt"
"net"
"net/http"
"time"
"github.com/go-chi/chi"
"github.com/go-chi/cors"
"github.com/kelseyhightower/envconfig"
"github.com/pkg/errors"
"go.uber.org/zap"
"github.com/openmultiplayer/web/server/src/api/legacy"
"github.com/openmultiplayer/web/server/src/api/servers"
"g... |
package main
/*
* @lc app=leetcode id=198 lang=golang
*
* [198] House Robber
*/
func rob(nums []int) int {
pre1, pre2 := 0, 0
for _, num := range nums {
if pre1+num > pre2 {
pre1, pre2 = pre2, pre1+num
} else {
pre1, pre2 = pre2, pre2
}
}
return pre2
}
|
package main
import "fmt"
func main() {
// 짧은 선언(Go에만 있음)
// 반드시 함수 안에서만 사용(전역으로는 사용 불가)
// 선언 후 재할당 하면 에러 발생
// 특정 메서드 안에 1회성으로 사용하는 것
// 주로 제한된 범위의 함수 내에서 사용할 경우 코드 가독성을 높일 수 있다.
shortVar1 := 3
shortVar2 := "Test"
shortVar3 := false
// shortVar1 := 10 // 에러 발생
fmt.Println("shortVar1: ", shortVar1, "sho... |
package anagrams
import (
"fmt"
"github.com/najeal/kata/pkg/common"
)
// NewAnagramDispatcher return a new AnagramDispatcher instance
func NewAnagramDispatcher(sortExtractor StringExtractorMethod) *AnagramDispatcher {
return &AnagramDispatcher{
wmap: make(map[string][]string),
sortExtractor: sortExtr... |
package main
import (
"bufio"
"flag"
"fmt"
"github.com/vseledkin/gortex"
"github.com/vseledkin/gortex/assembler"
"github.com/vseledkin/gortex/models"
"log"
"math"
"os"
"strings"
"sync"
"time"
)
const (
train = "train"
trainAutoencoder = "train.autoencoder"
translate = "translate"
epo... |
package otf
var (
TAG_TTC = TAG{'t', 't', 'c', 'f'}
)
var (
TAG_CMAP = TAG{'c', 'm', 'a', 'p'}
TAG_HEAD = TAG{'h', 'e', 'a', 'd'}
TAG_HHEA = TAG{'h', 'h', 'e', 'a'}
TAG_HMTX = TAG{'h', 'm', 't', 'x'}
TAG_OS_2 = TAG{'O', 'S', '/', '2'}
)
|
package k8s
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"go.starlark.net/starlark"
"go.starlark.net/starlarkstruct"
)
var _ = Describe("SearchParams", func() {
var searchParams SearchParams
Context("Building a new instance from a Starlark struct", func() {
var (
input *starlarkstruct... |
package utilx
import "os"
func EnvReadStringOr(envIdentifier string, defaultValue string) string {
value := os.Getenv(envIdentifier)
if value == "" {
return defaultValue
}
return value
}
func EnvReadBoolOr(envIdentifier string, defaultValue bool) bool {
value := os.Getenv(envIdentifier)
if value == ""... |
package size_test
import (
"fmt"
"testing"
"github.com/iochen/mudl/utils/size"
)
func TestSize_String(t *testing.T) {
i := size.Size(123456789)
fmt.Println(i.String())
size.Measure = 1000
fmt.Println(i.String())
size.Precision = 4
size.Measure = 1 << 10
fmt.Println(i.String())
size.Measure = 1000
fmt.Pr... |
/*
Copyright 2019 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, ... |
//
// Last.Backend LLC CONFIDENTIAL
// __________________
//
// [2014] - [2018] Last.Backend LLC
// All Rights Reserved.
//
// NOTICE: All information contained herein is, and remains
// the property of Last.Backend LLC and its suppliers,
// if any. The intellectual and technical concepts contained
// herein are prop... |
package main
import (
"flag"
"fmt"
"io/ioutil"
"strings"
"unicode"
"github.com/360EntSecGroup-Skylar/excelize"
"github.com/tidusant/c3m-common/log"
//"io"
"net/http"
// "os"
"strconv"
"time"
"github.com/gin-gonic/gin"
)
var mytoken string
var pagesize = 10
var SheetName = "Sheet1"
var hangtonsg []Han... |
package middleware
import "net/http"
//JSONHeader chainable middleware example
func JSONHeader(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "aplication/json")
next.ServeHTTP(w, r)
}
}
|
// Copyright 2019 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 elevator
import (
"fmt"
)
const (
DOWN = -1
IDLE = 0
UP = 1
)
type Elevator struct {
Id int
CurrentFloor int
Goals *PriorityQueue
Direction int
}
func NewElevator(id, startingFloor int) *Elevator {
return &Elevator{
Id: id,
CurrentFloor: startingFloor,
Goals: ... |
package main
// serverListReader is a function type used to allow mocking of the server list read in the unit tests
type serverListReader func(string) []string
// serverListType is a struct used to control generation/reading of a server list
type serverListType struct {
reader serverListReader
serverListFil... |
package main
import "fmt"
func main() {
//Declare and Asssign
var i int
i = 10
fmt.Println(i)
//Declare a time of initalization
var f float32 = 2.3
fmt.Println(f)
//Dynamic typecasting
firstName := "Sneha Vijay Konkati"
fmt.Println(firstName)
fmt.Println("Hello World")
b := true
fmt.Println(b)
c :=... |
package main
type myInt int //自定义类型
type yourInt = int //类型别名
|
package sese
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document00100101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:sese.001.001.01 Document"`
Message *TransferOutInstruction `xml:"sese.001.001.01"`
}
func (d *Document00100101) AddMe... |
/*
* Developed by Nicolas Martyanoff
* Copyright (c) 2015 Celticom
* Copyright (c) 2016 Nicolas Martyanoff <khaelin@gmail.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission ... |
package main
import "fmt"
import "strings"
// SayHello says Hello
func SayHello(greetings []string) {
fmt.Println(joinStrings(greetings))
}
// joinStrings joins strings
func joinStrings(words []string) string {
return strings.Join(words, ", ")
}
func add(a, b int, c int) int {
return a + b
}
type Test struct {
... |
package models
/*公共的用于返回结构体的类型定义,Data表示任意类型
*/
type Result struct {
Code int//接口返回状态类型
Message string//接口返回状态对应的描述信息
Data interface{}//返回的数据
}
|
package render
import (
"fmt"
"html/template"
"log"
"net/http"
"path/filepath"
"regexp"
"strings"
"github.com/oxtoacart/bpool"
"github.com/xDarkicex/playserver/server"
)
var Templates map[string]*template.Template
var bufpool *bpool.BufferPool
func init() {
bufpool = bpool.NewBufferPool(64)
Templates = ... |
package sitomat
import (
"context"
"net/http"
"github.com/julienschmidt/httprouter"
"github.com/peter-mueller/sit-o-mat/user"
)
type Controller struct {
Service *Service
}
func (c *Controller) ManualAssign(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
username, password, ok := r.BasicAuth()
... |
package wxgamevp
import (
"fmt"
"github.com/birjemin/wxgamevp/utils"
"log"
)
// Order model
type Order struct {
AppID string
OrderNo string
OutTradeNo string
AccessToken string
HTTPRequest *utils.HTTPClient
Debug bool
}
// RespOrder response
type RespOrder struct {
CommonError
PayForOrder... |
package gitlab
import (
"testing"
"time"
"github.com/stretchr/testify/suite"
)
const (
projectGraphFile = "../../test/data/simple2.yml"
)
type gitlabSuite struct {
suite.Suite
api gitlabAPI
}
func (s *gitlabSuite) SetupSuite() {
config := &gitlabConfig{
login: "root",
password: "password",
timeout:... |
package repository
import (
"github.com/dkpeakbil/taskserver/domain"
)
type Repository interface {
Save(user *domain.User) (*domain.User, error)
FindByID(id int) (*domain.User, error)
FindByUsername(username string) (*domain.User, error)
}
|
package main
import (
"fmt"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1"
)
func collect(podMetricsAccessor v1beta1.PodMetricsInterface, reporters []Reporter,
labelResolver LabelResolver, namespace string) error... |
package gen
import (
"bytes"
"errors"
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"text/template"
"time"
"github.com/vugu/xxhash"
)
// ParserGoPkg knows how to perform source file generation in relation to a package folder.
// Whereas ParserGo handle... |
package bin
import (
"bytes"
"testing"
mc "gx/ipfs/QmYMiyZRYDmhMr2phMc4FGrYbsyzvR751BgeobnWroiq2z/go-multicodec"
)
func TestBinaryDecoding(t *testing.T) {
buf := bytes.Buffer{}
buf.Write(Header)
data := []byte("Multicodec")
buf.Write(data)
dataOut := make([]byte, len(data))
Multicodec().Decoder(&buf).Decod... |
package migrations
import (
"database/sql"
"os"
"path"
_ "github.com/mutecomm/go-sqlcipher"
)
type Minor007 struct{}
func (Minor007) Up(repoPath string, pinCode string, testnet bool) error {
var dbPath string
if testnet {
dbPath = path.Join(repoPath, "datastore", "testnet.db")
} else {
dbPath = path.Join... |
package fixtures
import (
"github.com/urbn/ordernumbergenerator/app"
"net/http"
"net/http/httptest"
)
var ApplyResultAN = app.MongoDocument{
"AN",
"an",
"US-NV",
1,
}
var MockOrderDaoError = app.Error{
400,
http.StatusBadRequest,
"Unable to connect to MongoDB",
}
func PerformRequest(r http.Handler, method... |
package main
import "fmt"
func singleNumber(nums []int) int {
ans := 0
for _, tmp := range nums {
ans = ans ^ tmp
}
return ans
}
func main() {
fmt.Println(singleNumber([]int{1, 1, 2, 2, 4}))
}
|
package main
import (
"bytes"
"encoding/gob"
"fmt"
"io/ioutil"
)
type Post struct {
Id int
Content string
Author string
}
func store(data interface{}, filename string) {
buffer := new(bytes.Buffer)
encoder := gob.NewEncoder(buffer)
err := encoder.Encode(data)
if err != nil {
panic(err)
}
err = ... |
/*
Copyright 2021. The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writ... |
package health
import (
"context"
"database/sql"
"github.com/nagendra547/go-db-loadbalancer/log"
"github.com/nagendra547/go-db-loadbalancer/mydb"
)
// PingMaster -
func PingMaster(db *mydb.DB) error {
log.Info("Checking Master")
if err := db.Master.Ping(); err != nil {
log.Error("Master is down")
return er... |
package main
import (
"fmt"
"math"
)
func reverse(x int) int {
result := 0
neg := true
if (x < 0) {
neg = false
x *= -1
}
for x >= 10 {
result = result * 10 + x%10 * 10
x /= 10
}
result += x
Max := math.MaxInt32
Min := math.MinInt32
if (result > Max || result < Min) {
return 0
}
if (!neg) {
... |
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/go-gnss/data/cmd/database/apis"
)
func main() {
r := gin.New()
r.Use(gin.Logger())
r.Use(gin.Recovery())
v1 := r.Group("/api/v1")
v1.GET("/observations/:id", apis.GetObservation)
v1.GET("/observations", apis.GetObservations)
// /sources/:id... |
package main
import (
"fmt"
"os"
)
// 通过文件的路径获取文件的信息
func main() {
args := os.Args
if len(args) != 2 {
fmt.Println("输入的信息错误")
return
}
// 文件路径
filePath := args[1]
// 获取文件信息
fileInfo, err := os.Stat(filePath)
if err != nil {
fmt.Println("err = ", err)
return
}
fmt.Println("文件名:", fileInfo.Name()... |
package main
import "fmt"
func max(x int) int {
//This func max is actually at package level. It can be called through the package. IT IS NOT EXPORTED as it is not a capital letter
return 42 + x
}
// You can then call function max from anywhere
func main() {
max := max(7)
// This is declaring a variable at BLOC... |
package t2m
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"github.com/google/uuid"
)
const (
maxSize = 1000
)
var taskRe = regexp.MustCompile("/([^/?]*)")
var errUnknownTask = errors.New("Unknown task specified")
var errQueryParameter = e... |
package slices
import "github.com/cheekybits/genny/generic"
type OutType generic.Type
type InType generic.Type
func FMapᐸInType_OutTypeᐳ(f func(s InType) OutType) func([]InType) []OutType {
return func(xs []InType) []OutType {
ys := make([]OutType, len(xs))
for i := range xs {
ys[i] = f(xs[i])
}
return y... |
package common
import (
"testing"
"github.com/stretchr/testify/assert"
)
// TestNextPlaceholder verifies dynamically-generated placeholder strings.
func TestNextPlaceholder(t *testing.T) {
pg := NewPlaceholderGenerator()
assert.Equal(t, pg.NextPlaceholder(), "placeholder-0")
assert.Equal(t, pg.NextPlaceholder()... |
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"path/filepath"
"time"
"github.com/XiaoMi/pegasus-go-client/pegasus"
)
func main() {
cfgPath, _ := filepath.Abs("./example/pegasus-client-config.json")
rawCfg, err := ioutil.ReadFile(cfgPath)
if err != nil {
fmt.Println(err)
return
}
... |
// Package traefikplugindemo Traefik插件示例
// 给请求响应头添加 resp:xxx
package traefikplugindemo
import (
"context"
"net/http"
"github.com/iancoleman/strcase"
)
// Config the plugin configuration.
type Config struct {
// resp header值的字符串风格:snake, camel
ValueStrCase string
// resp header的默认值
DefaultValue string
}
// C... |
package rakuten
import (
"context"
"fmt"
)
type IchibaItemSearchParams struct {
Keyword string `url:"keyword,omitempty"`
ShopCode string `url:"shopCode,omitempty"`
ItemCode string `url:"itemCode,omitempty"`
GenreID int `url:"genreId,omitempty"... |
package coder
type VerifyToekn struct {
UserID int //用户ID
Token string //token
}
type VerifyTokenSuccess struct {
ChatLength int
LimitChatTimes int
}
type PUSH_ServerInfo struct {
ServerID int
OnLineNum int
}
type ErrJSON struct {
ErrCode int
ErrMsg string
}
|
package new
import (
"encoding/json"
"fmt"
"io/ioutil"
"github.com/AlecAivazis/survey/v2"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/ChrisRx/splits/pkg/prompt"
"github.com/ChrisRx/splits/pkg/srapi"
)
func NewCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "new [filename... |
package main
import (
"fmt"
"github.com/codegangsta/cli"
)
func list(c *cli.Context) error {
appPackages := c.StringSlice("app")
testPackages := c.StringSlice("test")
appImports, err := getAppImports(appPackages...)
if err != nil {
return fmt.Errorf("failed to detect app imports: %s", err)
}
testImports,... |
// Copyright (c) 2020 Blockwatch Data Inc.
// Author: alex@blockwatch.cc
package index
import (
"context"
"github.com/jinzhu/gorm"
"github.com/zyjblockchain/sandy_log/log"
"tezos_index/puller/models"
)
const FlowIndexKey = "flow"
type FlowIndex struct {
db *gorm.DB
}
func NewFlowIndex(db *gorm.DB) *FlowIndex ... |
package mitsubishi02
import (
"errors"
"strconv"
"github.com/dash-app/remote-go/aircon"
"github.com/dash-app/remote-go/hex"
)
func (r *mitsubishi02) Generate(e *aircon.Entry) ([]*hex.HexCode, error) {
code := [][]int{
{0x23, 0xCB, 0x26, 0x01, 0x00},
{0x23, 0xCB, 0x26, 0x01, 0x00, 0x00, 0x58, 0x00, 0x00, 0xC... |
package main
import "fmt"
func main() {
a:=10
b:=20
c:=a%b
fmt.Println(c)
} |
package core
import (
"errors"
"fmt"
"strings"
"github.com/bazelbuild/bazelisk/config"
"github.com/bazelbuild/bazelisk/httputil"
"github.com/bazelbuild/bazelisk/platforms"
"github.com/bazelbuild/bazelisk/versions"
)
const (
// BaseURLEnv is the name of the environment variable that stores the base URL for do... |
package ormlite
import (
"database/sql"
"database/sql/driver"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"testing"
)
type model struct{}
func (m *model) Table() string { return "" }
func TestGetModelValue(t *testing.T... |
package isValidSudoku
func isValidSudoku(board [][]byte) bool {
dict := map[byte]int{'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.': 0}
row := [10][10]int{}
col := [10][10]int{}
block := [3][3][10]int{}
for i := 0; i < 9; i++ {
for j := 0; j < 9; j++ {
if dict[board[i][j]] == 0 {... |
package tools
import (
"regexp"
"strconv"
// "golangapi/models"
)
// @Title Split Range
// @Description split range to start and end
// @Success int64 int 64 error
func SplitRange(rangestr string) (int64, int64, error){
reg := regexp.MustCompile(`[0-9]+`)
result := reg.FindAllString(rangestr, -1)
start, err := s... |
package cmd
import (
"github.com/sachaos/atcoder/lib/files"
"github.com/spf13/cobra"
"os"
"os/exec"
"path"
"strings"
)
// editCmd represents the edit command
var editCmd = &cobra.Command{
Use: "edit",
Short: "Edit source code",
Aliases: []string{"e"},
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Comma... |
package main
import (
"fmt"
"hackerrank.kamontat.net/question/the-birthday-bar/logic"
)
func main() {
fmt.Println(logic.Normal([]int32{2, 2, 1, 3, 2}, 4, 2))
fmt.Println(logic.Sum([]int32{2, 2, 1, 3, 2}, 4, 2))
}
|
//这只是一个实验程序,所以很多错误判断都没写.
//在实用环境中一定要加上!
//golang的核心优势之一就是,只要对错误进行了正确的判断,就没有段错误.
package main
import (
"encoding/json"
"fmt"
"net"
)
func main() {
listener, _ := net.Listen("tcp", "localhost:1234") //_表示空变量,赋值但不使用
conn, _ := listener.Accept()
buffer := make([]byte, 1024)
length, _ := conn.Read(buffer)
var myBl... |
package scan
import (
"fmt"
"io"
"h12.io/dfa"
)
type Matcher struct {
*dfa.M
EOF int
Illegal int
fast *dfa.FastM
}
type MID struct {
M interface{}
ID int
}
func NewMatcher(eof, illegal int, mids []MID) *Matcher {
m := or(mids)
fast := m.ToFast()
return &Matcher{
EOF: eof,
Illegal: illegal,... |
package honeycombio
import (
"context"
"fmt"
"time"
)
// QueryAnnotations describes all the query annotation-related methods that the
// Honeycomb API supports.
//
// API docs: https://docs.honeycomb.io/api/query-annotations/
type QueryAnnotations interface {
// List all query annotations.
List(ctx context.Conte... |
/*
I'm surprised this hasn't come up in a challenge yet.
Output the IP address of the machine you're running on. You are required to output both the local and external IP addresses.
Local IP address, ie along the default format of 192.168.x.x
Public IP address can be verified by using google https://www.google.co.u... |
package test
import (
"testing"
"github.com/icrowley/fake"
)
func TestInternet(t *testing.T) {
for _, lang := range fake.GetLangs() {
fake.SetLang(lang)
v := fake.UserName()
if v == "" {
t.Errorf("UserName failed with lang %s", lang)
}
v = fake.TopLevelDomain()
if v == "" {
t.Errorf("TopLevelD... |
package blc
import (
"flag"
"fmt"
"log"
"os"
)
type CLI struct{
}
func PrintUsage(){
fmt.Println("Usage: ")
fmt.Println("\tcreateblockchain --创建区块链")
fmt.Println("\taddblock --添加区块")
fmt.Println("\tprintchain --输出区块链信息")
}
func (cli *CLI) create(){
CreateBlockChain([]*Transaction{})
}
func (cli *CLI) add... |
package input
import (
"github.com/sherifabdlnaby/prism/pkg/component"
"github.com/sherifabdlnaby/prism/pkg/job"
)
// Input is a type that sends messages as jobs and waits for a
// response back.
type Input interface {
// JobChan returns a channel used for consuming jobs from
// this type.
JobChan() <-chan job.I... |
package main
import "fmt"
type LinkNode struct {
data interface{}
next *LinkNode
}
type Link struct {
head *LinkNode
tail *LinkNode
}
func (p *Link) InsertHead(data interface{}) {
node := &LinkNode{
data:data,
next:nil,
}
if p.head == nil && p.tail == nil {
p.head = node
p.tail = node
return
}
... |
/*
Copyright (c) 2019 VMware, Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package describer
import (
"context"
"testing"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
apiextv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
"k8s.io/apimachinery/... |
// Copyright (C) 2021 Cisco Systems 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 agr... |
package main
import (
"context"
"flag"
"fmt"
"log"
"time"
sample_data "github.com/psinthorn/gostore/data_generator"
"github.com/psinthorn/gostore/pb"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func main() {
serverAddr := flag.String("port", "", "Server addre... |
package main
import "fmt"
func by2num(num int) string {
if num%2 == 0 {
return "ok"
}
return "no"
}
func main() {
num := 15
if num%2 == 0 {
fmt.Println("even")
} else if num%5 == 0 {
fmt.Println("fives")
} else {
fmt.Println("odd")
}
x, y := 10, 10
if x == 10 && y == 10 {
fmt.Println("both 10")
... |
package golum
import (
"fmt"
"log"
"gonum.org/v1/plot"
"gonum.org/v1/plot/plotter"
"gonum.org/v1/plot/vg"
"github.com/kniren/gota/dataframe"
)
func CreateHistograms(df *dataframe.DataFrame, cols []string) error {
if len(cols) > 0 {
log.Println("Multiple columns")
for _, col := range cols {
dfSel := df... |
package main
//func TestStatistics(t *testing.T) {
// mqttc = NewMQTTMockedClient(t)
// clientID = "testClientID"
// statisticsInterval = 100 * time.Millisecond
// go statistics()
// time.Sleep(1)
// mqttc.Connect()
// time.Sleep(1 * time.Second)
//}
|
package main
import "fmt"
//抽象的业务员
type AbstractBanker interface {
DoBusi() //抽象的接口 ,业务接口
}
//存款的业务员
type SaveBanker struct {
AbstractBanker
}
func (sb *SaveBanker) DoBusi () {
fmt.Println("进行的存款")
}
//转账的业务员
type TransBanker struct {
AbstractBanker
}
func (sb *TransBanker) DoBusi () {
fmt.Println("进行的转账")
... |
package comm
import (
"encoding/json"
"fmt"
"github.com/go-redis/redis"
"github.com/smilga/analyzer/api"
)
type list string
type userList string
const (
PendingList userList = "pending:websites:user:"
TimeoutedList userList = "timeouted:websites:user:"
ListsList list = "pending:list... |
package server
import (
"context"
v1 "github.com/i-coder-robot/go-grpc-http-rest-microservice-todo/api/proto/v1"
"github.com/i-coder-robot/go-grpc-http-rest-microservice-todo/cmd/middleware"
"github.com/i-coder-robot/go-grpc-http-rest-microservice-todo/logger"
"google.golang.org/grpc"
"net"
"os"
)
func RunServ... |
package base
import (
"gengine/context"
)
type Constant struct {
ConstantValue interface{}
knowledgeContext *KnowledgeContext
dataCtx *context.DataContext
}
func (cons *Constant) AcceptString(str string) error {
cons.ConstantValue = str
return nil
}
func (cons *Constant) Initialize(kc *KnowledgeCo... |
// Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
// encapsulates standard host entities into a simple interface
package wasmlib
import (
"strconv"
)
type PostRequestParams struct {
ContractId *ScContractId
Function ScHname
Params *ScMutableMap
Transfer balances
Delay int64
}... |
package gomailer
import (
"bytes"
"html/template"
"path/filepath"
"strings"
)
const (
DefaultLayoutExtension = "html"
TemplateRoot = `{{define "root" }} {{ template "main" . }} {{ end }}`
)
type TemplateConfig struct {
LayoutFiles []string
LayoutDirectory string
LayoutExtension string
}
type ... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//335. Self Crossing
//You are given an array x of n positive numbers. You start at point (0,0) and moves x[0] metres to the north, then x[1] metres to... |
package model
type ResponseError struct {
// Unique correlation id
RequestId string `json:"requestId,omitempty"`
// Response status information
Status ResponseStatus `json:"status,omitempty"`
// Response information
Data *ResponseErrorData `json:"data,omitempty"`
}
|
package engine
import (
"crypto/rand"
"encoding/hex"
"fmt"
"log"
"path/filepath"
"time"
"orbit.sh/engine/gluster"
)
// Volume is a distributed block storage volume propagated by GlusterFS.
type Volume struct {
ID string `json:"id"`
Name string `json:"name"` // The short (friendly) name for the vol... |
package utils
import (
"os"
"path/filepath"
"time"
)
func CheckErr(err error) {
if err != nil {
Logs(err.Error())
}
}
//打印日志
func Logs(s string) {
dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
fd, _ := os.OpenFile(filepath.Join(dir, "logs.log"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
fd.WriteString(t... |
package util
import (
"bytes"
"encoding/xml"
"errors"
"fmt"
"regexp"
"strconv"
)
/*
xml to map:XmlToMapString
*/
type Node struct {
dup bool // is member of a list
attr bool // is an attribute
key string // XML tag
val string // element value
nodes []*Node
}
func XmlToXmlMap(doc string, recast... |
package main
import (
"fmt"
)
// 引数にいろいろな型を持たせたい時に,interface{}を引数に設定する。
// その後、type assertion
func do(i interface{}) {
ii := i.(int) // type assertion. intであることを確認
ii *= 2
fmt.Println(ii)
}
// switch type
func do2(i interface{}) {
switch v := i.(type) {
case int:
fmt.Println(v * 2)
case string:
fmt.Printl... |
package main
import (
"fmt"
"os"
"sort"
"strings"
"time"
"github.com/hashicorp/go-version"
"github.com/olekukonko/tablewriter"
"github.com/urfave/cli"
git "gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing"
gitobj "gopkg.in/src-d/go-git.v4/plumbing/object"
)
// command flags
var short = false
v... |
package api
import (
"github.com/valyala/fasthttp"
"net/http"
)
func ProcessOptions(ctx *fasthttp.RequestCtx) {
ctx.Response.Header.Set("Access-Control-Allow-Origin", "http://localhost:8080")
ctx.Response.Header.Set("Access-Control-Allow-Credentials", "true")
ctx.Response.Header.Set("Access-Control-Allow-Headers... |
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 main
import (
"fmt"
"math/rand"
"sync"
"time"
)
var wg sync.WaitGroup
func send() {
defer wg.Done()
ch := make(chan int, 1)
for {
num := rand.Intn(10)
ch <- num
time.Sleep(time.Second * 2)
}
}
func main() {
wg.Add(1)
go send()
fmt.Println("over")
wg.Wait()
}
|
package parser_test
import (
"testing"
"github.com/romshark/llparser/examples/dicklang/parser"
"github.com/stretchr/testify/require"
)
func TestParser(t *testing.T) {
src := `
B===> 8==> B::>
<====8 <::::::3
8xxxx> 8xxx=xxx>
B:x:=:x>
<:=3
`
mod, err := parser.Parse("sample.dicklang", []rune(src))
r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.