text stringlengths 11 4.05M |
|---|
package main
import (
"flag"
"fmt"
"google.golang.org/grpc"
"log"
"net"
//"net/http"
_ "net/http/pprof"
"os"
"rloop/Go-Ground-Station/datastore"
"rloop/Go-Ground-Station/gsgrpc"
"rloop/Go-Ground-Station/gstypes"
"rloop/Go-Ground-Station/helpers"
"rloop/Go-Ground-Station/logging"
"rloop/Go-Ground-Station/... |
package confluent
import (
"log"
"strings"
"github.com/confluentinc/confluent-kafka-go/kafka"
"github.com/google/uuid"
"github.com/pedromss/kafli/concurrent"
c "github.com/pedromss/kafli/config"
"github.com/pedromss/kafli/contracts"
"github.com/pedromss/kafli/model"
)
type ConfluentConsumer struct {
c ... |
package dictionary
// import (
// "github.com/Evedel/fortify/src/say"
// )
func ruleCommentAll(ttail []Token) (resCode int, stopInd int, resNode TokenNode, errmsg string) {
resCode = Ok
indexInternal := 1
strval := ""
errmsg = ""
resNode = TokenNodeCommentAll()
for indexInternal < len(ttail) {
if ttail[ind... |
package main
import (
"fmt"
"io"
"os"
"strconv"
"strings"
)
type Logger interface {
Log(args ...interface{})
Logf(format string, args ...interface{})
}
func main() {
if err := Solution(os.Stdin, os.Stdout, nil); err != nil {
panic(err)
}
}
func Solution(r io.Reader, w io.Writer, logger Logger) error {
v... |
/*****************************************************************
* Copyright©,2020-2022, email: 279197148@qq.com
* Version: 1.0.0
* @Author: yangtxiang
* @Date: 2020-08-07 15:30
* Description:
*****************************************************************/
package pdl
import (
"encoding/json"
"github.com/apach... |
/*
* Package targets
* Target NES
*
* Part of XPMC.
* Contains data/functions specific to the NES output target
*
* /Mic, 20142015
*/
package targets
import (
"os"
"time"
"../specs"
"../utils"
"../timing"
)
func (t *TargetNES) Init() {
t.Target.Init()
ut... |
package workcloud
import (
"regexp"
)
const (
tokenRegrexp = "<meta content=\"(.+?)\" name=\"csrf-token\" />"
titleRegexp = "<title>(.+?)</title>"
)
// get csrf token.
func getToken(doc string) string {
tokenRegexp := regexp.MustCompile(tokenRegrexp)
return tokenRegexp.FindStringSubmatch(doc)[1]
}
// isLogin ... |
package distutil
import (
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"time"
)
// DefaultFileInclPattern is a sensible default set of "static" files.
// This might be updated from time to time to include new types of assets used on the web.
// Extensions which are used for server executables, server configuration ... |
package acoustid
// AcoustIDLookupResp is the type used to parse a successfull AcoustID JSON response
type AcoustIDLookupResp struct {
Status string `json:"status"`
Results []ACLookupResult `json:"results"`
}
// ACLookupResult is a fingerprint match. It contaons one or more recordings that
// include the... |
package blockexplorer
import (
"strings"
"github.com/bkrem/blockchain.info-api-v1-client-go/api"
"github.com/bkrem/blockchain.info-api-v1-client-go/util"
)
type blockExplorerOpts struct {
api.Opts
Limit int `url:"limit,omitempty"`
Active string `url:"active,omitempty"`
Offset int `url:"offset,omitempty... |
package main
// func TestdeviceUpdate(t *testing.T) {
// }
|
package library
import (
"fmt"
"reflect"
)
type Student struct {
Name string
Age int
Class int
}
func (s *Student) GetPropertyInfo() {
// reflect berisi objek Struct s
var reflectValue = reflect.ValueOf(s)
// pengecekan variable reflectValue pointer atau bukan,
// jika iya, cari objek reflect aslinya ... |
package sgs
import (
"encoding/json"
"er"
"hlf"
"strconv"
"time"
)
//Session session interface for users
type Session interface {
CmdChan() chan Command
ForwardToClient(cid int, command Command) *er.Err
GetLogger() hlf.Logger
GetClientName(cid int) string
}
type session struct {
id int
cch chan Command
... |
package models
import (
"encoding/json"
"strings"
"time"
)
// YyyyMmDdDashed is the special date type to parse YYYY-MM-DD format.
type YyyyMmDdDashed time.Time
func (y *YyyyMmDdDashed) UnmarshalJSON(bytes []byte) error {
cleanString := strings.Trim(string(bytes), `"`)
parsedTime, err := time.Parse("2006-01-02",... |
package types
const (
RPCTypeEthereum = uint8(iota)
RPCTypeFilecoin
RPCTypeSolana
)
|
package auth
import (
"crypto/rsa"
"io/ioutil"
"log"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
)
var (
verifyKey *rsa.PublicKey
signKey *rsa.PrivateKey
)
//JSON : 受け取るJSON
type JSON struct {
ID string `json:"id" binding:"required"`
}
// LoginHandler : JWTの発行
func LoginHandler(c... |
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
type data struct {
Endpoint string `json:'endpoint'`
Quotes []map[string]interface{} `json:'quotes'`
Requested_time string `json:'requested_time'`
Timestamp int32 ... |
package models
type Error struct {
Message string `json:"message,omitempty"`
Value string `json:"value,omitempty"`
}
|
package execute
import (
"TskSch/logger"
"TskSch/resultDB"
"bytes"
"fmt"
"gopkg.in/mgo.v2"
"os"
"os/exec"
"strings"
"sync"
"time"
)
type res struct{
Value bool
Name string
}
type taskInfo struct {
taskId map[string]res
mutex *sync.Mutex
}
var Info = func() *taskInfo{
return &taskInfo{taskId : make(map... |
package inmemory
import (
"github.com/Tanibox/tania-core/src/assets/storage"
"github.com/Tanibox/tania-core/src/growth/query"
"github.com/gofrs/uuid"
)
type FarmReadQueryInMemory struct {
Storage *storage.FarmReadStorage
}
func NewFarmReadQueryInMemory(s *storage.FarmReadStorage) query.FarmReadQuery {
return Fa... |
package migemo
import (
"bufio"
"io"
"sort"
"strings"
"unicode/utf16"
)
// CompactDictionaryU8 は、読み毎に複数の単語を格納した辞書
type CompactDictionaryU8 struct {
keyTrie *LoudsTrieU8
valueTrie *LoudsTrieU8
mappingBitVector *BitVector
mapping []uint32
// hasMappingBitList は、あるノードがマッピングを持つかを格納する
h... |
package router
import (
"cherry/weather"
"github.com/gin-gonic/gin"
"strings"
)
var (
ginEgine *gin.Engine
)
func init() {
ginEgine = gin.Default()
ginEgine.LoadHTMLGlob("static/html/*")
ginEgine.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
ginEgine.GET("/index", fu... |
// Copyright 2020 orivil.com. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found at https://mit-license.org.
package modes
type Platform struct {
ID int
Title string
} |
package instructions
import (
"github.com/zxh0/jvm.go/jvmgo/jvm/rtda"
rtc "github.com/zxh0/jvm.go/jvmgo/jvm/rtda/class"
)
// Create new object
type new_ struct {
Index16Instruction
class *rtc.Class
}
func (self *new_) Execute(frame *rtda.Frame) {
if self.class == nil {
cp := frame.ConstantPool()
kClass := c... |
/*
* Copyright 2018, CS Systemes d'Information, http://www.c-s.fr
*
* 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 requir... |
package google
import (
"regexp"
"strings"
"sync"
"time"
"github.com/hashicorp/go-retryablehttp"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"unicode"
"gitgud.io/softashell/comfy-translator/config"
"gitgud.io/softashell/comfy-translator/translator"
)
const (
userAgent = "Mozilla/5.0 (Win... |
/*
Copyright 2020 Humio https://humio.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 by applicable law or agreed to in writing, ... |
package router
import (
"encoding/json"
"gopkg.in/macaron.v1"
"gopkg.in/mgo.v2/bson"
"tech/model"
"tech/modules/middleware"
"tech/modules/page"
"fmt"
)
func Home(ctx *macaron.Context) {
var serieses []model.Series
_ = page.Page(ctx, model.SERIES, &bson.M{}, &serieses)
str, _ := json.Marshal(serieses)
ctx.D... |
package daomodel
// GuestBook ..
type GuestBook struct {
ID string
Timestamp int64
Comment string
}
|
package main
import (
"fmt"
)
func main() {
x := 0
for {
if x > 10 {
break
}
fmt.Println(x)
x++
}
}
|
/*
* @lc app=leetcode.cn id=1128 lang=golang
*
* [1128] 等价多米诺骨牌对的数量
*/
package main
// @lc code=start
func numEquivDominoPairs(dominoes [][]int) int {
counter := make([]int, 100)
count := 0
for i := 0; i < len(dominoes); i++ {
val := 0
if dominoes[i][0] > dominoes[i][1] {
val = dominoes[i][0]*10 + domino... |
package service
import (
"context"
"sync"
"github.com/golang/protobuf/proto"
cp "github.com/halivor/common/golang/packet"
ce "github.com/halivor/common/golang/util/errno"
)
type Method func(context.Context, *cp.Request) (*cp.Response, error)
type Service interface {
SetUp(name string, m Method)
Call(name str... |
package testdata
import "errors"
// World says hello world!
func World() (string, error) {
return "hello", errors.New("world")
}
|
package arangodb
import (
"encoding/json"
"github.com/apex/log"
"fmt"
"github.com/thedanielforum/arangodb/errc"
)
func (c *Connection) Create(col string, doc interface{}) (*Document, error) {
responseDoc := &Document{}
// Check if we need to create a new collection
if c.config.AutoCreateColOnInsert {
c.cach... |
package work
type Tasks struct {
Page float64 `json:"page"`
PageSize float64 `json:"pageSize"`
Tasks []struct {
Cancellable bool `json:"cancellable"`
CancellationRequested bool `json:"cancellationRequested"`
Cancelled bool `json:"cancelled"`
Completed ... |
package api
import (
"github.com/gorilla/sessions"
"github.com/MoptopX/dp-throwfiles/datastore"
)
type API struct {
database datastore.Datastore
sessions sessions.Store
}
// New instantiates a new API object
func New(db datastore.Datastore, secret string) *API {
return &API{
database: db,
se... |
package fusebill
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
"strconv"
"sync"
"time"
)
type Invoice struct {
OutstandingBalance float64 `json:"outstandingBalance"`
}
type WriteOff struct {
InvoiceId int `json:"invoiceId"`
Amount flo... |
func subsets(nums []int) [][]int {
res:=make([][]int,1)
for i:=0;i<len(nums);i++{
s:=len(res)
for j:=0;j<s;j++{
tmp:=make([]int,len(res[j]))
copy(tmp,res[j])
res = append(res,tmp)
res[len(res)-1] = append(res[len(res)-1],nums[i])
}
}
... |
package dbBeans
import (
"strings"
"github.com/kinwyb/go/db"
)
//CREATE TABLE `receipt` (
// `id` bigint(16) unsigned NOT NULL AUTO_INCREMENT COMMENT '单据号',
// `money` decimal(20,3) NOT NULL COMMENT '交易金额',
// `bank_id` int(10) unsigned NOT NULL COMMENT '银行ID',
// `description` text NOT NULL COMMENT '备注',
// ... |
// Copyright 2016 Dave Shanley <dave@quobix.com>
// Use of this source code is governed by a The MIT License
// license that can be found in the LICENSE file.
// service package handles all web service calls and provides a simple RESTful API for the bundled UI.
package service
import (
"os"
"net/http"
"lo... |
package server
// Server 注册服务
type Server struct{}
|
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int, 3)
ch <- 2
ch <- 2
ch <- 2
close(ch) // close when using simple function
sum(ch) // if this is made a go routine no error
time.Sleep(time.Millisecond * 100)
}
func sum(ch chan int) {
for v := range ch {
fmt.Println("Value: ", v,... |
// Copyright © 2021 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 main
import (
"context"
"log"
"os"
"strconv"
"testing"
"time"
"github.com/circonus-labs/gosnowth"
"github.com/circonus-labs/gosnowth/fb/noit"
flatbuffers "github.com/google/flatbuffers/go"
"github.com/google/uuid"
"github.com/openhistogram/circonusllhist"
)
// ExampleSubmitText demonstrates how to... |
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/pablosilvab/cafe-backend-golang/api"
"github.com/pablosilvab/cafe-backend-golang/api/products"
)
var data api.Configuration
func init() {
data = api.LoadConfig()
}
func home(w http.ResponseWriter, r *http.Request) {
fmt.Fprin... |
package auth
import (
"errors"
"net/http"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/Zenika/marcel/config"
)
var (
key = []byte("ThisIsTheSecret")
)
func getVerifiedClaims(tokenString string, sampleClaims jwt.Claims) (jwt.Claims, error) {
token, err := jwt.ParseWithClaims(
tokenString,
sampleC... |
package lastpass
import (
"fmt"
"github.com/scnewma/pwaudit/pkg/pw"
)
// CSVLoader loads passwords from an exported LastPass CSV file.
type CSVLoader struct {
scanner *CSVScanner
passwords chan pw.Password
err error
}
// NewCSVLoader returns a CSVLoader bootstrapped
// with the provided CSVScanner
func ... |
package main
import "net/http"
func main() {
http.HandleFunc("/", sayHello)
http.ListenAndServe(":4400", nil)
}
func sayHello(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello!"))
}
|
package edf
import (
"errors"
"fmt"
"strconv"
"strings"
)
/******************
* EDF PROPERTIES *
******************/
// GetDuration gets the duration of the file in seconds
func (edf Edf) GetDuration() int {
v, oops := strconv.Atoi(strings.TrimSpace(edf.Header["duration"]))
if oops != nil {
panic(oops)
}
... |
package main
import "fmt"
func mFunc() {
a := 66666
fmt.Println("a=", a)
}
//有参无返回值函数的定义,普通参数列表
//定义函数时,在函数名后面定义的参数叫形参
//参数传递,只能由实参传递给形参,不能反过来, 单向传递
func test(a int) {
fmt.Println("a=", a)
}
func test1(a int, b int) {
fmt.Printf("a =%d, b = %d \n", a, b)
}
//不定参数类型
func test2(args ...int) {
fmt.Println("打印参... |
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"fmt"
)
type RequestBody struct {
id int
group int
contents int
}
func main(c web.C, w http.ResponseWriter, r *http.Request) {
body, _ := ioutil.ReadAll(r.Body)
var posted RequestBody
json.Unmarshal(body, &posted)
... |
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"time"
)
const (
awsTimeFormat = "2006-01-02T15:04:05Z"
)
type metadataHandler struct {
http.Handler
credentials *VaultCredentials
}
func NewMetadataHandler(vc *VaultCredentials) http.Handler {
h := &metadataHandler{credentials: vc}
router := ht... |
package main
import "fmt"
type Monster struct {
Name string
Age int
}
//重写toString()
func (m *Monster) String() string {
return fmt.Sprintf("{Name=%v,Age=%v}", m.Name, m.Age)
}
type E struct {
Monster
int //匿名字段
num int
}
func main() {
var e E
e.Monster.Name = "tom"
//此写法 等价于 e.Monster.Age
e.Age = 18
/... |
package fakes
import (
"fmt"
bosherr "github.com/cloudfoundry/bosh-agent/errors"
bmstemcell "github.com/cloudfoundry/bosh-micro-cli/stemcell"
bmtestutils "github.com/cloudfoundry/bosh-micro-cli/testutils"
)
type SaveInput struct {
StemcellManifest bmstemcell.Manifest
CID bmstemcell.CID
}
type Sa... |
package main
import "fmt"
func main() {
var (
l int
s string
tc = NewTC()
)
fmt.Scan(&l)
fmt.Scan(&s)
for i := 0; i < l; i++ {
tc.Add(s[i])
}
fmt.Println(tc.Longest())
}
type TC struct {
letters map[byte]int
pairs map[string]int
}
func NewTC() *TC {
return &TC{
letters: make(map[byte]int),... |
package waktu
// StartOfDay ex: 1993-09-10 00:00:00 +0700 GMT+7.
func (t Time) StartOfDay() Time {
return t.ResetTimeLocal()
}
// StartOfWeek ex: 1993-09-05 00:00:00 +0700 GMT+7.
func (t Time) StartOfWeek(startWeek ...Weekday) Time {
weekday := int(t.Weekday())
if len(startWeek) > 0 {
weekday -= int(startWeek[0]... |
package main
/*
1.Go语言内置测试功能, 提供了必要的测试工具
2.go test工具用来运行测试
3.测试源文件总是以_test.go结尾
4.表组测试是利用一个测试函数测试多组值的好办法
5.包中的示例代码, 既能用于测试, 也能用于文档
6.基准测试提供了探查代码性能的机制
*/
|
package generate
import (
"testing"
"github.com/stretchr/testify/require"
)
func testRandomString(t *testing.T) {
string1 := RandomString(8)
string2 := RandomString(8)
string3 := RandomString(8)
require.NotEqual(t, string1, string2)
require.NotEqual(t, string3, string1)
require.NotEqual(t, string3, string2)... |
package main
import (
"context"
"strings"
"testing"
"github.com/ozbe/wom"
"github.com/ozbe/wom/testutil"
)
func TestApp(t *testing.T) {
input := wom.Input{
Context: context.Background(),
}
cfg := config{
getPod: func(_ context.Context, name string) string {
return strings.Repeat(name, 2)
},
}
app... |
package github
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/brigadecore/brigade/v2/apiserver/internal/api"
"github.com/brigadecore/brigade/v2/apiserver/internal/meta"
"github.com/google/go-github/v33/github"
"github.com/pkg/errors"
"golang.org/x/oauth2"
)... |
package install
import (
"encoding/json"
"github.com/allentom/youcomic-api/config"
"github.com/allentom/youcomic-api/log"
"github.com/allentom/youcomic-api/utils"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"io/ioutil"
"os"
)
var LogField = log.Logger.WithField("scope", "install")
var PreinstallC... |
// Copyright The OpenTelemetry 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 ag... |
package data
import (
"context"
"encoding/csv"
"os"
"time"
log "github.com/sirupsen/logrus"
"github.com/rodrigo-brito/ninjabot/pkg/exchange"
"github.com/xhit/go-str2duration/v2"
)
const batchSize = 500
type Downloader struct {
exchange exchange.Exchange
}
func NewDownloader(exchange exchange.Exchange) Dow... |
package slack
import (
"io"
"log"
"net/http"
"testing"
)
const (
validSigningSecret = "e6b19c573432dcc6b075501d51b51bb8"
invalidSigningSecret = "e6b19c573432dcc6b075501d51b51boo"
validBody = `{"token":"aF5ynEYQH0dFN9imlgcADxDB","team_id":"XXXXXXXXX","api_app_id":"YYYYYYYYY","event":{"type":"app_me... |
package donothing
import (
"bytes"
"testing"
"text/template"
"github.com/stretchr/testify/assert"
)
// TemplateInputs should render correctly with various inputs.
//
// Output from TemplateInputs should never end with a newline. Spacing between sections will be
// handled by the template that calls it.
func Test... |
package problem0069
import "testing"
import "math"
func TestSqrtx(t *testing.T) {
for i := 0; i < 1000; i++ {
t.Log(mySqrt(i) == int(math.Sqrt(float64(i))))
}
}
func TestNewtonSqrtx(t *testing.T) {
for i := 0; i < 1000; i++ {
t.Log(newtonSqrt(i) == int(math.Sqrt(float64(i))))
}
}
|
package main
import (
"io/ioutil"
"os"
"github.com/hilarryxu/golua/binchunk"
)
func main() {
if len(os.Args) > 1 {
data, err := ioutil.ReadFile(os.Args[1])
if err != nil {
panic(err)
}
binchunk.Undump(data)
}
}
|
package main
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path"
"sort"
"strconv"
"strings"
)
type Response struct {
Status string `json:"status"`
Message string `json:"message"`
Capabilities map[string]interface{} `json:"capabilities"`
}
func (r *Response) prin... |
/*
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 writing, softw... |
// 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 in writing... |
package suites
import (
"testing"
"github.com/stretchr/testify/suite"
)
type PostgresSuite struct {
*RodSuite
}
func NewPostgresSuite() *PostgresSuite {
return &PostgresSuite{
RodSuite: NewRodSuite(postgresSuiteName),
}
}
func (s *PostgresSuite) Test1FAScenario() {
suite.Run(s.T(), New1FAScenario())
}
fun... |
package main
import (
"errors"
"fmt"
"hash/crc32"
"log"
"sort"
"sync"
"sync/atomic"
)
const (
InReadSet = 1 + iota
InWriteSet
InIndex
Deleted
NotInRWSet
NotExist
)
type Record struct {
key string
last *Version
mu sync.Mutex
}
type Version struct {
key string
value string
wTs uint64
... |
package evaluator
import (
"regexp"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/pomerium/pomerium/config"
)
// These certificates can be regenerated by running:
//
// go run ./gen-test-certs.go
//
// (Copy and paste the output here.)
const (
testCA = `
----... |
package main
import (
"encoding/csv"
"encoding/json"
"os"
"github.com/nirav-chavda/practice/exercises/TwitterApp/twitter"
)
const (
keyFile string = "keys.json"
tweetID string = "1362379742410731520"
userFile string = "users.csv"
)
func main() {
key, secret, err := getKeys(keyFile)
if err != nil {
pani... |
package btf
import (
"fmt"
"testing"
qt "github.com/frankban/quicktest"
)
func TestPostorderTraversal(t *testing.T) {
ptr := newCyclicalType(2).(*Pointer)
cst := ptr.Target.(*Const)
str := cst.Type.(*Struct)
t.Logf("%3v", ptr)
pending := []Type{str, cst, ptr}
iter := postorderTraversal(ptr, nil)
for iter.... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//765. Couples Holding Hands
//N couples sit in 2N seats arranged in a row and want to hold hands. We want to know the minimum number of swaps so that ... |
package main
// TODO: Improve efficiency of route
import (
"fmt"
"math"
"strconv"
"strings"
)
func getDistance(a []int, b []int) int {
deltaX := int(math.Abs(float64(a[0]) - float64(b[0])))
deltaY := int(math.Abs(float64(a[1]) - float64(b[1])))
return deltaX + deltaY
}
func getClosest(pos []int, board [][]str... |
package controllers
import (
"encoding/binary"
"errors"
"log"
"net"
"services"
"models"
"fmt"
"crypto/x509"
"strconv"
"bytes"
)
func handleTCPMessage(messageChannel services.TCPMessageChannel, myPeer *services.Peer) {
messageType := binary.BigEndian.Uint16(messageChannel.Message[2:4])
log.Println("Messag... |
package guest
import (
"context"
"fmt"
"reflect"
"testing"
"github.com/angryronald/guestlist/config"
constant "github.com/angryronald/guestlist/internal/guest"
"github.com/angryronald/guestlist/internal/guest/infrastructure/repository"
"github.com/angryronald/guestlist/internal/guest/infrastructure/repository... |
// Copyright © 2017 NAME HERE <EMAIL ADDRESS>
//
// 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 login
import (
"context"
"errors"
"tpay_backend/adminapi/internal/common"
"tpay_backend/adminapi/internal/svc"
"tpay_backend/adminapi/internal/types"
"tpay_backend/model"
"tpay_backend/utils"
"github.com/tal-tech/go-zero/core/logx"
)
type LoginLogic struct {
logx.Logger
ctx context.Context
svcC... |
package guest
import (
"context"
"github.com/angryronald/guestlist/internal/guest"
"github.com/google/uuid"
)
func (s *Service) DeleteGuest(ctx context.Context, guestID uuid.UUID) error {
guestRepo, err := s.repository.FindByID(ctx, guestID)
if err != nil {
return nil
}
if guestRepo == nil {
return guest... |
package config
import (
"crypto/tls"
"log"
"net"
"net/url"
"os"
"github.com/globalsign/mgo"
)
var mongodbSession *mgo.Session
var (
dbPrefix = "{{.DatabaseNamePrefix}}"
)
// DBSession returns the current db session.
func DBSession() *mgo.Session {
if mongodbSession != nil {
return mongodbSession
}
uri ... |
package httphandler
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"strings"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/geekakili/portside/driver"
"github.com/geekakili/portside/models"
repository "github.com/geekakili/portside/repository/image"
"gith... |
package main
import (
"fmt"
"github.com/go-redis/redis/v8"
"log"
"net/http"
"os"
)
func main() {
rdb := redis.NewClient(&redis.Options{
Addr: os.Getenv("REDIS_HOST") + ":" + os.Getenv("REDIS_PORT"),
})
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
visitors, err := rdb.Incr(r.Context... |
package common
import (
"testing"
)
type Profile struct {
Name string
Age int
}
func TestGetBytes(t *testing.T) {
// --- encode ---
profile := &Profile{
Name: "Roman",
Age: 30,
}
bts, err := GetBytes(profile)
if err != nil {
t.Fatal("encode error:",err.Error())
return
}
// --- decode ---
var dec... |
package cm
import (
"encoding/json"
"fmt"
"github.com/shawn-tranter/go-basics/app"
"github.com/shawn-tranter/go-basics/api"
"github.com/shawn-tranter/go-basics/bld"
"log"
)
type ConfigManagementRecord struct {
Application *app.ApplicationRecord `json:"application"`
API *api.APIRecord `json:"api"`
... |
// Copyright 2020-2021 Buf Technologies, 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... |
package osutil
import (
"os"
"github.com/mattn/go-isatty"
)
// IsInteractive tests whether Stdin and Stdout are interactive.
func IsInteractive() bool {
return isatty.IsTerminal(os.Stdin.Fd()) && isatty.IsTerminal(os.Stdout.Fd())
}
|
package fundsquarenet
import (
"strings"
"testing"
"github.com/mmbros/quote/internal/quotegetter/scrapers"
"github.com/mmbros/quote/internal/quotegetter/scrapers/testingscraper"
)
func getTestScraper() scrapers.Scraper {
return &scraper{"fundsquarenet", nil}
}
func TestSource(t *testing.T) {
const name = "dum... |
package issummary
type Config struct {
Port int
Token string
GitServiceBaseURL string
GitServiceType string
Organizations []string
SPLabelPrefix string
ClassLabelPrefix string
TargetLabelPrefixes []string
}
|
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/rs/cors"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
var db *gorm.DB
var err error
type Logindetails struct {
Name string
Email string `gorm:"primary_key"`
Pass string
Roll string
// No_of_t... |
package cmd
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"os/user"
"path/filepath"
"sort"
"strings"
"time"
"github.com/BurntSushi/toml"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/go-connections/tlsconfig"
"github.... |
package main
import "github.com/davecgh/go-spew/spew"
// 538. 把二叉搜索树转换为累加树
// 给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。
// https://leetcode-cn.com/problems/convert-bst-to-greater-tree/
func main() {
r := &TreeNode{
Val: 1,
Right: &TreeNode{
Val: 2,
Left: &TreeNode{... |
package env
import (
"os"
)
type Config struct {
Vars []string
}
func WithVars(vars ...string) *Config {
return &Config{Vars: vars}
}
type Env map[string]string
var env Env
func New(c *Config) Env {
if env == nil {
env = make(Env, len(c.Vars))
env.fill(c.Vars)
}
return env
}
func (e Env) fill(keys []st... |
package presenter_test
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/Khigashiguchi/khigashiguchi.com/api/interfaces/presenter"
"github.com/google/go-cmp/cmp"
)
type testResponse struct {
Field1 string `json:"field1"`
Field2 int `json:"field2"`
}
func TestRespondJson(t *testing... |
package c49_cbc_mac_forgery
import (
"bytes"
"crypto/rand"
"github.com/vodafon/cryptopals/set2/c10_implement_cbc_mode"
)
type CBCMAC struct {
key []byte
blockSize int
randIV bool
iv []byte
}
func NewCBCMAC(key []byte) CBCMAC {
bs := 16
if len(key) != bs {
panic("Invalid key size")
}
ret... |
package configuration
import (
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509"
"fmt"
"net/mail"
"net/url"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/go-crypt/crypt/algorithm/plaintext"
"github.com/mitchellh/mapstructure"
"github.com/authelia/authelia/v4/internal/configuration/schema"
"github.... |
package main
import (
"fmt"
"math"
"os"
"time"
"unicode"
"github.com/faiface/beep"
"github.com/faiface/beep/effects"
"github.com/faiface/beep/mp3"
"github.com/faiface/beep/speaker"
"github.com/gdamore/tcell"
)
func multiplyChannels(left, right float64, s beep.Streamer) beep.Streamer {
return beep.Streamer... |
// Copyright 2020 Torben Schinke
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.