text stringlengths 11 4.05M |
|---|
package main
import (
"fmt"
"regexp"
"strconv"
)
// ok, _ := regexp.Match(pat, []byte(searchIn))
// ok, _ := regexp.MatchString(pat, searchIn)
func main() {
//目标字符串
searchIn := "John: 2578.34 William: 4567.23 Steve: 5632.18"
pattern := "[0-9]+.[0-9]+" //正则
f := func(s string) string {
v, _ := strconv.Parse... |
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package cca provides utilities to interact with Chrome Camera App.
package cca
import (
"context"
"fmt"
"math"
"regexp"
"time"
"chromiumos/tast/common/perf"
"chro... |
package main
import (
"fmt"
)
func main(){
for i, course := range topoSort(prereqs) {
fmt.Printf("%d:\t%s\n", i+1, course)
}
}
func topoSort(m map[sring][]string){
seen := make(map[string]bool)
var visitAll func(items []string)
visitAll = func(items []string){
for item := range m {
if !seen[item] {
... |
package main
import (
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
func main() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
log.Info().
Str("Scale", "833 cents").
Float64("Interval", 833.09).
Msg("Fibonacci is everywhere")
log.Print("Print")
log.Trace().Msg("Trace")
log.Debug().Msg("De... |
package main
import (
"bytes"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"github.com/gorilla/mux"
)
var groupID = -1001288115081
type reqBody struct {
ChatID int64 `json:"chat_id"`
Text string `json:"text"`
}
type sendMessageReqBody struct {
ChatID in... |
package parser
import (
"testing"
"github.com/amsa/doop/common"
"github.com/stretchr/testify/assert"
)
func TestSelect(t *testing.T) {
parser := MakeSqlParser()
sql, err := parser.Parse(`SELECT * FROM users;`)
common.HandleError(err)
assert.Equal(t, "SELECT", sql.Op)
assert.Equal(t, "users", sql.TblName)
as... |
package mint
import "fmt"
// MaskString6P4 masks a string exposing first 6 and 4 last symbols, like: YeAHCqTJk4aFnHXGV4zaaf3dTqJkdjQzg8TJENmP3zxDMpa97 => YeAHCq***pa97
func MaskString6P4(s string) string {
charz := []rune(s)
if len(charz) <= 10 {
return s
}
return fmt.Sprintf("%s***%s", string(charz[0:6]), stri... |
package log
import (
"os"
"github.com/op/go-logging"
)
var Log = logging.MustGetLogger("FrankLog")
var format = logging.MustStringFormatter(
`%{color}%{level:.4s} %{time:15:04:05.000} %{shortfunc} ▶%{color:reset} %{message}`,
)
func InitLogger() {
backend := logging.NewLogBackend(os.Stderr, "", 0)
formatter ... |
package bd
import (
"context"
"time"
"github.com/paolapesantez/avatweet-server/models"
)
/*EliminarRelacion borra la relación en la bd */
func EliminarRelacion(relacion models.Relacion) (bool, error) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
db := MongoCN.Databa... |
package logger
import (
"fmt"
"github.com/stretchr/testify/assert"
"testing"
)
func TestUnmarshalText(t *testing.T) {
cases := map[string]struct {
input string
output Level
err error
}{
"select log level Not_A_Level": {"Not_A_Level", 0, ErrInvalidLogLevel},
"select log level Bad_Input": {"Bad_Inp... |
package models
type TgAdminUserMoneyRecharge struct {
Id int `xorm:"primary_key autoincr comment('') INT(11)" json:"id"`
Uid int `xorm:"int(10)" json:"uid"`
Cid int `xorm:"int(10)" json:"cid"`
Way string `xorm:"varchar(200)" json:"way"`
Money float64 `xorm:"decimal(10,2)" json:"money"`
C... |
package shlex
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/tilt-dev/tilt/internal/tiltfile/starkit"
)
func TestQuote(t *testing.T) {
f := starkit.NewFixture(t, NewPlugin())
f.File("Tiltfile", `
s = shlex.quote("foo '$FOO'")
print(shlex.quote("foo '$FOO'"))
`)
_, err := f.ExecFile("T... |
package main
import (
"fmt"
"os"
"encoding/csv"
"io/ioutil"
"database/sql"
_ "github.com/mattn/go-sqlite3"
"strings"
"flag"
"github.com/pkg/errors"
"path"
)
type GTFSFile struct {
name string
fields []string
}
func main() {
var gtfsDir string
var dbPath string
var batchSize int
flag.StringVar(>fs... |
package controllers
import "edwardhey.com/football/wx/models"
type AsyncschedulerController struct {
BaseController
}
func (c *AsyncschedulerController) DeactiveActivity() {
c.IsJSON = true
// safe := &io.LimitedReader{R: c.Ctx..Context.Request.Body, N: 100000000}
_id, err := c.GetInt64("ID")
if err != nil {
... |
package main
import (
"fmt"
"os"
"github.com/kavirajk/gojek/battleship/game"
)
func main() {
g := game.New(os.Stdin)
g.Play()
fmt.Println("Player1")
fmt.Println(g.Grid1)
fmt.Println("Player2")
fmt.Println(g.Grid2)
p1Score := g.P1Score()
p2Score := g.P2Score()
fmt.Println("P1:", p1Score)
fmt.Println("P2... |
package ravendb
func queryFieldUtilEscapeIfNecessary(name string) string {
if stringIsEmpty(name) ||
IndexingFieldNameDocumentID == name ||
IndexingFieldNameReduceKeyHash == name ||
IndexingFieldNameReduceKeyValue == name ||
IndexingFieldsNameSpatialShare == name {
return name
}
escape := false
insideEs... |
package cmd
import (
"fmt"
"runtime"
"github.com/spf13/cobra"
)
func NewVersionCmd(version, commit, date, builtBy string) *cobra.Command {
// versionCmd represents the version command
return &cobra.Command{
Use: "version",
Short: "Prints the version of chekr.",
Run: func(cmd *cobra.Command, args []strin... |
package main
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"io"
"math/rand"
"net"
"os"
"testing"
"time"
"github.com/xindong/frontd/aes256cbc"
)
var (
_echoServerAddr = []byte("127.0.0.1:62863")
_expectAESCiphertext = []byte("U2FsdGVkX19KIJ9OQJKT/yHGMrS+5SsBAAjetomptQ0=")
_secret = []... |
package responses
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func createTestServer(f http.HandlerFunc) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(f))
}
func callTestServer(ts *httptest.Server) (string, int, error) {
res, err := http... |
package main
var x, i = []int{1, 2}, 0
func f() int { i = 1; return 9 }
//func main() {
// x[i] = f()
// println(x[0], x[1])
//}
|
package utils
import (
"io"
"log"
"strings"
)
type loggerWriter struct {
logger *log.Logger
}
func (lw loggerWriter) Write(p []byte) (int, error) {
str := strings.Trim(string(p), "\x00")
l := len(str)
lw.logger.Printf("%s", strings.Trim(string(p), "\x00"))
return l, nil
}
// LogWriter turns a *log.Logger in... |
/*
* @lc app=leetcode.cn id=1352 lang=golang
*
* [1352] 最后 K 个数的乘积
*
* https://leetcode.cn/problems/product-of-the-last-k-numbers/description/
*
* algorithms
* Medium (47.16%)
* Likes: 89
* Dislikes: 0
* Total Accepted: 10.5K
* Total Submissions: 22.3K
* Testcase Example: '["ProductOfNu... |
// Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, ... |
package main
import (
"flag"
"fmt"
"os"
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/pschlump/godebug"
"gitlab.com/pschlump/PureImaginationServer/ReadConfig"
)
type EthAccount struct {
Address string
KeyFile string
KeyFilePasswo... |
package main
import (
pb "hello-grpc/hello"
"log"
"net"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
const (
listen = ":50051"
)
type server struct{}
// Echo implements hello.HelloServiceServer
func (s *server) Echo(ctx context.Context, in *pb.StringMessage) (*pb... |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
package testutils
import (
"encoding/json"
. "github.com/onsi/gomega"
)
func CheckJSONPrettyPrint(a string, b string) {
raw := []byte(b)
var rawI interface{}
json.Unmarshal(raw, &rawI)
jsonBytes, _ := json.MarshalIndent(rawI, "", " ")
expect := string(jsonBytes)
Expect(a).To(Equal(expect))
}
|
import (
"fmt"
"math"
)
func getSum(p, a float64) int {
fmt.Println("Factor", p, "is", a, "times")
dobP := (math.Pow(p, a+1) - 1) / (p - 1)
return int(dobP)
}
func primeSummation(n int) int {
var i, count, sum int = 3, 0, 0
for n%2 == 0 {
n /= 2
count++
}
sum += getSum(float64(2), float64(count))
for n ... |
package number
import "testing"
func TestBitNumberBase(t *testing.T) {
bitNum := NewBitNumber()
bitNum.Mark(1)
bitNum.IsMarked(1)
t.Logf("%v", bitNum)
}
|
// Copyright 2018 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package vm
import (
"bufio"
"bytes"
"context"
"net"
"os"
"strconv"
"strings"
"github.com/golang/protobuf/proto"
"chromiumos/tast/common/testexec"
"chromiumos/tas... |
package cache
import (
"fmt"
"github.com/Skipor/memcached/recycle"
)
type Item struct {
ItemMeta
Data *recycle.Data
}
type ItemMeta struct {
Key string
Flags uint32
Exptime int64
Bytes int
}
func (m ItemMeta) expired(now int64) bool {
return m.Exptime != 0 && m.Exptime < now
}
func (i Item) NewVi... |
package oauth
import (
"errors"
"time"
. "github.com/jsl0820/wechat"
)
const TICKET_URL = "/cgi-bin/ticket/getticket?type=jsapi&access_token={{TOKEN}}"
var ticketInstance = &Ticket{Expires: GetConfig().Expires}
type Ticket struct {
Expires uint
Ticket string
}
//刷新票据
func (ti *Ticket) ticketRefresh() {
url... |
package comparisons
import (
"jean/instructions/base"
"jean/instructions/factory"
"jean/rtda/heap"
"jean/rtda/jvmstack"
)
type IF_ACMPEQ struct {
base.BranchInstruction
}
func (ifAcmp *IF_ACMPEQ) Execute(frame *jvmstack.Frame) {
_ifAcmp(frame, func(r1, r2 *heap.Object) bool {
return r1 == r2
}, ifAcmp.Offse... |
package main
import (
"fmt"
"net"
"strconv"
"strings"
"time"
"github.com/BurntSushi/toml"
log "github.com/Sirupsen/logrus"
)
type PortScannerConfig struct {
Portrange string
Ipaddress string
Protocol string
}
type PortScannerResult struct {
portScannerResult portScannerResultMap
running int
... |
// Copyright 2020 The gVisor 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 agree... |
package modifiers
import (
"path/filepath"
dynatracev1beta1 "github.com/Dynatrace/dynatrace-operator/src/api/v1beta1"
"github.com/Dynatrace/dynatrace-operator/src/controllers/dynakube/activegate/consts"
"github.com/Dynatrace/dynatrace-operator/src/controllers/dynakube/activegate/internal/statefulset/builder"
"gi... |
// Copyright (C) 2017 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 t... |
// Copyright 2016 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, ... |
package core
import (
"github.com/Peakchen/xgameCommon/akLog"
)
/*
by stefan 2572915286@qq.com
Based upon https://github.com/qiao/PathFinding.js
*/
type TGrid struct {
width int
height int
nodes DoubleNode
}
const (
allWalked = bool(false)
)
/**
* The Grid class, which serves as the encapsulation of the ... |
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package taskmanager
import (
"context"
"math/rand"
"time"
"chromiumos/tast/ctxutil"
"chromiumos/tast/errors"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/ch... |
package ymdRedisServer
import "github.com/orestonce/ymd/ymdRedis/ymdRedisProtocol"
func (this *RedisCore) Echo(message string) (reply ymdRedisProtocol.BulkReply, errMsg string) {
reply.Value = []byte(message)
return reply, ``
}
func (this *RedisCore) Ping(message string) (reply ymdRedisProtocol.BulkReply, errMsg s... |
package aws
import (
"encoding/base64"
"errors"
"sync/atomic"
"time"
"github.com/NYTimes/gizmo/pubsub"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s... |
package main
import (
"context"
"github.com/aws/aws-lambda-go/lambda"
"github.com/iarlyy/golang-multicloud-function/function"
)
func HandleRequest(ctx context.Context, msg function.MsgPayload) (function.MsgPayload, error) {
res_msg := msg.Process()
return res_msg, nil
}
func main() {
lambda.Start(HandleReque... |
package fourway
const (
PictureLength = 600.0 // pixels
IntersectionLength = 200.0 // px
) |
package entities
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestCreatesCorrectly(t *testing.T) {
registration := CreateNewRegistration("myevent", "mycallback")
assert.NotZero(t, registration.Id)
assert.NotZero(t, registration.CreationDate)
assert.Equal(t, "myevent", registration.EventName)... |
package fridge
import (
"github.com/shomali11/fridge/item"
"time"
)
const (
// Fresh is when an item has not passed its "Best By" duration
Fresh = "FRESH"
// Cold is when an item has passed its "Best By" duration but not its "Use By" one
Cold = "COLD"
// Expired is when an item has passed its "Use By" durati... |
package model
import (
"time"
"github.com/caos/zitadel/internal/crypto"
"github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/model"
)
type KeyView struct {
ID string
Private bool
Expiry time.Time
Algorithm string
Usage KeyUsage
Key *crypto.CryptoValue
Sequence ... |
package main
import "sort"
//42 接雨水
//1-D的接雨水问题有一种解法是从左右两边的边界往中间不断进行收缩,收缩的过程中,对每个坐标(一维坐标)能接的雨水进行求解
func trap(height []int) int {
left, right := 0, len(height)
lmax, rmax := 0, 0
sum := 0
for left < right {
if height[left] <= height[right] {
if height[left] > lmax {
lmax = height[left]
} else {
s... |
/**
Code for parsing Kustomize YAML and analyzing dependencies.
Adapted from
https://github.com/GoogleContainerTools/skaffold/blob/511c77f1736b657415500eb9b820ae7e4f753347/pkg/skaffold/deploy/kustomize.go
Copyright 2018 The Skaffold Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not ... |
package main
import (
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
)
var (
listenAddr = flag.String("addr", ":8080", "Address to listen on")
cacheMaxAge = flag.Int("max-age", 60, "Seconds to allow caching of resources on the client side")
cert = flag.String("cert", "", "Certificate file for TLS. The conc... |
package util
import (
"math/rand"
"time"
"fmt"
"strconv"
)
func CheckErr(err error) {
if err != nil {
panic(err)
}
}
func GetRandomCode(n int8) string {
randomCode := ""
rand.Seed(int64(time.Now().Nanosecond()))
for i := int8(0); i < n; i ++ {
randomCode +=fmt.Sprintf("%v", rand.Intn(10))
}
return ran... |
package config
import (
stdlog "log"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/aws/aws-sdk-go/service/sqs/sqsiface"
"g... |
package models
import (
"github.com/dgrijalva/jwt-go"
"github.com/jinzhu/gorm"
)
type User struct {
gorm.Model
Name string
Email string `gorm:"type:varchar(100);unique_index"`
Gender string `json:"Gender"`
Password string `json:"Password"`
}
type Token struct {
UserID uint
Name string
Email str... |
package main
import (
"fmt"
"io/ioutil"
"net/http"
// "log"
)
func main() {
resp, _ := http.Get("http://shop.nordstrom.com")
/*resp, err := http.Get("http://shop.nordstrom.com")
if err != nil{
log.Fatal(err)
}*/
page, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
fmt.Println(string(pa... |
package examples
import (
"io/ioutil"
"os"
"path/filepath"
"testing"
kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
"github.com/openshift/origin/pkg/api/latest"
configapi "github.com/openshift/origin/pkg/config/api"
deployapi "github.com/ope... |
package ghcapi
import (
"fmt"
"github.com/go-openapi/runtime/middleware"
"github.com/gobuffalo/validate/v3"
"go.uber.org/zap"
"github.com/gofrs/uuid"
mtoshipmentops "github.com/transcom/mymove/pkg/gen/ghcapi/ghcoperations/mto_shipment"
"github.com/transcom/mymove/pkg/gen/ghcmessages"
"github.com/transcom/my... |
package configfile
import (
"io/ioutil"
"os"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestAttachWatcher(t *testing.T) {
t.Run("AttachWatcher", func(t *testing.T) {
// Mock the log.Fatal function to intercept fatal errors for inspection
var watcherErr error
logFatal = func(v ...interfa... |
// 函数
func protect(g func()){
defer func(){
log.PrintLn("done")
if x:= recover(),x !=nil {
log.Printf("run time panic: %v", x)
}
}{}
log.Println("start")
g()
} |
// Copyright 2019 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package ui
import (
"context"
"time"
"chromiumos/tast/errors"
uiperf "chromiumos/tast/local/bundles/cros/ui/perf"
"chromiumos/tast/local/chrome"
"chromiumos/tast/loca... |
package model
import (
"gorm.io/datatypes"
)
type CDNCluster struct {
Model
Name string `gorm:"column:name;size:256;uniqueIndex;not null" json:"name"`
BIO string `gorm:"column:bio;size:1024" json:"bio"`
Config datatypes.JSONMap `gorm:"column:config;n... |
package controller
import (
"context"
"fmt"
"sort"
"time"
"github.com/mylxsw/adanos-alert/internal/repository"
"github.com/mylxsw/asteria/log"
"github.com/mylxsw/coll"
"github.com/mylxsw/glacier/infra"
"github.com/mylxsw/glacier/web"
"github.com/mylxsw/go-utils/str"
"go.mongodb.org/mongo-driver/bson/primit... |
// Copyright 2013 (c) Freek Kalter. All rights reserved.
// Use of this source code is governed by the "Revised BSD License"
// that can be found in the LICENSE file.
package main
import (
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"regexp"
"s... |
// Copyright 2019 - 2022 The Samply Community
//
// 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 helpers containts helper functions used within project */
package helpers
import (
"errors"
"fmt"
"os"
logic "github.com/xDarkicex/Logic"
)
// vars for use of logic ops
var (
Equal = logic.Eq
And = logic.And
argOne bool
argTwo bool
)
/*
Manual - Accepts two boolean values and
Prints out avalibl... |
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main() {
file, err := os.Open("input")
if err != nil {
return
}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
var txtlines []string
for scanner.Scan() {
txtlines = append(txtlines, scanner.Text())
}
file.Close()
for _,... |
package jit
import "fmt"
// FoldConst returns a new expression where all constant subexpressions have been replaced by numbers.
// E.g.:
// 1+1 -> 2
func FoldConst(e expr) expr {
switch e := e.(type) {
default:
return e
case binexpr:
return foldBinexpr(e)
case callexpr:
return foldCallexpr(e)
}
}
func is... |
package util
import "container/heap"
type Element struct {
Val int
}
type PQ []*Element
func (q *PQ) Len() int {
return len(*q)
}
func (q *PQ) Less(i, j int) bool {
return (*q)[i].Val < (*q)[j].Val
}
func (q *PQ) Swap(i, j int) {
(*q)[i], (*q)[j] = (*q)[j], (*q)[i]
}
func (q *PQ) Push(v interface{}) {
*q = ... |
package backoff
import (
"context"
"math/rand"
"time"
)
// An Option configures a BackOff.
type Option interface {
apply(b Policy) Policy
}
// optionFunc wraps a func so it satisfies the Option interface.
type optionFunc func(Policy) Policy
func (f optionFunc) apply(p Policy) Policy {
return f(p)
}
// statele... |
package operations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
"github.com/go-openapi/swag"
strfmt "... |
package config
import (
"context"
"errors"
"flag"
"fmt"
"github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/mvcc/mvccpb"
"gopkg.in/yaml.v2"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
var (
Conf *conf // 静态配置
DynamicConf *dynamicConf // 动态配置
_path string
_etc... |
package main
import (
"net/http"
"github.com/SuperTikuwa/mission-techdojo/handler"
)
func main() {
http.HandleFunc("/user/create", handler.CreateHandler)
http.HandleFunc("/user/get", handler.GetHandler)
http.HandleFunc("/user/update", handler.UpdateHandler)
http.HandleFunc("/gacha/draw", handler.DrawHandler)
... |
package oneagent_mutation
import (
"strconv"
"github.com/Dynatrace/dynatrace-operator/src/config"
"github.com/Dynatrace/dynatrace-operator/src/kubeobjects"
dtwebhook "github.com/Dynatrace/dynatrace-operator/src/webhook"
corev1 "k8s.io/api/core/v1"
)
func (mutator *OneAgentPodMutator) configureInitContainer(requ... |
package schedule
type Job struct {
//CodeName string `json:"code_name"`
Image string `json:"image"`
Payload string `json:"payload"`
}
type ReqData struct {
Jobs []*Job `json:"jobs"`
}
|
// Copyright 2018 Satoshi Konno. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package transport
import (
"testing"
)
const (
testUnicastTCPSocketPort = 32001
)
func TestUnicastTCPSocketOpenClose(t *testing.T) {
sock := NewUnicastTCPS... |
/**
阶乘
数字最小是从 0 开始的
*/
package main
import "fmt"
func main() {
num := factorial(0)
fmt.Println(num)
}
func factorial(n int) int {
if n == 0 || n == 1 {
return 1
}
return factorial(n-1) * n
}
|
package panic_recover
import "fmt"
func ProductCode(x, y int) {
var z int
func() {
defer func() {
if recover() != nil {
z = 0
}
}()
panic("test panic")
z = x / y
return
}()
fmt.Printf("x/y = %d\n", z)
}
|
package dynamic_programming
import (
"sort"
"testing"
)
//俄罗斯套娃信封问题
//二维数组下的 最长递增子序列
func maxEnvelopes1(envelopes [][]int) int {
if len(envelopes) <= 1 {
return len(envelopes)
}
sort.Slice(envelopes, func(i, j int) bool {
//宽相同 对高进行排序
if envelopes[i][0] == envelopes[j][0] {
return envelopes[i][1] < enve... |
package rating
import (
"math"
"log"
)
// some constants copied from https://github.com/golang/go/blob/master/src/math/bits.go
const (
shift = 64 - 11 - 1
bias = 1023
mask = 0x7FF
)
// Round returns the nearest integer, rounding half away from zero.
// This function is available natively in Go 1.10
//
// Spec... |
package main
import (
"bytes"
)
//49. 字母异位词分组
//给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
//
//示例:
//
//输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
//输出:
//[
//["ate","eat","tea"],
//["nat","tan"],
//["bat"]
//]
//说明:
//
//所有输入均为小写字母。
//不考虑答案输出的顺序。
//思路 字典表统计,给特征码
func groupAnagrams(strs []string) [][]string ... |
// Copyright 2021 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package camera
import (
"context"
"chromiumos/tast/autocaps"
"chromiumos/tast/local/camera/testutil"
"chromiumos/tast/testing"
)
func init() {
testing.AddTest(&testin... |
package log
import (
"testing"
)
func TestLogger(t *testing.T) {
log := New("trace")
// this is a facade to get code coverage up
t.Run("Testing PluggableLogger : should pass", func(t *testing.T) {
log.Info("Test %s ", "log")
log.Warn("Test %s ", "log")
log.Debug("Test %s ", "log")
log.Trace("Test %s ", ... |
/*
Copyright 2021 The Skaffold 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, sof... |
package repo
import (
"github.com/emicklei/go-restful"
)
type RepoResourceOptions struct {
RepoDir string
RepoUrl string
}
//RepoResource ...
type RepoResource struct {
RepoDir string
RepoUrl string
}
//NewRepoResource ...
func NewRepoResource(options *RepoResourceOptions) *RepoResource {
return &RepoResource... |
/*
MIT License
Copyright (c) 2020-2021 Kazuhito Suda
This file is part of NGSI Go
https://github.com/lets-fiware/ngsi-go
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, inc... |
package mongodb
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Repository struct {
collection *mongo.Collection
}
func NewRepository(db *Client, collName string) *Repository {
collection := db.Databa... |
package main
import (
"fmt"
"log"
"net/http"
"os"
"sync"
chatgpt "github.com/golang-infrastructure/go-ChatGPT"
"github.com/line/line-bot-sdk-go/linebot"
)
var mu sync.Mutex
type User struct {
DisplayName string
InHour int
InMin int
OutHour int
OutMin int
}
var bot *linebot.Client
c... |
package wax
import (
"fmt"
"github.com/pgavlin/warp/wasm"
"github.com/pgavlin/warp/wasm/code"
"github.com/willf/bitset"
)
const ValueTypeBool = 1
type Flags int32
const (
FlagsLoadLocal = 1 << iota
FlagsLoadGlobal
FlagsLoadMem
FlagsStoreLocal
FlagsStoreGlobal
FlagsStoreMem
FlagsMayTrap
FlagsPseudo
Fl... |
package tests_test
import (
"sigs.k8s.io/kustomize/k8sdeps/kunstruct"
"sigs.k8s.io/kustomize/k8sdeps/transformer"
"sigs.k8s.io/kustomize/pkg/fs"
"sigs.k8s.io/kustomize/pkg/loader"
"sigs.k8s.io/kustomize/pkg/resmap"
"sigs.k8s.io/kustomize/pkg/resource"
"sigs.k8s.io/kustomize/pkg/target"
"testing"
)
func writeK... |
package code
import (
"github.com/spf13/viper"
"os"
"strings"
)
/*
*@Author Administrator
*@Date 9/4/2021 12:17
*@desc
*/
func RouterFile(SelectTableName string) {
f2 := new(FileNameChange)
model := f2.Case2Camel(SelectTableName)
router := f2.Lcfirst(model)
all := strings.ReplaceAll(routerTemp, "{{model}}", m... |
package ssss
import (
"fmt"
)
import ()
type Result struct {
Code int `json:"code" xml:"code"` //0为成功,其它值为错误码
Message string `json:"message,omitempty" xml:"message,omitempty"`
Info interface{} `json:"info,omitempty" xml:"info,omitempty"` //具体结果数据, 只有当code为0时,才设置此属性值
}
func NewErrorResult(code... |
package service
import (
"fmt"
"github.com/google/uuid"
"io/ioutil"
"net/http"
"os"
"time"
"verification-service/dto"
"verification-service/model"
"verification-service/repository"
)
type VerificationService struct {
VerificationRepository *repository.VerificationRepository
}
func (handler *VerificationSer... |
// 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 constants
// Version number string.
const Version = "0.0.1"
|
package grpcx_test
import (
"context"
"errors"
"fmt"
"net"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/encoding"
"google.golang.org/grpc/test/bufconn"
"github.com/socialpoint-labs/bsk/grpcx"
)
func ExampleDaemon_Run() {
server := exampleServer()
lis := b... |
// Copyright (C) 2017 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 t... |
// Copyright 2019 - 2022 The Samply Community
//
// 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 utils
import (
"fmt"
"testing"
)
func TestDoubleAverage(t *testing.T) {
testDoubleAverage(10, 10000)
type args struct {
count int64
amount int64
}
tests := []struct {
name string
args args
want int64
}{
{
name:"1",
args:args{10, 10000},
want:10000,
},
{
name:"2",
args:ar... |
package viz
import (
"errors"
)
type DB interface {
Init(Config) error
Get(int, int) (string, error)
Lines() (int, error)
Update() error
Watch(chan bool, chan bool) error
}
// init nil DB
var db DB
func InitDB() error {
switch config.DB {
case "csv":
if config.CSV.File == "" {
return errors.New("Field ... |
package rtq
import (
"encoding/json"
"errors"
"fmt"
"time"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func (rt *rtQ) processMessage(msg Message, rawData []byte) error {
start := time.Now()
defer rt.cfg.Pmx.ProcessingTime.Observe(float64(time.Since(start).Seconds()))
// all data is json
payload := make... |
package main
import (
"database/sql"
)
func connect(url string) (*sql.DB, error) {
database, err := sql.Open("postgres", url)
if err != nil {
return database, err
}
return database, nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.