text stringlengths 11 4.05M |
|---|
package RedisPool
import (
"Common/redisz"
"errors"
"fmt"
_ "github.com/garyburd/redigo/redis"
)
var redisPool *redisz.RedisPool
func InitRedis(ip string, runCount int) {
redisPool = redisz.NewRedisPool("common", ip, "", runCount)
}
func RedisDBSize() {
size := redisPool.Dbsize()
fmt.Printf("size is %d \n",... |
package inmobi
import (
"encoding/json"
"errors"
"fmt"
"github.com/econnelly/myrevenue"
"github.com/econnelly/myrevenue/adnetwork"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"time"
)
type ReportRequester struct {
SessionID string `json:"session_id"`
AccountID string `json:"account_id"`
Username string... |
// Copyright 2017 Jeff Foley. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
package handlers
import (
"encoding/json"
"io"
"net"
)
type DataOptsHandler struct {
Enc *json.Encoder
}
func NewDataOptsHandler(w io.Writer) *DataOptsHandler {
r... |
package openid
import (
"fmt"
"net/http"
"github.com/dgrijalva/jwt-go"
)
// SetupErrorCode is the type of error code that can
// be returned by the operations done during middleware setup.
type SetupErrorCode uint32
// Setup error constants.
const (
SetupErrorInvalidIssuer SetupErrorCode = iota // Inv... |
package fitbit
import (
"context"
"fmt"
"net/http"
)
type HeartRateData struct {
ActivitiesHeart []ActivitiesHeart `json:"activities-heart"`
ActivitiesHeartIntraday ActivitiesHeartIntraday `json:"activities-heart-intraday"`
}
type ActivitiesHeart struct {
DateTime string `json:"dateTime"`
Value ... |
package main
import (
"fmt"
// "time"
)
func main() {
ch := make(chan int)
quit := make(chan int)
go read(ch, quit)
go write(ch)
// for i := 0; i < 10; i++ {
// fmt.Println(<-ch, "read")
// }
// time.Sleep(time.Second)
// close(ch)
<-quit
}
func write(b chan int) {
for i := 0; i < 10; i++ {
b <- i
... |
package parcels
// https://habr.com/ru/post/114947/
// transcription https://www.study.ru/article/fonetika-angliyskogo/transkripciya-i-pravila-chteniya
// https://iloveenglish.ru/stories/view/vse-o-transkriptsii-v-anglijskom-yazike
// https://www.translate.ru/Gramm/Rules/
// https://sloovo.com/ru/biblioteka.php?type=o... |
package data
import (
"github.com/pkg/errors"
"upper.io/db.v3/lib/sqlbuilder"
"upper.io/db.v3/postgresql"
)
var DB sqlbuilder.Database
var settings = postgresql.ConnectionURL{
Database: `postgres`,
Host: `db`,
User: `postgres`,
Password: `password`,
}
func SetupDB() error {
var err error
DB, err = ... |
package reminderscheduler
import (
"time"
"github.com/malware-unicorn/managed-bots/gcalbot/gcalbot"
)
func (r *ReminderScheduler) sendReminderLoop(shutdownCh chan struct{}) error {
// sleep until the next minute so that the loop executes at the beginning of each minute
now := time.Now()
nextMinute := time.Date(... |
package main
import (
"fmt"
"sync"
"time"
)
// ScoreUpdate response sent back
type ScoreUpdate struct {
CurrentScore Score `json:"currentScore"`
LastScore LastScore `json:"lastScore"`
}
// Score keep track of the scores
type Score struct {
Blue int `json:"blue"`
Red int `json:"red"`
}
// LastScore ke... |
package database
import (
"FPproject/Backend/log"
"FPproject/Backend/models"
"time"
)
func (d *Database) InsertUH(id string, h models.UserHealth) (string, error) {
res, err := d.db.Exec("INSERT INTO userhealth(id, gender, height, weight, dob, active, target, created, updated) VALUES(?,?,?,?,?,?,?,?,?)",
id, h.G... |
package testdata
import (
"github.com/frk/gosql/internal/testdata/common"
)
type FilterNestedRecords struct {
_ *common.Nested `rel:"test_nested:n"`
common.FilterMaker
}
|
package model
import (
"Blog/util/errmsg"
"errors"
"github.com/jinzhu/gorm"
)
type Post struct {
Category Category `gorm:"foreignKey:Cid" json:"category,omitempty"`
gorm.Model
Title string `gorm:"type:varchar(100);not null" json:"title,omitempty"`
Cid int `json:"cid,omitempty"`
Desc string `gorm:"type:... |
package templatecode
import (
"fmt"
"io/ioutil"
"os"
"regexp"
"strings"
)
const (
index = `{{define "Content"}}<div>久等网络</div>{{end}}`
)
// CreateController 创建文件
// name: 文件名称
// path: 文件所在文件夹路径
func CreateController(project, name, path string, isCreate ...bool) {
create(project, name, path, 1, isCreate...)... |
package config
import (
log "github.com/Sirupsen/logrus"
"github.com/codegangsta/cli"
"github.com/widuu/goini"
"strconv"
)
// 配置项
type Options struct {
Port int
TlsCertFile string
TlsKeyFile string
SidecarCfgFile string
}
// 解析配置文件
func ParseConf(c *cli.Context) (*Options, error) {
options ... |
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"os"
"github.com/ubclaunchpad/inertia/common"
"github.com/ubclaunchpad/inertia/daemon/inertiad/log"
)
// envHandler manages requests to manage environment variables
func envHandler(w http.ResponseWriter, r *http.Request) {
if deployment == nil {
h... |
package main
import (
"bufio"
"fmt"
"os"
"sort"
)
func main() {
var r = bufio.NewReader(os.Stdin)
var n, k int
fmt.Fscan(r, &n, &k)
var x = make([]int, n)
for i := 0; i < n; i++ {
fmt.Fscan(r, &x[i])
}
var solution = Solve(x, k)
fmt.Println(solution)
}
func Solve(x []int, k int) int {
sort.Ints(x)
va... |
// MIT License
//
// Copyright (c) 2016 C.T.Chen
//
// 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, including without limitation the rights
// to use, copy, modify, me... |
package lexec
import (
"io"
"sync"
)
// Stream represents execution output stream.
type Stream string
const (
// Stdout is ID for execution stdout.
Stdout Stream = `stdout`
// Stdout is ID for execution stderr.
Stderr Stream = `stderr`
// Start is ID for execution start.
Launch Stream = `launch`
// Finin... |
package leetcode
import "testing"
func TestIsValid(t *testing.T) {
t.Log(isValid("()"))
t.Log(isValid("()[]{}"))
t.Log(isValid("(]"))
t.Log(isValid("{[]}"))
t.Log(isValid("{["))
t.Log(isValid("]"))
}
|
// Copyright 2020 Clivern. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package storage
import (
"crypto/sha256"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-g... |
// Copyright 2016 The LUCI 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... |
// Copyright 2021 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... |
// 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 app
import (
"context"
"net/http"
"time"
)
type App struct {
httpServer *http.Server
}
func (app *App) Run(port string, handler http.Handler) error {
app.httpServer = &http.Server{
Addr: ":" + port,
Handler: handler,
MaxHeaderBytes: 1 << 20, // 1 Mb
ReadTimeout: 10 * time.Sec... |
package config
import (
"os"
"github.com/spf13/viper"
)
func Init() {
// Google
if os.Getenv("GOOGLE_APPLICATION_CREDENTIALS") == "" {
os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", os.Getenv("STEAM_GOOGLE_APPLICATION_CREDENTIALS"))
}
//
viper.AutomaticEnv()
viper.SetEnvPrefix("STEAM")
// Rabbit
viper.Se... |
package xml
import (
"testing"
)
const fragmentXml = "<root k='v' kk='vv'><child>text</child></root>"
func BenchmarkType(b *testing.B) {
d := desc(0)
for i := 0; i < b.N; i++ {
d.depth()
}
}
|
package ardupilotmega
/*
Generated using mavgen - https://github.com/ArduPilot/pymavlink/
Copyright 2020 queue-b <https://github.com/queue-b>
Permission is hereby granted, free of charge, to any person obtaining a copy
of the generated software (the "Generated Software"), to deal
in the Generated Software without re... |
package sol
func containsDuplicate(nums []int) bool {
meno := make(map[int]bool)
for _, num := range nums {
if _, dup := meno[num]; dup {
return true
}
meno[num] = true
}
return false
}
|
package log
import (
"errors"
"io"
"os"
"testing"
"github.com/stretchr/testify/require"
api "github.com/tkhoa2711/proglog/api/v1"
)
func makeSegment(baseOffset uint64) (s *segment, dir string, err error) {
dir, err = os.MkdirTemp("", "segment-test")
if err != nil {
return nil, "", err
}
c := Config{}
c... |
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(flipCase("Hello World"))
fmt.Println(flipCase("HaHaHa"))
}
func flipCase(s string) string {
var res string;
for i := 0 ; i < len(s) ; i++ {
if strings.ToLower(string(s[i])) == string(s[i]) { //letter is lowercase
res += strings.ToUpper(str... |
package http
import (
"net/http"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/upframe/api"
)
func tokensGet(w http.ResponseWriter, r *http.Request, c *api.Config) (int, interface{}, error) {
password := r.FormValue("password")
if password != api.Password {
return http.StatusUnauthorized, nil, nil
}
... |
package roman_to_integer
import (
"github.com/stretchr/testify/assert"
"testing"
)
func Test_romanToInt(t *testing.T) {
cases := map[string]int{
"III": 3,
"IV": 4,
"IX": 9,
"LVIII": 58,
"MCMXCIV": 1994,
}
for key, value := range cases {
assert.Equal(t, value, romanToInt(key))
}
}
|
package client
import (
"context"
"errors"
"github.com/wish/ctl/pkg/client/filter"
"github.com/wish/ctl/pkg/client/types"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// GetCronJob returns a single cron job
func (c *Client) GetCronJob(contextStr, namespace string, name string, options GetOptions) (*types.Cron... |
package services
import (
"log"
"time"
"github.com/agusbasari29/Skilltest-RSP-Akselerasi-2-Backend-Agus-Basari/entity"
"github.com/agusbasari29/Skilltest-RSP-Akselerasi-2-Backend-Agus-Basari/repository"
"github.com/agusbasari29/Skilltest-RSP-Akselerasi-2-Backend-Agus-Basari/request"
"github.com/mashingan/smappi... |
package config
import (
"io/ioutil"
"gopkg.in/yaml.v3"
)
var configModel *Config
// NewConfig gets the configuration based on the environment passed
func NewConfig(env string) (IConfig, error) {
configFile := "config/tier/" + env + ".yaml"
bytes, err := ioutil.ReadFile(configFile)
if err != nil {
return nil... |
// Copyright (C) 2015 Nicolas Lamirault <nicolas.lamirault@gmail.com>
// 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 ... |
package main
import (
"testing"
)
func Test_findRow(t *testing.T) {
type args struct {
code string
min int
max int
}
tests := []struct {
name string
args args
want int
}{
{"F should return 0 for 0-1", args{"F", 0, 1}, 0},
{"B should return 1 for 0-1", args{"B", 0, 1}, 1},
{"FB should return 1... |
package boshio_test
import (
"net/http"
"net/http/httptest"
"regexp"
"strconv"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"fmt"
"testing"
)
func TestBoshio(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Boshio Suite")
}
var (
boshioServer *server
)
type server struct {
RedirectHandl... |
package main
import (
"fmt"
"html/template"
"math"
"net/http"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
)
func lsmodLineToKernelModule(index int, line string) KernelModule {
spaceRegexp := regexp.MustCompile(`\s+`)
line = spaceRegexp.ReplaceAllString(line, " ")
lineElements := strings.Split(line, " ")
... |
package caching
import "errors"
var (
ErrCacheUnavailable = errors.New("cache unavailable")
)
type Cache interface {
IsOk() bool
Get(key string) (string, error)
Set(key string, value string) error
Del(key string) error
}
|
package service
import (
"demo/grpc_test/proto/helloworld"
"golang.org/x/net/context"
"log"
)
type GreeterServer struct {
}
func (g *GreeterServer) SayHello(ctx context.Context, req *helloworld.HelloRequest) (*helloworld.HelloReply, error) {
log.Println(req)
rp := &helloworld.HelloReply{
Message: "Hello" + r... |
package main
func trap(height []int) int {
n := len(height)
lo, hi := 0, n-1
maxLeft, maxRight := 0, 0
totalAccumulated := 0
for lo < hi {
if height[lo] < height[hi] {
if height[lo] < maxLeft {
totalAccumulated += maxLeft - height[lo]
} else {
maxLeft = height[lo]
}
lo++
} else {
if h... |
package main
import (
"fmt"
"github.com/go-redis/redis"
)
// 声明一个全局的rdb变量
var rdb *redis.Client
// 初始化连接
func initClient() (err error) {
// 传入的是Redis的数据库配置结构体
rdb = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 1, // use default DB
})
_, err = rd... |
package main
import (
"fmt"
"strings"
"github.com/fiorix/wsdl2go/soap"
)
// Namespace was auto-generated from WSDL.
var Namespace = "http://wsiv.ratp.fr"
// NewWsivPortType creates an initializes a WsivPortType.
func NewWsivPortType(cli *soap.Client) WsivPortType {
return &wsivPortType{cli}
}
// WsivPortType w... |
package itemCat
import (
"github.com/tidwall/gjson"
"io/ioutil"
"net/http"
"strconv"
)
// ArtCat functions related to ML's api that get items by categories
type ItemCat struct {
data string
}
// LoadItems load all items of page one
// Returns 1 on fail
func (a *ItemCat) LoadItems(idCat string) int {
resp, err ... |
package port
import (
"context"
"time"
)
// BayarSetoranInport ...
type BayarSetoranInport interface {
Execute(ctx context.Context, req BayarSetoranRequest) (*BayarSetoranResponse, error)
}
// BayarSetoranRequest ...
type BayarSetoranRequest struct {
TagihanID string
TanggalHariIni time.Time `json:"-"`
}
... |
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/alecthomas/kingpin"
)
const defaultCountFile = ".config/ct/count"
var eLog = log.New(os.Stderr, "", 0)
var (
rotate = kingpin.Flag("rotate", "Number of rotation.").Short('r').Int()
countFilePath = kingpin.Flag("file", "File to save nu... |
package cosmos
import "testing"
func TestCosmosCollection(t *testing.T) {
client := getDummyClient()
db := client.Database("dbtest")
coll := db.Collection("colltest")
if coll.client.rType != "colls" {
t.Errorf("%+v", coll.client)
}
if coll.client.rLink != "dbs/dbtest/colls/colltest" {
t.Errorf("%+v", coll.... |
package main
import (
"math/rand"
"net/http"
"os"
"strings"
"time"
"github.com/nektro/mantle/pkg/db"
"github.com/nektro/mantle/pkg/handler"
"github.com/nektro/mantle/pkg/idata"
"github.com/nektro/mantle/pkg/ws"
"github.com/nektro/go-util/util"
etc "github.com/nektro/go.etc"
"github.com/nektro/go.etc/tran... |
package main
import "chapter4/context"
func main() {
context.Initialize()
}
|
package main
import (
"bufio"
"fmt"
"os"
"strings"
"time"
"github.com/araddon/dateparse"
"github.com/bwmarrin/discordgo"
)
// global variables
var tokensFile = "tokens.txt"
var discordToken string
var commandPrefix string
// remindmes = list of structs w/ author, time message will execute (post-converted), r... |
package main
import (
"fmt"
"html/template"
"log"
"net/http"
//"github.com/feng/future/agfun/data"
"github.com/feng/future/agfun/control"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Println("URL**************", r.URL.Path)
})
http.HandleFunc("/index", control.Ag... |
package vsphere
import (
"context"
"fmt"
"strings"
"time"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/vmware/govmomi/vim25/mo"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/wait"
"github.com/openshift/installer/pkg/destroy/providers"
installertypes "gi... |
package util
func DJBHash(str string) int32 {
hash := 5381
for _, c := range str {
hash += (hash << 5) + int(c)
}
return int32(hash & 0x7FFFFFFF)
}
|
/*
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 common
// BotMessage is an exported type that.
type BotMessage struct {
Channel string
User string
Message string
}
// NewMessage creates and returns objects of
// the exported type Message.
func NewMessage(user, channel, message string) *BotMessage {
msg := &BotMessage {
C... |
package watcher
import (
"github.com/pubg/kube-image-deployer/controller"
"github.com/pubg/kube-image-deployer/interfaces"
pkgRuntime "k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"
)
type ApplyStrategicMergePatch = controller.ApplyStrategicMergePatch
func NewW... |
/**
* Author: Tony.Shao(xiocode@gmail.com)
* Date: 13-02-27
* Version: 0.02
*/
package weigo
import (
"encoding/json"
"fmt"
"reflect"
)
func JSONParser(body string, result interface{}) (err error) {
body_bytes := []byte(body)
err = json.Unmarshal(body_bytes, result)
if err != nil {
return
}
return nil
... |
package rkt
type KeyValue struct {
Name string `json:"name"`
Value string `json:"value"`
}
type MountPoint struct {
Name string `json:"name"`
Path string `json:"path"`
}
type Port struct {
Count int `json:"count"`
Name string `json:"name"`
Port int `json:"port"`
Protoco... |
package FizzBuzzHandler
import (
"errors"
"leboncoin/model"
"strconv"
routing "github.com/qiangxue/fasthttp-routing"
)
type FizzBuzzHandler interface {
GetFizzBuzz(request *routing.Context) error
}
type defaultFizzBuzzHandler struct {
defaultLimit int64
}
func New(defaultLimit int64) FizzBuzzHandler {
retur... |
package common
import (
"bytes"
"fmt"
"html/template"
"net/http"
)
func getTemplates(folder string, filenames []string, fm template.FuncMap) (tmpl *template.Template) {
var files []string
for _, file := range filenames {
files = append(files, fmt.Sprintf("templates/%s%s.html", folder, file))
}
if fm != nil ... |
package instance_test
import (
"encoding/json"
"errors"
"os"
"path/filepath"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
boshlog "github.com/cloudfoundry/bosh-agent/logger"
bmdepl "github.com/cloudfoundry/bosh-micro-cli/deployment"
bmrel "github.com/cloudfoundry/bosh-micro-cli/release"
bmstemcell... |
package types
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
sdk "github.com/cosmos/cosmos-sdk/types"
)
func TestTakeFeePoolRewards(t *testing.T) {
// initialize
height := int64(0)
fp := InitialFeePool()
vi1 := NewValidatorDistInfo(valAddr1, height)
vi2 := Ne... |
package main
import (
"sort"
)
type house struct {
id uint64
district string
roomNumber uint64
price int64
distanceFromCenter uint64
}
func commonSortPart (Houses []house, compare func(a,b house)bool) []house{
ready := make([]house, len(Houses))
copy(ready,Houses)
sort.Slice(ready,func(i,j int)bool{
... |
package web
import (
"context"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"testing"
pb "github.com/autograde/aguis/ag"
"github.com/autograde/aguis/ci"
)
func TestParseWithInvalidDir(t *testing.T) {
const dir = "invalid/dir"
_, err := parseAssignments(dir, 0)
if err == nil {
t.Errorf("want no such file o... |
package service
import (
"github.com/social-network/subscan-plugin/example/system/dao"
"github.com/social-network/subscan-plugin/example/system/model"
"github.com/social-network/subscan-plugin/storage"
"github.com/social-network/subscan-plugin/tools"
"github.com/social-network/substrate-api-rpc"
)
type Service s... |
// +build bench
package hw10_program_optimization //nolint:golint,stylecheck
import (
"archive/zip"
"testing"
"time"
"github.com/stretchr/testify/require"
)
const (
mb uint64 = 1 << 20
memoryLimit uint64 = 30 * mb
timeLimit = 300 * time.Millisecond
)
// go test -v -count=1 -timeout=30s -tags bench... |
package practice02
import "fmt"
//值类型 var
//引用类型ref 指针,slice,map,chan
func TestValueAndRefType() {
var a = 100
var b chan int = make(chan int, 1)
fmt.Println("a=", a)
fmt.Println("b=",b)
modify(a)
fmt.Println("a=", a)
modifyPoint(&a)
fmt.Println("a=", a)
}
func modify(a int) {
a = 10
return
}
func mod... |
package app
import (
"fmt"
"time"
"github.com/gin-gonic/gin"
validation "github.com/go-ozzo/ozzo-validation"
"github.com/ikasamt/zapp/zapp"
"github.com/jinzhu/gorm"
)
type Organization struct {
ID int
Name string
CreatedAt time.Time
UpdatedAt time.Time
beforeJSON gin.H
errors error
}
... |
package mysql_test
import (
"mysql"
"os"
"testing"
)
func TestConnection(t *testing.T) {
opt := mysql.NewOption(os.Getenv("mysqlUser"), os.Getenv("mysqlPassword"), os.Getenv("mysqlAddress"), os.Getenv("mysqlDbName"))
var conn mysql.Connection
if err := conn.Connect(opt); err != nil {
t.Fail()
}
// conn.Cl... |
package api
import (
"github.com/itsmeadi/cart/src/entities/models"
"github.com/itsmeadi/cart/src/templatego"
"log"
"net/http"
"strconv"
)
func (api *API) ProductList(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
//r.se
w.Header().Set("Content-Type", "text/html")
categoryIdStr := r.FormValu... |
package service
import (
"context"
"github.com/goscaffold/snowflake"
micro "github.com/micro/go-micro"
"github.com/xormplus/xorm"
"go.uber.org/zap"
"io"
"mix/test/utils/dispatcher"
"mix/test/utils/flags"
)
const (
BundlePath = "cold/btc"
)
func NewContext(ctx context.Context, db *xorm.Session, logger *zap.L... |
package webrpc
import (
"errors"
"log"
"net"
"reflect"
"time"
"github.com/gorilla/websocket"
)
// Common handler errors.
var (
ErrNotInChan = errors.New("not in channel")
)
const (
writeWait = 10 * time.Second
pingTimeout = 60 * time.Second
pingPeriod = 20 * time.Second
sendqLength = 1024
)
// Conn r... |
package covid19
import (
"github.com/go-kit/kit/log"
stdopentracing "github.com/opentracing/opentracing-go"
generalEndpoint "github.com/tech-showcase/covid19-service/endpoint"
"github.com/tech-showcase/covid19-service/middleware"
"github.com/tech-showcase/covid19-service/service"
)
type (
Endpoint struct {
Ge... |
package main
import (
"net/http"
"github.com/jmoiron/sqlx"
)
type DBDriver struct {
Conn *sqlx.DB
}
type API struct {
DB *DBDriver
EmailInfo *SendEmailInfo
}
//user input on login
type UserSignInData struct {
Email string `json:"email"`
Password string `json:"password"`
}
//user input for signup
... |
package main
import (
"admigo/common"
"crypto/tls"
"fmt"
"golang.org/x/crypto/acme/autocert"
"log"
"net/http"
"time"
)
func main() {
if common.Env().Debug {
startDevTLS()
return
}
startTLS()
}
func startDevTLS() {
e := common.Env()
fmt.Printf("[%s] Admigo v%s started at %s:%d\n", "debug",
common.V... |
package main
import "fmt"
func main() {
var arr1 [5]int
//当定义完数组后,其实数组的各个元素都有了默认值(数据类型的默认值int0float0boolfalsestring"")
fmt.Printf("数组的地址%p\n", &arr1)
fmt.Printf("数组第一个元素的地址%p\n", &arr1[0]) //第一个元素的地址等于数组变量arr1的地址
fmt.Printf("数组第二个元素的地址%p\n", &arr1[1]) //第二个元素 = 第一个元素地址+8(1个int占8个字节)
//四种定义数组
var array1 [3]int... |
package Problem0556
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
// tcs is testcase slice
var tcs = []struct {
n int
ans int
}{
{
12443322,
13222344,
},
{
2321,
3122,
},
{
2147483467,
2147483476,
},
{
2147483647,
-1,
},
{
12,
21,
},
{
21,
-1,
},
/... |
package exampleAsATest
import (
"fmt"
"testing"
)
func HelloWorld(name string) string {
return fmt.Sprintf("Hello, %s", name)
}
func ExampleHelloWorld(t *testing.T) {
returnedString := HelloWorld("Quick Quack!")
fmt.Sprintf(returnedString)
// Output: Hello, Quick Quack!
}
|
package otp
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base32"
"fmt"
"hash"
"math"
)
// otpauth://totp/Company:joe_example@gmail.com?secret=[...]&issuer=Company
type HOTP struct {
seed string
window int
counter int
tokenLength int
base32 bool
encoding func() hash.Hash
}
func N... |
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package task
import (
"bytes"
"context"
"github.com/opentracing/opentracing-go"
"github.com/pingcap/errors"
backuppb "github.com/pingcap/kvproto/pkg/brpb"
"github.com/pingcap/log"
"github.com/pingcap/tidb/br/pkg/backup"
"github.com/pingcap/tidb/br/pk... |
package binary_search
func BinarySearch(arr []int, value int) int {
return binarySearch(arr, 0, len(arr), value)
}
func binarySearch(arr []int, l int, r int, value int) int {
if len(arr) <= 0 || l >= r {
return -1
}
for l < r {
mid := l + (r-l)/2
//fmt.Printf("l=[%d], r=[%d], mid=[%d]\n", l, r, mid)
if ar... |
package responses
type Results []Result
type Result map[string]interface{}
|
// +build zalandoValidation
package validators
import (
. "github.com/zalando/chimp/types"
"strings"
)
type ZalandoValidator struct{}
//Validate returns true if the passed interface is valid, false otherwise.
//If the interface cannot be passed, an error is returned.
func (*ZalandoValidator) Validate(input interf... |
package mutual
import (
"fmt"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func Test_resource_occupyAndRelease(t *testing.T) {
// 避免 debugprint 输出
temp := needDebug
needDebug = false
defer func() { needDebug = temp }()
//
ast := assert.New(t)
//
p := 0
ts := timestamp{time: 0, proc... |
package main
import (
"encoding/json"
"fmt"
"math/rand"
"os"
"strings"
"time"
"github.com/erbridge/gotwit"
"github.com/erbridge/gotwit/twitter"
)
type (
corpus struct {
Words []string `json:"words"`
Prefixes map[string][]string `json:"prefixes"`
}
)
func getCorpus() (c corpus, err error)... |
package cmd
import (
"fmt"
"os"
"os/exec"
"github.com/urfave/cli"
)
func EditCmd() cli.Command {
return cli.Command{
Name: "edit",
Aliases: []string{"e"},
Usage: "Edit emoji commit messages",
Action: edit,
}
}
func edit(c *cli.Context) error {
editor := os.Getenv("EDITOR")
if editor == "" {
... |
package repository_test
import (
"errors"
"strings"
"testing"
"github.com/goodplayer/Princess/repository"
"github.com/gofrs/uuid"
)
func TestDb_SaveUser(t *testing.T) {
repository.Init()
db := repository.NewDb(repository.GlobalDb)
uid := uuid.Must(uuid.NewV7())
user := &repository.User{
UserId: uid... |
package multiple
import (
"errors"
"io"
"log"
"strings"
"time"
)
type UserMgr struct {
conns []localConn
// Network string
// Addrs []string
Listens []string
dialTimeout, writeTimeout time.Duration
readTimeout time.Duration
encoder MultipleEncoder
done chan bool
// packet 上层调用sen... |
package config
import (
kingpin "gopkg.in/alecthomas/kingpin.v2"
)
// AddCommandLine setup Graphite specific cli args and flags.
func AddCommandLine(app *kingpin.Application, cfg *Config) {
app.Flag("graphite.default-prefix",
"The prefix to prepend to all metrics exported to Graphite.").
StringVar(&cfg.DefaultP... |
package leetcode
/*X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X. Each digit must be rotated - we cannot choose to leave it alone.
A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 ro... |
/*
Write a method that accepts two integer parameters rows and cols.
The output is a 2d array of numbers displayed in column-major order,
meaning the numbers shown increase sequentially down each column and wrap
to the top of the next column to the right once the bottom of the current column is reached.
Examples
pri... |
package post
import (
"time"
"yj-app/app/yjgframe/db"
)
type Entity struct {
PostId int64 `json:"post_id" xorm:"not null pk autoincr comment('岗位ID') BIGINT(20)"`
PostCode string `json:"post_code" xorm:"not null comment('岗位编码') VARCHAR(64)"`
PostName string `json:"post_name" xorm:"not null comme... |
package env
import (
"log"
"os"
"regexp"
"strconv"
"strings"
"sync"
)
const (
broadcasterHTTPPortEnvName = "BROADCASTER_HTTP_PORT"
broadcasterBufferSizeEnvName = "BROADCASTER_BUFFER_SIZE"
broadcasterHostList = "BROADCASTER_HOST_LIST"
)
var (
httpPort = 7000
bufferSize = 1024
hostList = []s... |
// 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 ... |
//
// This package was written by Paul Schou in Dec 2020
//
// Originally intended to help with linking two apps together and expanded to be a general
// open source software for use to link apps together that usually don't do mTLS (mutual TLS)
//
package main
import (
"crypto/rand"
"crypto/tls"
"crypto/x509"
... |
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"testing"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/cognitoidentityprovider"
"github.com/aws/aws-sdk-go/service/cognitoidentityprovider/cognitoidentityprovideriface"
)
type mockLogout struct {
cognitoident... |
package chainedhashmap
import "fmt"
type node struct {
val interface{}
next *node
}
type linkedlist struct {
len int
next *node
}
type chainedHashMap struct {
cap int
bucket []*linkedlist
}
//Init 初始化链式哈希表
func (h *chainedHashMap) Init(cap int) {
h.cap = cap
if h.cap != 0 {
h.bucket = make([]*linked... |
package auth
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path"
"testing"
"github.com/ubclaunchpad/inertia/common"
"github.com/stretchr/testify/assert"
)
func getTestPermissionsHandler(dir string) (*PermissionsHandler, error) {
err := os.Mkdir(dir, os.ModePerm)
if err != n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.