text stringlengths 11 4.05M |
|---|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package azurestack
import (
"fmt"
"net/http"
"os"
"github.com/Azure/aks-engine/pkg/armhelpers/azurestack/testserver"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2017-03-30/compute"
"github.com/Azure/go-... |
package tasks
import (
"crypto/rand"
"math/big"
"time"
)
type PeriodicTask struct {
Task func()
InitialDuration time.Duration
IntervalDuration time.Duration
JitterDuration time.Duration
quit chan bool
done chan bool
}
func (t *PeriodicTask) Start() {
if t.quit == nil {
t.quit = make(chan bool, 1)
}... |
package controllers
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"github.com/books-list/models"
"github.com/books-list/repository/bookRepository"
"github.com/gorilla/mux"
)
var books []models.Book
type Controller struct{}
func (c Controller) GetBooks(db *sql.DB) http.HandlerFun... |
package humanize
import (
"fmt"
"go/ast"
)
// Function is functions with name, not the func types
type Function struct {
pkg *Package
file *File
Name string
Docs Docs
Type *FuncType
Receiver *Variable // Nil means normal function
}
// String convert function object to go code
func (f *Function)... |
package runner
import (
"sync"
discoveryv1 "github.com/syncromatics/kafmesh/internal/protos/kafmesh/discovery/v1"
"github.com/pkg/errors"
)
var (
serviceSetup sync.Once
)
// ServiceDiscovery provides service information for discovery
type ServiceDiscovery struct {
Name string
Description string
}
// ... |
/*Package eventual is a simple event dispatcher for golang base on channels.
The goal is to pass data arond, without depending to any package except for this
one.
There is some definition :
- Mandatory means publish is not finished unless all subscribers receive the message,
in this case, the receiver must always rea... |
package node
import log "code.google.com/p/log4go"
import "github.com/d-d-j/ddj_master/dto"
var NodeManager = NewManager()
//This structure is used to get node. Node is returned on BackChan
type GetNodeRequest struct {
NodeId int32
BackChan chan<- *Node
}
//Manager is an object that takes car of nodes and they ... |
/*
Copyright 2020 Skyscanner Limited.
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 (
"gopkg.in/alecthomas/kingpin.v2"
"mingchuan.me/app"
)
func main() {
var (
configPath = kingpin.Flag("config", "config path").Default("config.yml").Short('c').String()
)
// parse argv
kingpin.Parse()
// start App
err := app.Start(*configPath)
if err != nil {
panic(err)
}
}
|
package ondemand
import (
"fmt"
"strings"
)
// Competitors https://www.barchart.com/ondemand/api/getCompetitors
type Competitors struct {
Results []struct {
Symbol string `json:"symbol"`
Name string `json:"name"`
MarketCap int64 `json:"marketCap"`
FiftyTwoWkHigh f... |
package resources_test
import (
"testing"
"themis/utils"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
func TestResources(t *testing.T) {
// setup logger
utils.InitLogger()
utils.SetLogFile("test.log")
RegisterFailHandler(Fail)
RunSpecs(t, "Resources Suite")
}
|
// Copyright 2023 Google LLC. 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 applica... |
/*
The mode of a group of numbers is the value (or values) that occur most often (values have to occur more than once).
Given a sorted array of numbers, return an array of all modes in ascending order.
Notes
In this challenge, all group of numbers will have at least one mode.
*/
package main
import (
"fmt"
)
fu... |
package chapter8
import (
"fmt"
"testing"
)
func TestSearchPostingsListRecursive(t *testing.T) {
a := &PostingsListElement{Value: 1, Order: -1}
b := &PostingsListElement{Value: 2, Order: -1}
c := &PostingsListElement{Value: 3, Order: -1}
d := &PostingsListElement{Value: 4, Order: -1}
a.Next = b
b.Next = c
c... |
// Copyright 2013 The Go Circuit Project
// Use of this source code is governed by the license for
// The Go Circuit Project, found in the LICENSE file.
//
// Authors:
// 2013 Petar Maymounkov <p@gocircuit.org>
package main
import (
"flag"
"github.com/gocircuit/runtime/boot"
"github.com/gocircuit/runtime/circuit... |
package main
// 如果返回值命名了,可以通过名字来修改返回值,也可以通过defer语句在return语句之后修改返回值。
// 其中defer语句延迟执行了一个匿名函数,因为这个匿名函数捕获了外部函数的局部变量v,这种函数我们一般称之为闭包。
// 闭包对捕获的外部变量并不是以传值方式访问,而是以引用方式访问。
func Inc() (v int) {
defer func() {
v++ // 在函数return 之后会执行++ 42+1= 43
}()
return 42
}
|
package problem0501
//TreeNode 树节点
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func findMode(root *TreeNode) []int {
result := []int{}
if root == nil {
return result
}
maxTimes := 0
curTimes := 0
stack := []*TreeNode{}
cur := root
var prev *TreeNode
for cur != nil || len(stack) > ... |
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile("i")
fmt.Println(re.ReplaceAllString("sift rise", "o"))
} |
package dictator
import (
"crypto/rand"
"crypto/sha1"
"errors"
"fmt"
"math/big"
"time"
"gopkg.in/mgo.v2/bson"
)
type (
DictatorPayload struct {
Type int
Blob []byte
DictatorID string
}
NodeContext struct {
NodeID string
BecomeDictator *time.Timer
SuicideChan chan stru... |
package mapreduce
import (
"encoding/json"
"log"
"os"
"sort"
)
// !!! Define ByKey
type ByKey []KeyValue
func (a ByKey) Len() int {
return len(a)
}
func (a ByKey) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a ByKey) Less(i, j int) bool {
return a[i].Key < a[j].Key
}
// doReduce manages one reduce task... |
package main
import (
"fmt"
"os"
"strings"
. "github.com/colefan/gsgo/tools/packettool"
"github.com/colefan/gsgo/tools/utils"
)
//Useage: packettool.exe xmlpath storepath
//
func main() {
xmlPath := ""
storePath := ""
if len(os.Args) < 3 {
fmt.Println("Useage:packettool.exe protocol_desc_file packet_store_... |
package deprecated
type Deprecation struct {
DeprecatedSince int
AlternativeAvailableSince int
}
var Stdlib = map[string]Deprecation{
// FIXME(dh): AllowBinary isn't being detected as deprecated
// because the comment has a newline right after "Deprecated:"
"go/build.AllowBinary": ... |
package main
import "fmt"
func main() {
fmt.Println("This is main function!!")
fmt.Println(sum(1, 2))
}
var sum = func(a, b int) int {
return a + b
}
|
// Package document - пакет обеспечивает создание структур документа реализующих контракт Documenter
package document
import (
"fmt"
"regexp"
"strings"
)
type Documenter interface {
Id() int
Title() string
Words() []string
fmt.Stringer
}
type WebPage struct {
id int
title string
url string
Documenter
}
f... |
package main
import (
"fmt"
"log"
"math/big"
"time"
)
func main() {
start := time.Now()
r := new(big.Int)
fmt.Println(r.Binomial(1000, 10))
elapsed := time.Since(start)
log.Printf("Binomial took %s", elapsed)
}
|
package main
import (
"fmt"
"github.com/jackytck/projecteuler/tools"
)
func extend(d []int) []int {
ret := d
if tools.IncludesInt(d, 6) && !tools.IncludesInt(d, 9) {
ret = append(d, 9)
}
if tools.IncludesInt(d, 9) && !tools.IncludesInt(d, 6) {
ret = append(d, 6)
}
return ret
}
func isValidPair(d1, d2 []... |
package queue
import "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer"
// PeerQueue maintains a set of peers ordered according to a metric.
// Implementations of PeerQueue could order peers based on distances along
// a KeySpace, latency measurements, trustworthiness, reputation, etc.
type PeerQ... |
package intstr
import "k8s.io/apimachinery/pkg/util/intstr"
// convenience func to get a pointer
func ParsePtr(val string) *intstr.IntOrString {
x := intstr.Parse(val)
return &x
}
|
package main
import "fmt"
func main() {
var n int
fmt.Scan(&n)
phoneBook := make(map[string]int)
for i := 0; i < n; i++ {
var (
name string
phoneNumber int
)
fmt.Scan(&name, &phoneNumber)
phoneBook[name] = phoneNumber
}
for {
var name string
if _, err := fmt.Scan(&name); err != nil... |
package tcp
import (
"encoding/binary"
"chat-system/log"
"chat-system/util"
)
type INetMsg interface {
Clone() INetMsg
Version() uint8
SetVersion(version uint8)
CheckCode() uint8
SetCheckCode(code uint8)
PackLen() uint16
SetPackLen(length uint16)
MainCmd() uint16
SetMainCmd(cmd uint16)
SubCmd() uint16
... |
/*
* @lc app=leetcode.cn id=150 lang=golang
*
* [150] 逆波兰表达式求值
*/
// @lc code=start
// 前提是 s 是有效的表达式
package main
import "fmt"
import "strconv"
func isOperator(s string) bool {
return s == "+" || s == "-" || s == "*" || s == "/"
}
func doOperate(a, b int, ope string) (res int){
switch ope {
case "+":
res ... |
// Copyright 2017 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 (
"flag"
"fmt"
"github.com/kjirou/tower-of-go/controller"
"github.com/kjirou/tower-of-go/views"
"github.com/nsf/termbox-go"
"math/rand"
"time"
)
func drawTerminal(screen *views.Screen) {
screen.ForEachCells(func (y int, x int, symbol rune, fg termbox.Attribute, bg termbox.Attribute) {
//... |
package main
import (
"log"
"net/http"
"github.com/garyburd/redigo/redis"
"github.com/felipeguilhermefs/restis/commands/global"
"github.com/felipeguilhermefs/restis/commands/hashes"
"github.com/felipeguilhermefs/restis/commands/lists"
"github.com/felipeguilhermefs/restis/commands/sets"
"github.com/fe... |
// 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 main
import (
"net/http"
)
// Message struct
type Message struct {
Name string `json:"name"`
Data interface{} `json:"data"`
}
// Channel struct
type Channel struct {
ID string `json:"id"`
Name string `json:"name"`
}
func main() {
router := NewRouter()
router.Handle("channel add", addChannel)
... |
package taskflow
import (
"github.com/Huawei/eSDK_K8S_Plugin/src/utils"
"github.com/Huawei/eSDK_K8S_Plugin/src/utils/log"
)
type TaskRunFunc func(params map[string]interface{}, result map[string]interface{}) (map[string]interface{}, error)
type TaskRevertFunc func(result map[string]interface{}) error
type Task str... |
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
)
var programName string
var programVersion = "3.0.0"
func init() {
programName = filepath.Base(os.Args[0])
}
func main() {
commands := map[string]command{
"ruler": makeRulerCommand(),
"version": makeVersionCommand(),
}
flag.Usage = func() {
f... |
// Copyright 2017 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 ratecounter
import (
"strconv"
"time"
)
// An AvgRateCounter is a thread-safe counter which returns
// the ratio between the number of calls 'Incr' and the counter value in the last interval
type AvgRateCounter struct {
hits *RateCounter
counter *RateCounter
interval time.Duration
}
// NewAvgRateCo... |
package main
import (
"encoding/json"
"log"
"strings"
"github.com/kataras/iris"
"github.com/kataras/iris/websocket"
)
func main() {
app := iris.New()
app.Get("/", func(ctx iris.Context) {
ctx.ServeFile("websockets.html", false) // second parameter: enable gzip?
})
setupWebsocket(app)
app.Run(iris.Addr... |
// Copyright 2023 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
/*
Create a function that takes two parameters and, if both parameters are strings, add them as if they were integers or if the two parameters are integers, concatenate them.
Examples
stupid_addition(1, 2) ➞ "12"
stupid_addition("1", "2") ➞ 3
stupid_addition("1", 2) ➞ None
Notes
If the two parameters are diff... |
// Package rest allows for quick and easy access any REST or REST-like API.
package rest
import (
"errors"
"net/http"
"net/url"
)
// Method contains the supported HTTP verbs.
type Method string
// Supported HTTP verbs.
const (
Get Method = "GET"
Post Method = "POST"
Put Method = "PUT"
Patch Method = ... |
package problems
func removeElement(nums []int, val int) int {
var nLen int
for i := 0; i < len(nums); i++ {
if nums[i] != val {
nums[nLen] = nums[i]
nLen++
}
}
return nLen
}
// less assignment
func removeElement1(nums []int, val int) int {
i, nLen := 0, len(nums)
for i < nLen {
if nums[i] == val ... |
// 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... |
// exibe os argumentos da linha de comando
// arataca89@gmail.com
// 20210413
package main
import (
"fmt"
"os"
)
func main() {
for indice, valor := range os.Args[:] {
fmt.Println(indice, " - ", valor)
}
}
/////////////////////////////////////////////////////////////////////
//
// Exemplo do u... |
package main
import (
"testing"
"time"
"github.com/go-redis/redis"
)
func TestMain(t *testing.T) {
client := redis.NewClient(&redis.Options{})
t.Log(client.SetNX("key", "value", 10*time.Second).Result())
t.Log(client.Get("key").Result())
}
|
package vsock
// GetContextID returns the local Context Identifier for the VSOCK socket
// address family. This may be a privileged operation.
func GetContextID() (uint32, error) {
return getContextID()
}
|
package detector
import (
"fmt"
"strings"
"github.com/hashicorp/hcl/hcl/ast"
"github.com/wata727/tflint/issue"
)
type TerraformModulePinnedSourceDetector struct {
source string
line int
file string
}
func NewTerraformModulePinnedSourceDetector(detector *Detector, file string, item *ast.ObjectItem) *Terra... |
package main
import (
"flag"
"fmt"
"github.com/dominikh/arp"
"os"
)
var (
dash string
count int
itf string
num = 0
)
func handler(w arp.ResponseSender, r *arp.Request) {
if r.SenderHardwareAddr.String() == dash && r.SenderIP.String() == "0.0.0.0" {
num += 1
fmt.Printf("Dash %d!\n", num)
if count ... |
package arima
import (
"math"
"github.com/DoOR-Team/goutils/log"
"github.com/DoOR-Team/timeseries_forecasting/arima/matrix"
)
func Fit(data []float64, p int) []float64 {
length := len(data)
if length == 0 || p < 1 {
log.Fatalf(
"fitYuleWalker - Invalid Parameters length= %d, p ", length, p)
}
r := make... |
package main
import (
. "awesomeProject/internal/app/db/servicesDAO"
. "awesomeProject/internal/app/model"
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"gopkg.in/mgo.v2/bson"
"log"
"net/http"
)
var servicesDAO = ServicesDAO{}
func AllServicesEndPoint(w http.ResponseWriter, r *http.Request) {
services, err... |
package main
import "github.com/01-edu/z01"
func main() {
var var1 = 'z'
for var1 >= 'a' {
z01.PrintRune(var1)
var1--
}
z01.PrintRune(10)
}
|
package secrets
import (
"errors"
"testing"
"github.com/10gen/realm-cli/internal/cli"
"github.com/10gen/realm-cli/internal/cloud/realm"
"github.com/10gen/realm-cli/internal/utils/test/assert"
"github.com/10gen/realm-cli/internal/utils/test/mock"
)
func TestSecretsCreateHandler(t *testing.T) {
projectID := "pr... |
package main
import (
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"time"
"github.com/gorilla/websocket"
"github.com/wuxc/gowebwx/webwx"
)
var upgrader = websocket.Upgrader{}
func serveWs(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("... |
package healthcheck
import (
"context"
"google.golang.org/grpc/health/grpc_health_v1"
)
type HealthChecker struct{}
func (s *HealthChecker) Check(_ context.Context, _ *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error) {
return &grpc_health_v1.HealthCheckResponse{
Status: grpc_heal... |
package user
import (
"context"
"sync"
"time"
google_protobuf2 "github.com/gogo/protobuf/types"
proto "github.com/weisd/web-kit/api/protobuf/user"
"github.com/weisd/web-kit/internal/pkg/ierrors"
"github.com/weisd/web-kit/internal/pkg/istring"
)
// var _ proto.RPCServiceServer = &MemoryServer{}
var _ RPCServer... |
package main
import (
"encoding/json"
"html/template"
"log"
"net/http"
"net/url"
)
// Client contains infomation of a client
type Client struct {
ClientID string
ClientSecret string
RedirectURIs []string
Scope string
}
// Service contains AuthServer and its Clients
type Service struct {
Clients ... |
package daemon
import (
"context"
"fmt"
"sync"
"time"
"github.com/hashicorp/serf/serf"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/klog"
"github.com/xmwilldo/edge-health/cmd/app-health/app/options"
"github.com/xmwilldo/edge-health/pkg/app-health-daemon/server"
)
type AppDaemon struct {
serf *serf.Ser... |
package g2util
import (
cRand "crypto/rand"
"math/big"
"math/rand"
)
// CryptoRandInt ...
func CryptoRandInt(n int) *big.Int {
b, _ := cRand.Int(cRand.Reader, big.NewInt(int64(n)))
return b
}
// MathRandInt ...
func MathRandInt(n int) int { return rand.Intn(n) }
|
package middlewares
import (
"errors"
"fmt"
"github.com/Highway-Project/highway/config"
"github.com/Highway-Project/highway/logging"
"github.com/Highway-Project/highway/pkg/middlewares"
"github.com/Highway-Project/highway/pkg/middlewares/cors"
"github.com/Highway-Project/highway/pkg/middlewares/nothing"
"githu... |
/*
* Copyright 2020 American Express Travel Related Services Company, 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 requ... |
--- vendor/github.com/modern-go/reflect2/go_below_118.go.orig 2022-04-16 21:56:08 UTC
+++ vendor/github.com/modern-go/reflect2/go_below_118.go
@@ -0,0 +1,21 @@
+//+build !go1.18
+
+package reflect2
+
+import (
+ "unsafe"
+)
+
+// m escapes into the return value, but the caller of mapiterinit
+// doesn't let the return ... |
package main
import (
"io/ioutil"
)
func main() {
a, err := ioutil.ReadFile("crc.ascii")
if err != nil {
panic(err)
}
b := []byte{0, 0, 0, 0}
for k := 0; k < 8; k++ {
if a[k] > 0x4f {
a[k] = a[k] - 0x20
}
if a[k] > 0x39 {
a[k] = a[k] - 7
}
}
b[0] = ((a[6] - 0x30) * 0x10) + (a[7] - 0x30)
b[1]... |
package cmd
import (
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"math/rand"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/google/uuid"
"helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/lint/support"
"sigs.k8s.io/kustomize/kyaml/yaml"
"github.com/dollarshaveclub/acyl/pkg... |
package instruction
// CountSteps returns a number of step required to reach the end of slice
// when instruction is incremented by 1 after jump
func CountSteps(instructions []int) int {
return count(instructions, func(n int) int { return n + 1 })
}
// CountStrangeSteps returns a number of step required to reach the... |
package html
import (
"github.com/elliotchance/gedcom"
"regexp"
"strings"
)
var alnumOrDashRegexp = regexp.MustCompile("[^a-z_0-9-]+")
func GetIndividuals(document *gedcom.Document, placesMap map[string]*place) map[string]*gedcom.IndividualNode {
individualMap := map[string]*gedcom.IndividualNode{}
for _, indi... |
// Copyright 2022 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 (
"context"
"errors"
"flag"
"os"
"github.com/cybozu-go/log"
"github.com/cybozu-go/well"
"github.com/fsnotify/fsnotify"
)
func main() {
flag.Parse()
err := well.LogConfig{}.Apply()
if err != nil {
log.ErrorExit(err)
}
if len(flag.Args()) == 0 {
log.ErrorExit(errors.New("please spe... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//29. Divide Two Integers
//Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
//Ret... |
package coremidi
import (
"errors"
"fmt"
"syscall"
"unsafe"
)
/*
#cgo LDFLAGS: -framework CoreMIDI -framework CoreFoundation
#include <CoreMIDI/CoreMIDI.h>
#include <stdio.h>
#include <unistd.h>
static void MIDIInputProc(const MIDIPacketList *pktlist, void *readProcRefCon, void *srcConnRefCon)
{
MIDIPacket *p... |
package service
import (
"encoding/json"
"fmt"
"github.com/bar41234/bar_book_service/datastore"
"github.com/bar41234/bar_book_service/models"
"github.com/gin-gonic/gin"
"net/http"
)
const (
errorMsgInvalidPutRequest = "Error: Invalid PUT request"
errorMsgInvalidPostRequest = "Error: Invalid POST request"
)
... |
package exercise
import (
"fmt"
)
func TestCfb() {
for a := 1; a < 10; a++ { // 行
for b := 1; b <= a; b++ { // 列
fmt.Printf("%d*%d = %d ", b, a, b*a)
}
fmt.Println()
}
}
|
package util
import (
"github.com/go-playground/locales/id"
ut "github.com/go-playground/universal-translator"
"github.com/labstack/echo/v4"
"gopkg.in/go-playground/validator.v9"
idTrans "gopkg.in/go-playground/validator.v9/translations/id"
)
// CustomValidator validation that handle validation
type CustomValida... |
////////////////////////////////////////////////////////////////////////////////
// //
// Copyright 2019 Broadcom. The term Broadcom refers to Broadcom Inc. and/or //
// its subsidiaries. ... |
package main
import (
"bufio"
"fmt"
"math"
"os"
"strconv"
)
func readInput() []int64 {
f, _ := os.Open("input.txt")
defer f.Close()
input := make([]int64, 0)
scanner := bufio.NewScanner(f)
for scanner.Scan() {
num, _ := strconv.ParseInt(scanner.Text(), 10, 64)
input = append(input, num)
}
return inpu... |
package main
import (
"flag"
)
func main() {
flag.Parse()
app, cleanup, err := initApp()
if err != nil {
panic(err)
}
defer cleanup()
// start and wait for stop signal
if err := app.Run(app.GetConfig().GetHttp().LocalAddr); err != nil {
panic(err)
}
}
|
package memory
import (
"io"
"sync"
"github.com/delgus/def-parser/internal/app"
)
// Queue реализует очередь безопасную для вызова в асинхронных потоках
type Queue struct {
tasks []app.HostTask
mu sync.Mutex
}
// NewQueue вернет новую очередь
func NewQueue() *Queue {
return &Queue{}
}
// Add реализует доб... |
/*
* winnow: weighted point selection
*
* input:
* matrix: an integer matrix, whose values are used as masses
* mask: a boolean matrix showing which points are eligible for
* consideration
* nrows, ncols: the number of rows and columns
* nelts: the number of points to select
*
* output:
* point... |
package websocket_route
import (
"encoding/binary"
"github.com/changx123/websocket-sync"
"bytes"
)
//钩子常量
const (
//新连接通知
HOOK_NEW_CONN = "new conn"
//连接closed 通知
HOOK_CLOSED = "closed"
//错误通知
HOOK_ERROR = "error"
//路由寻址不存在
HOOK_NOT_MODULE = "not module"
//发送消息通知
HOOK_WRITE_MESSAGE = "write message"
... |
package main
import "fmt"
func main() {
//Explicit declaration
var sentence string = "A string"
//Implicit declaration
var number = 256.98
//Implicit variable declaration may cause the compiler to assign the wrong type
//This only happens in very, very rare occasions
//Expression assignment operator
//Bas... |
package main
import (
"container/ring"
"fmt"
"jblee.net/adventofcode2018/utils"
)
func main() {
line := utils.ReadLinesOrDie("input.txt")[0]
var numPlayers, maxPointValue int
fmt.Sscanf(line, "%d players; last marble is worth %d points",
&numPlayers, &maxPointValue)
currentMarble := ring.New(1)
currentMa... |
package format_test
import (
"testing"
"github.com/g-harel/gothrough/internal/types"
"github.com/g-harel/gothrough/internal/types/format"
)
func TestString(t *testing.T) {
tt := map[string]struct {
Input types.Type
Expected string
}{
"simple interface": {
Input: &types.Interface{
Name: "Test",
... |
package public
import (
"context"
"gorm.io/gorm"
"strings"
"tpay_backend/merchantapi/internal/common"
"tpay_backend/model"
"tpay_backend/utils"
"tpay_backend/merchantapi/internal/svc"
"tpay_backend/merchantapi/internal/types"
"github.com/tal-tech/go-zero/core/logx"
)
type WithdrawLogic struct {
logx.Logge... |
package compress
import (
"bufio"
"bytes"
"compress/flate"
"errors"
"io"
"io/ioutil"
"github.com/gobwas/pool/pbufio"
)
const (
maxCompressionLevel = flate.BestCompression
minCompressionLevel = -2
)
var (
ErrWriteClose = errors.New("write to closed writer")
ErrUnexpectedEndOfStream = errors.New... |
package txsizes
import (
"bytes"
"encoding/hex"
"testing"
"github.com/btcsuite/btcd/wire"
)
const (
p2pkhScriptSize = P2PKHPkScriptSize
p2shScriptSize = 23
)
func makeInts(value int, n int) []int {
v := make([]int, n)
for i := range v {
v[i] = value
}
return v
}
func TestEstimateSerializeSize(t *testi... |
package test
import (
"testing"
"reflect"
"strings"
"encoding/json"
"github.com/trevershick/analytics2-cli/a2m/rest"
)
/* Test Helpers */
func AssertEquals(t *testing.T, expected interface{}, actual interface{}) {
if expected != actual {
t.Errorf("Expected %v (type %v) - Got %v (type %v)", expected, reflect.T... |
package stemmer
import (
"strings"
)
type PorterStemmer interface {
Stem(string) (string, error)
}
//stem a word
func Stem(origWord string) string {
if len(origWord) > 2 {
return step5b(step5a(step4(step3(step2(step1(strings.TrimSpace(origWord)))))))
}
return origWord
}
//Step 1 deals with plurals and past ... |
package main
import (
"fmt"
"sync"
"time"
)
func main() {
// lock()
// rwlock()
wg()
}
func lock() {
var m sync.Mutex
m.Lock()
go func() {
time.Sleep(3 * time.Second)
m.Unlock()
fmt.Println("unlock1")
}()
// var m2 sync.Mutex // もちろんこれだと意味ない
// m2.Lock()
m.Lock()
fmt.Println("この手前でブロック")
m.Unloc... |
package src
func Pass3(compiler *Compiler, RootAST *RootAST) *RootAST {
return RootAST
} |
package gojsonq
import (
"encoding/json"
"fmt"
"reflect"
"strings"
"testing"
)
func TestNew(t *testing.T) {
jq := New()
if reflect.ValueOf(jq).Type().String() != "*gojsonq.JSONQ" {
t.Error("failed to match JSONQ type")
}
}
func TestJSONQ_String(t *testing.T) {
jq := New()
expected := fmt.Sprintf("\nConte... |
package main
import (
"fmt"
"plugin"
)
func main() {
// 插件目录
p, err := plugin.Open("./plugin/plugin.so")
if err != nil {
panic(err)
}
// 加载插件方法
add, err := p.Lookup("Add") // 方法名必须与插件的方法名一致,区分大小写
if err != nil {
panic(err)
}
sub, err := p.Lookup("Subtract")
if err != nil {
panic(err)
}
// 运行插件方法... |
package gcppubsub
import (
"fmt"
"time"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"github.com/pkg/errors"
"github.com/batchcorp/plumber-schemas/build/go/protos/records"
"github.com/batchcorp/plumber/printer"
)
// DisplayMessage will parse a Read record and print (pretty) output to STDOUT
fun... |
package plantuml
import (
"io"
)
type Package struct {
name string
children []Renderable
}
func NewPackage(name string) *Package {
return &Package{name: name}
}
func (p *Package) Add(r ...Renderable) *Package {
p.children = append(p.children, r...)
return p
}
func (p *Package) Render(wr io.Writer) error ... |
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"time"
"github.com/julienschmidt/httprouter"
"github.com/peter-mueller/sit-o-mat/httperror"
"github.com/peter-mueller/sit-o-mat/sitomat"
"github.com/peter-mueller/sit-o-mat/user"
"github.com/peter-mueller/sit-o-mat/workplace"
"fmt"
_ "gocloud.... |
package x
// GENERATED BY XO. DO NOT EDIT.
import (
"errors"
"strings"
//"time"
"strconv"
"github.com/jmoiron/sqlx"
)
// (shortname .TableNameGo "err" "res" "sqlstr" "db" "XOLog") -}}//(schema .Schema .Table.TableName) -}}// .TableNameGo}}// PostKeys represents a row from 'sun.post_keys'.
// Manualy copy this ... |
/*
Copyright 2021 CodeNotary, 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 law or agreed to i... |
package noop
import "go.mercari.io/datastore"
var _ datastore.Middleware = &noop{}
// New no-op middleware creates and returns.
func New() datastore.Middleware {
return &noop{}
}
type noop struct {
}
func (*noop) AllocateIDs(info *datastore.MiddlewareInfo, keys []datastore.Key) ([]datastore.Key, error) {
return ... |
// 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.