text stringlengths 11 4.05M |
|---|
// 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... |
package hashtable
import (
"fmt"
"runtime"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestNew(t *testing.T) {
h := New(0)
defer h.Free()
h.Put(1, 1) //1
h.Put(2, 1) //2
h.Put(2, 2)
h.Put(3, 2) //4
h.Put(4, 2) //4
h.Put(5, 2) //8
h.Put(6, 2) //8
h.Put(61, 2) //8
h.Put(62, 2) //8
... |
package wssh
import (
"encoding/json"
"log"
"net"
"time"
"golang.org/x/crypto/ssh"
"golang.org/x/net/websocket"
)
type WebSocketShell struct {
Host string
Port string
Username string
Password string
Key []byte
Client *ssh.Client
Session *ssh.Session
}
// msg flag type.
const (
Terminal... |
package entities
import "github.com/jinzhu/gorm"
// User entity
type User struct {
gorm.Model
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"password"`
Token string `json:"token"`
Projects []Project `json:"projects"`
}
|
package main
import (
"crypto"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"os"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
func saveRSACert(name string, pubkey *rsa.PublicKey) error {
log.Debugf("write certificate %s", name)
f, err := os.Create(name)
if err != nil {
return errors.Wrap(err, ... |
package main
import (
"fmt"
)
func main() {
name:= "Go Programming"
fmt.Println(name)
fmt.Println(len(name))
fmt.Printf("name[0] = %v (type %T)\n",name[0], name[0])
// strings in go are immutable
// name[0] = 33 // cannot assign to name[0]
fmt.Println(name[1:10]) // does not include name[10]
fmt.Println(n... |
package backoff
import (
"context"
"testing"
"github.com/pkg/errors"
"github.com/utilitywarehouse/go-pubsub"
"github.com/utilitywarehouse/go-pubsub/mockqueue"
"github.com/magiconair/properties/assert"
)
func TestBackOff(t *testing.T) {
in := mockqueue.NewMockQueue()
err := in.PutMessage(pubsub.SimpleProduc... |
package main
import (
"io"
"net"
)
func main() {
// '@' indicates the socket held in an abstract namespace
// which doesn't belong to a file in the filesystem
abstractUnixSocket := "@criu.sock"
ln, err := net.Listen("unix", abstractUnixSocket)
if err != nil {
panic(err)
}
defer ln.Close()
for {
conn, ... |
package main
import (
"fmt"
"net/http"
)
func Index(w http.ResponseWriter, q *http.Request) {
fmt.Println(q.Method)
fmt.Println(q.URL)
fmt.Fprintf(w, "OK\n")
}
func main() {
http.HandleFunc("/", Index)
http.HandleFunc("/hello", Index)
s := http.Server{Addr: "127.0.0.1:8080"}
err := s.ListenAndServe()
if e... |
package plik
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/root-gg/plik/server/common"
)
func TestUploadFileTwice(t *testing.T) {
ps, pc := newPlikServerAndClient()
defer shutdown(ps)
err := start... |
/*
* Copyright (c) 2015, Yawning Angel <yawning at torproject dot org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright ... |
package gflag
import (
"bytes"
"errors"
"flag"
"fmt"
"io"
"os"
"reflect"
"strings"
"unsafe"
"github.com/gookit/color"
"github.com/gookit/gcli/v3/helper"
"github.com/gookit/goutil/cflag"
"github.com/gookit/goutil/strutil"
)
// Flags type
type Flags = Parser
// HandleFunc type
type HandleFunc func(p *Par... |
package main
//go:generate sqlboiler psql
import (
"flag"
"fmt"
"log"
"os"
"github.com/javiercbk/jayoak/http"
)
const defaultFilesFolder = "jayoak-files"
const defaultLogFilePath = "jayoak-server.log"
const defaultAddress = "0.0.0.0"
const defaultDBName = "jayoak"
const defaultDBUser = "jayoak"
func main() {
... |
package main
import (
"assignment_2/configs"
"assignment_2/docs"
"assignment_2/routes"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/swaggo/echo-swagger"
"os"
"strconv"
)
func main() {
// App environment start here ...
configs.Env()
appPort := os.Getenv("APP_PORT")
//... |
package main
import (
"bufio"
"fmt"
"os"
"strings"
"golang.org/x/net/html"
)
func main() {
reader := getFileContents()
// doc, err := html.Parse(os.Stdin)
doc, err := html.Parse(reader)
if err != nil {
fmt.Fprintf(os.Stderr, "findlinks1: %v\n", err)
os.Exit(1)
}
visit(doc)
}
func visit(n *html.Node) ... |
// Copyright 2020 Nokia
// Licensed under the BSD 3-Clause License.
// SPDX-License-Identifier: BSD-3-Clause
package sonic
import (
"context"
"fmt"
log "github.com/sirupsen/logrus"
"github.com/srl-labs/containerlab/nodes"
"github.com/srl-labs/containerlab/runtime"
"github.com/srl-labs/containerlab/types"
"git... |
package fitbit
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestHeartRateParamParse(t *testing.T) {
ctx := context.Background()
t.Run("ok cases", func(t *testing.T) {
cases := []struct {
in *HeartRateParam
}{
{in: &HeartRateParam{Date: "2006-01-02", DetailLevel: "1s... |
package server
import (
"fmt"
"net/http"
"time"
"github.com/calvinmclean/automated-garden/garden-app/pkg"
)
// AllPlantsResponse is a simple struct being used to render and return a list of all Plants
type AllPlantsResponse struct {
Plants []*PlantResponse `json:"plants"`
}
// NewAllPlantsResponse will create ... |
package phoenix
import "fmt"
type (
ApiError struct {
Message string `json:"error"`
MessageErr error `json:"error_msg"`
Params map[string]interface{} `json:"params"`
}
SSOError struct {
Error string
ErrorMessage string
}
)
func (e ApiError) Error() string ... |
package ast
import "github.com/fr3fou/monkey/token"
// Boolean is any literal that contains only a bool
// true;
// false;
// let foobar = true;
type Boolean struct {
Token token.Token
Value bool
}
func (b *Boolean) expressionNode() {}
// TokenLiteral returns the boolean token literal
func (b *Boolean) TokenLiter... |
package main
import (
"context"
"os"
"os/signal"
"syscall"
"github.com/jaredallard-home/worker-nodes/registrar/internal/registrard"
"github.com/sirupsen/logrus"
"github.com/tritonmedia/pkg/app"
"github.com/tritonmedia/pkg/service"
"github.com/urfave/cli/v2"
)
func main() {
ctx, cancel := context.WithCancel... |
package thread
import (
"fmt"
"sync"
"time"
)
var value int = 0
type safe struct {
sync.Mutex
val int
}
var svalue *safe = &safe{
val: 0,
}
func RaceCondition() {
go r2()
for i := 0; i < 100; i++ {
value++
time.Sleep(time.Millisecond * 1)
}
time.Sleep(time.Second * 1)
}
func r2() {
for i := 0; i... |
package main
import (
"context"
"fmt"
"log"
"net"
addpb "github.com/golang-grpc-snippet/drill_exercise_1/addition/protobuf"
"google.golang.org/grpc"
)
type server struct{}
func (*server) Add(ctx context.Context, req *addpb.AddRequest) (*addpb.AddResponse, error) {
fmt.Println("Service start..")
first := req... |
package cmd
import (
"fmt"
"github.com/oberd/ecsy/ecs"
"github.com/spf13/cobra"
)
// listServicesCmd represents the listServices command
var listServicesCmd = &cobra.Command{
Use: "list-services",
Short: "list services in a cluster",
Long: `list services in a cluster`,
RunE: func(cmd *cobra.Command, args [... |
package rest
import (
"github.com/m3hm3t/customerapi3/internal/model"
"github.com/m3hm3t/customerapi3/utils"
)
type customerResponse struct {
User struct {
Username string `json:"username"`
Email string `json:"email"`
Token string `json:"token"`
} `json:"customer"`
}
func NewCustomerResponse(u *mo... |
// 47. Bleichenbacher's PKCS 1.5 Padding Oracle (Simple Case)
package main
import (
"bufio"
"crypto/rand"
"errors"
"fmt"
"io"
"math/big"
"os"
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
two = big.NewInt(2)
three = big.NewInt(3)
)
func main() {
priv, err := RSAGenerateKey(3, 256)
if err != nil... |
package main
import (
"flag"
"fmt"
"go-load/cmd/loadstream"
"go-load/cmd/loadwhole"
)
var testFilesFolderPath = flag.String("testfile", "", "path to mock file")
func getApply(count *int) func(a ...interface{}) (n int, err error) {
return func(a ...interface{}) (n int, err error) {
(*count)++
return fmt.Prin... |
package controller
import (
"github.com/go-martini/martini"
"github.com/yosssi/rendergold"
)
func AddRoute(m *martini.ClassicMartini) {
// reads "templates" directory by default
m.Use(rendergold.Renderer())
m.Get("/", top)
}
func top(r rendergold.Render) {
r.HTML(200, "top", nil)
}
|
package main
import "fmt"
/*
获取 map 对应的值
value ,ok = countryMap[key]
根据 ok 的值 来判断 map 中有没有对应的 key
// 如果 key存在会返回 ok = true, 返回对应的值
// 如果key 不存在 ok = false ,返回对应类型的默认值
删除 map 中的元素 delete
delete(map,key) 如果 key 不存在也不会报错,并且 delete 没有任何返回值
清空map 可以重新生成一个 map ,这里go语言 并没有提供一个清空map的方法
*/
func main_01() {
... |
package main
import (
"os"
"github.com/Yangshuting/golang_model/config"
"github.com/Yangshuting/golang_model/mid"
"github.com/Yangshuting/golang_model/model"
"github.com/Yangshuting/golang_model/router"
"github.com/Yangshuting/golang_model/storage"
"github.com/labstack/echo"
"github.com/labstack/echo/middlewa... |
//Package helm implements a wrapper over a native Helm client.
//The wrapper exposes a simple installation API and the configuration.
//
//The code in the package uses the user-provided function for logging.
package helm
import (
"context"
"fmt"
"strings"
"time"
"github.com/kyma-incubator/hydroform/parallel-inst... |
/*
Ruby has a strange operator, .., called flip-flop (not to be confused with the range operator, which looks the same). Used in a loop, flip-flop takes two conditions as operands and will return false until the first operand is truthy, then return true until the second operand is truthy, whereupon it returns true one... |
package chapter4
import (
"fmt"
"os"
"time"
)
func init() {
fmt.Println("=== Go Routine ===")
cars := fillCars()
go showCars(cars, "first goroutine")
go showCars(cars, "second goroutine")
go showCars(cars, "third goroutine")
go func(msg string) {
fmt.Println(msg)
}("going")
time.Sleep(2 * time.Second)... |
package compute
import "fmt"
// IsOperationCancelledError determines if an error is an OperationCancelledError.
func IsOperationCancelledError(err error) bool {
_, isOperationCancelledError := err.(*OperationCancelledError)
return isOperationCancelledError
}
// OperationCancelledError is the error returned when a... |
package abstract_factory
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestGetFactory(t *testing.T) {
factory := GetFactory(TENSOR_FLOW)
_, ok := factory.(*tensorFlowFactory)
assert.True(t, ok)
factory = GetFactory(SPARK_ML)
_, ok = factory.(*sparkMLFactory)
assert.True(t, ok)
}
func TestCr... |
package mem
import (
"github.com/lab5e/lmqtt/pkg/packets"
"github.com/lab5e/lmqtt/pkg/persistence/unack"
)
var _ unack.Store = (*Store)(nil)
// Store is the memory store implementation for the unack store
type Store struct {
clientID string
unackpublish map[packets.PacketID]struct{}
}
// Options is the opti... |
package main
import (
"context"
"fmt"
"io"
"log"
"math"
"net"
"github.com/wexel-nath/grpc-go-course/calculator/pb"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type server struct {}
func (*server) Sum(ctx context.Context, req *pb.SumRequest) (*pb.SumResponse, e... |
package main
import (
"base/glog"
"math"
"myserver/consts"
)
func main() {
aTmp, bTmp := getMinAndSecByLoop(179)
glog.Error("minute = ", aTmp)
glog.Error("second = ", bTmp)
}
func getMinAndSecByLoop(loop uint32) (uint32, uint32) {
leftTime := consts.OneGameTime - loop
glog.Error("leftTime = ", leftTime)
aTm... |
package repository
import "github.com/raphael-trzpit/sandgo/model"
// Role is a repository
type Role interface {
Find(map[string]string) (model.Role, error)
FindAll(map[string]string) ([]model.Role, error)
}
|
package dockerfile
import (
"bytes"
"github.com/mitchellh/packer/builder/docker"
)
// Driver is the interface that has to be implemented to communicate with
// Docker. The Driver interface also allows the steps to be tested since
// a mock driver can be shimmed in.
type Driver interface {
docker.Driver
// B... |
package models
// TranslationWord struct with the translation object
type TranslationWord struct {
EnglishWord string `json:"english-word,omitempty"`
GopherWord string `json:"gopher-word,omitempty"`
}
// ListTranslationWords contains a list of translations
type ListTranslationWords struct {
TranslationWords []Tran... |
package p2
import (
"../p1"
"bytes"
"encoding/hex"
"encoding/json"
"fmt"
"golang.org/x/crypto/sha3"
"strings"
"time"
)
type Block struct {
Header Header
Value p1.MerklePatriciaTrie
Transactions p1.MerklePatriciaTrie
}
// Structure used inside the Block structure
type Header struct {
Height ... |
package dbrepository
import (
"database/sql"
"errors"
"fmt"
"os"
"path/filepath"
"testing"
)
// initdb initalize db for test environment
func initdb() {
dir, _ := os.Getwd()
databasepath := filepath.Join(dir, "tasks.db")
InitDatabase(databasepath)
}
// TestInitDatabase testcase for initalize database functi... |
// 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... |
package main
import "fmt"
func main() {
var x int = 10
var y int = 15
var sum int = x + y
fmt.Println("La somma è ", sum)
}
|
package service
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestHello_Greet(t *testing.T) {
tests := []struct {
name string
req string
}{
{"simple", "simple"},
{"UTF", "मिलन"},
{"special char", `%&# /\`},
{"empty", ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testi... |
package domain
type fakePlayerId string
func NewFakePlayerId(value string) PlayerId {
return fakePlayerId(value)
}
func (i fakePlayerId) String() string {
return string(i)
}
|
package shared
import (
"bytes"
"encoding/json"
"github.com/spf13/cobra"
"io"
"os"
"text/template"
)
func WithConfig(cmd *cobra.Command, opt *ExtraArgs) MessagePrinter {
return &printMessage{cmd: cmd, opt: opt}
}
type MessagePrinter interface {
Info(templateText string, args map[string]interface{})
Debug(te... |
package envoy
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"io/ioutil"
"net/http"
net_url "net/url"
"strings"
"github.com/pkg/errors"
"github.com/sethvargo/go-retry"
kuma_dp "github.com/kumahq/kuma/pkg/config/app/kuma-dp"
"github.com/kumahq/kuma/pkg/core"
kuma_version "github.c... |
package models
import (
"errors"
"github.com/satori/go.uuid"
"time"
)
type Creator struct {
ID uint `gorm:"primary_key" json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DiscordID string `json:"discord_id" gorm:"unique_index:idx_creator_discord_id_guild_i... |
package security
import (
"fmt"
"html/template"
"net/http"
"net/url"
"sort"
)
func AccountsPage(t *template.Template, am AccessManager) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
session, err := LookupSession(r, am)
if err != nil {
ShowError(w, r,... |
package catalog
import (
"context"
"fmt"
"github.com/operator-framework/operator-lifecycle-manager/pkg/controller/install"
errorwrap "github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
apiequality "k8s.io/apimachinery/pkg/api/equality"
apierrors "k8s.io/apimachinery/pkg/api/errors"... |
package helper
import "github.com/gin-gonic/gin"
type Route struct {
Method string
Path string
Handler []gin.HandlerFunc
}
type Handler interface {
Route() []Route
}
|
// ˅
package main
import (
"math/rand"
)
// ˄
// When winning a game, show the same hand at the next time.
type StrategyA struct {
// ˅
// ˄
won bool
preHand *Hand
// ˅
// ˄
}
func NewStrategyA(randomSeed int64) *StrategyA {
// ˅
rand.Seed(randomSeed)
strategyA := &StrategyA{}
strategyA.won = false... |
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(getNandResult(3, []int{1, 2}, [][]int{
{1, 2, 3},
{0, 0, 3},
{1, 2, 2},
}))
fmt.Println(getNandResult(4, []int{4, 6, 4, 7, 10, 9, 11}, [][]int{
{1, 5, 7},
{1, 7, 14},
{0, 6, 7},
{1, 6, 5},
}))
}
func getNandResult(k int, arr []int, ... |
// +build debug
package main
import (
"fmt"
"os"
"github.com/blevesearch/bleve/index/store"
"github.com/blevesearch/bleve/index/store/metrics"
)
func printOtherHeader(s store.KVStore) {
storeMetrics, ok := s.(*metrics.Store)
if ok && storeMetrics != nil {
fmt.Printf(",")
storeMetrics.WriteCSVHeader(os.Std... |
package concurrency
import (
"fmt"
)
func channel() {
ch := make(chan int)
go func() {
for i := 0; i != 10; i++ {
ch <- i
}
close(ch)
}()
for i := range ch {
fmt.Println(i)
}
}
func selectExample() {
c0 := chanInt(3)
c1 := chanInt(3)
ok0, ok1 := true, true
for ok0 || ok1 {
var x, y int
selec... |
package ksqlparser
import (
"sort"
"strings"
)
type graphitem struct {
name string
stmt Stmt
depends map[string]graphitem
dependants map[string]graphitem
}
type dependencyGraph []graphitem
func (a dependencyGraph) Len() int { return len(a) }
func (a dependencyGraph) Less(i, j int) boo... |
package database_Celica
import (
"Celica/checkError_Celica"
)
func (this *CelicaSql) RecordInsert(newInsert *RecordOpe) int {
if this == nil || this.db == nil {
return 1
}
if newInsert.tableName == "" || newInsert.keyName == "" {
return 2
}
commad := "insert into " + newInsert.tableName + "(" + newInsert.k... |
package types
import (
"memoapp/model"
"net/url"
)
type (
Parameters url.Values
// Results メモリスト
Memos []*model.Memo
Contents interface{}
Results []interface{}
)
|
package config
import "github.com/spf13/viper"
func ReadConfig(filename string) (*viper.Viper,error){
config := viper.New()
config.SetConfigType("json")
config.AddConfigPath("./conf")
config.SetConfigName(filename)
err := config.ReadInConfig()
return config,err
} |
package event
import (
"net/http"
ihttp "github.com/serverless/event-gateway/internal/http"
)
// HTTPRequestData is a event schema used for sending events to HTTP subscriptions.
type HTTPRequestData struct {
Headers map[string]string `json:"headers"`
Query map[string][]string `json:"query"`
Body interfac... |
package main
import (
"crypto/sha256"
"flag"
"fmt"
"github.com/astaxie/beego"
"github.com/devplayg/golibs/secureconfig"
"github.com/devplayg/ipas-mcs/controllers"
_ "github.com/devplayg/ipas-mcs/routers"
"os"
"path/filepath"
"strings"
)
var (
flags *flag.FlagSet
)
func main() {
// 옵션
flags = flag.NewFl... |
package registry
import (
"context"
"fmt"
"io"
"google.golang.org/grpc"
registryapi "github.com/operator-framework/operator-registry/pkg/api"
"github.com/operator-framework/operator-registry/pkg/client"
opregistry "github.com/operator-framework/operator-registry/pkg/registry"
)
// ChannelEntryStream interfac... |
package retoil
import (
"github.com/reiver/go-toil"
)
type internalRetoil struct {
toiler toil.Toiler
strategizer Strategizer
}
// New returns an initialized retoiler (which is also a toil.Toiler),
// based on the toiler and strategizer passed as parameters.
func New(toiler toil.Toiler, strategizer Strate... |
package ui
import "fmt"
func (c *CalculatorForm) init() {
c.InputSpinBox1.ConnectValueChanged(func(value int) { c.OutputWidget.SetText(fmt.Sprint(value + c.InputSpinBox2.Value())) })
c.InputSpinBox2.ConnectValueChanged(func(value int) { c.OutputWidget.SetText(fmt.Sprint(value + c.InputSpinBox1.Value())) })
}... |
package main
import (
"bufio"
"crypto/sha256"
"encoding/json"
"flag"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/sergi/go-diff/diffmatchpatch"
)
var (
oldExecutable = flag.String("old_executable",
"",
"Path to the old RobustI... |
package core
import (
"er"
"fwb"
"hlf"
"sgs"
"strconv"
)
var _debugGlobalApp *fwAppImp
//FwAppBuildFunc hook up with the SGS server
func FwAppBuildFunc() sgs.App {
return &fwAppImp{}
}
var _execMap = map[int]func(*fwAppImp, sgs.Command) *er.Err{
sgs.CMD_TICK: onTick,
sgs.CMD_APP_RUN: forwar... |
package proxy
import (
"io"
"log"
"net"
"net/http"
"github.com/st3v/uaa-proxy/util"
)
func Websocket(target string, fallback http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !util.IsWebsocketRequest(r) {
fallback.ServeHTTP(w, r)
return
}
d, err... |
package blc
type Transaction struct{
TxHash []byte
} |
package api
import (
"database/sql"
"fmt"
"net/http"
"strconv"
"github.com/DemoHn/obsidian-panel/app/account"
"github.com/DemoHn/obsidian-panel/app/proc"
procClient "github.com/DemoHn/obsidian-panel/app/proc/client"
"github.com/labstack/echo"
)
// CtrlInstRsp -
type CtrlInstRsp struct {
Op string `j... |
// +build windows
// Copyright 2016 The go-daylight Authors
// This file is part of the go-daylight library.
//
// The go-daylight library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either versi... |
package bob // package name must match the package name in bob_test.go
import "strings"
const testVersion = 2 // same as targetTestVersion
const (
QUESTION = "Sure."
YELL = "Whoa, chill out!"
NOWORD = "Fine. Be that way!"
ELSE = "Whatever."
)
func Hey(input string) string {
trim := strings.TrimSpace(... |
package sdl
/**
* \brief The structure that defines a point
*
* \sa SDL_EnclosePoints
* \sa SDL_PointInRect
*/
type SDL_Point struct {
X int32
Y int32
}
/**
* \brief A rectangle, with the origin at the upper left.
*
* \sa SDL_RectEmpty
* \sa SDL_RectEquals
* \sa SDL_HasIntersection
* \sa SDL_Int... |
package main
import (
"bufio"
"chat/sandbox/terminal"
"context"
"encoding/json"
"fmt"
"os"
"os/user"
"strings"
"time"
"github.com/gomodule/redigo/redis"
)
const healthCheckPeriod = time.Minute
var pool = NewRedisPool(":6379", healthCheckPeriod)
type Message struct {
User string `json:"user"`
Body strin... |
package main
import (
"flag"
"fmt"
"math/big"
"runtime"
"strconv"
)
var n = 0
var silent = false
var (
tmp1 = big.NewInt(0)
tmp2 = big.NewInt(0)
tmp3 = big.NewInt(0)
y2 = big.NewInt(0)
bigk = big.NewInt(0)
numer = big.NewInt(1)
accum = big.NewInt(0)
denom = big.NewInt(1)
ten = big.NewInt(10)
)... |
package main
import (
"fmt"
"io"
"io/ioutil"
"regexp"
"strings"
)
type versionInfo struct {
Wanted string
Latest string
}
type logOutput struct {
Updates map[string]versionInfo
LockStatements map[string]string
}
func extractUpdates(data string) map[string]versionInfo {
var result = make(map[string]... |
package main
import (
"github.com/go-redis/redis"
"net/http"
"fmt"
)
func main() {
client := redis.NewClient(&redis.Options{
Addr: "redis:6379",
Password: "", // no password set
DB: 0, // use default DB
})
http.HandleFunc("/set", func(w http.ResponseWriter, r *http.Request) {
err := client.S... |
package golog
import (
"fmt"
"log"
"os"
"path/filepath"
"time"
"github.com/bingoohuang/golog/pkg/logfmt"
"github.com/bingoohuang/golog/pkg/str"
"github.com/bingoohuang/golog/pkg/spec"
"github.com/sirupsen/logrus"
)
// SetupLog setup the logrus logger with specific configuration like guava CacheBuilderSpe... |
package gate
import (
"fmt"
"net/http"
"testing"
)
func TestHttpGate(t *testing.T) {
sigChan := make(chan string, 1)
go func() {
c := &Config{
Port:10000,
WriteWait:20,
PongWait:60,
PingPeriod:54,
MaxMessageSize:512,
MessageBufferSize:256,
}
gate := NewGate(c)
gate.UseHttp()
gate.Reg... |
package solutions
/*
* @lc app=leetcode id=198 lang=golang
*
* [198] House Robber
*/
/*
Your runtime beats 100 % of golang submissions
Your memory usage beats 100 % of golang submissions (1.9 MB)
*/
// @lc code=start
func rob(nums []int) int {
if len(nums) == 1 {
return nums[0]
}
last := nums[0]
curr := nu... |
package main
// GetSchemas GetSchemas
func GetSchemas() []string {
return []string{
`CREATE TABLE IF NOT EXISTS User (
ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password TEXT NOT NULL
);`,
`CREATE TABLE IF NOT EXISTS 'Group' (
ID INTEGER NOT NULL PRIMARY KEY AUTOI... |
/*
* Copyright 2018 The openwallet Authors
* This file is part of the openwallet library.
*
* The openwallet library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License... |
package trappingrainwater
import (
"golang/helper"
"testing"
)
func Test(t *testing.T) {
input := []int{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}
helper.AssertInt(trap(input), 6, t)
}
|
package poloniex
import (
"fmt"
)
func (c *ConfigPoloniex) GetBalance() {
bl, err := c.Poloniex.Balances()
if err != nil {
fmt.Println(err)
return
}
for _, v := range bl {
if v.BTCValue != 0 {
c.BalanceInValues.BTCValues = c.BalanceInValues.BTCValues + v.BTCValue
}
//fmt.Println(k,v)
}
c.Balance =... |
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
var createCmd = &cobra.Command{
Use: "create",
Short: "Create various resources: consortium, membership, environment, node",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("create command")
},
}
func newCreateCmd() *cobra.Command {
... |
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"thorium-go/requests"
"github.com/go-martini/martini"
)
func main() {
log.Print("running a fake bolt server")
var game_id int
var service_port int
var listen_port int
var map_name string
var game_mode string
flag.IntVar(&ga... |
package pixeldrain
import (
"encoding/json"
"errors"
"main/utils"
)
const (
referer = "https://pixeldrain.com/"
uploadUrl = referer + "api/file"
)
func upload(path string, size, byteLimit int64, headers map[string]string) (string, error) {
respBody, err := utils.MultipartUpload(uploadUrl, path,... |
package oidc
import (
"context"
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"errors"
"fmt"
"sort"
"strings"
"github.com/golang-jwt/jwt/v5"
fjwt "github.com/ory/fosite/token/jwt"
"github.com/ory/x/errorsx"
"gopkg.in/square/go-jose.v2"
"github.com/authelia/authelia/v4/internal/configuration/schema"
)
// NewKeyM... |
package server
import (
"context"
rs "roman/proto/roman"
)
type GrpcServer struct {
repository *Repository
}
func (gs *GrpcServer) ProcessAnalysis(ctx context.Context, token *rs.TokenAnalysis) (*rs.Response, error) {
var response *rs.Response
response = gs.repository.ProcessAnalysis(token)
return response, nil... |
package utils
import (
"github.com/jinzhu/gorm"
"master/define"
"master/utils/mylog"
_ "github.com/go-sql-driver/mysql"
)
type DbMgr struct {
Db *gorm.DB
//GameDb *gorm.DB
}
var mDbIns *DbMgr = nil
func GetDbMgr()*DbMgr{
if mDbIns ==nil{
mDbIns = &DbMgr{}
}
return mDbIns
}
func (this *DbMgr)InitDB(sour... |
package router
import (
"github.com/gin-gonic/gin"
"im/db"
"im/dto"
"im/helper"
"im/model"
"im/util"
"log"
)
func login(ctx *gin.Context) {
var login dto.LoginDto
err := ctx.ShouldBindJSON(&login)
if err != nil {
helper.Err(ctx, 4000, "username password参数不正确")
return
}
var user model.ChatUser
first :... |
package valid
import (
"regexp"
"testing"
)
func TestValid(t *testing.T) {
for _, v := range []struct {
validate func(string) bool
value string
exp bool
}{
{IsNumber, "123", true},
{IsNumber, "-123", true},
{IsNumber, "123.456", true},
{IsNumber, "123abc", false},
{IsHexString, "123abc", t... |
package cache
import (
"testing"
)
func TestMemoryCache(t *testing.T) {
c, err := NewCache("memorycache", `{"interval":30,"cap":1024}`)
if err != nil {
println("create cache error")
}
c.Put("yjx", "nihao", 20)
c.Put("yjx2", "nihao2", 20)
//yjx := c.Get("yjx")
println(" get yjx = ", c.Get("yjx").(string))
p... |
package test
import (
"context"
"log"
"github.com/go-redis/redis/v8"
)
var Redis *redis.Client
func init() {
host := "127.0.0.1:6379"
pass := "123456a"
//db := 8 // adminapi-8
//db := 9 // merchantapi-9
db := 10 // payapi-10
// redis连接
redisObj := redis.NewClient(&redis.Options{
Addr: host,
Passw... |
package user
import (
"camp/lib"
"camp/week2/api"
"camp/week2/service"
"encoding/json"
"github.com/globalsign/mgo/bson"
"github.com/simplejia/clog/api"
"net/http"
)
type ListOneReq struct {
Id bson.ObjectId `json:"uid"`
}
func (l *ListOneReq) Regular() (ok bool) {
if l == nil || l.Id.String() == "" {
re... |
/*
Copyright 2011 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 to in writing, software
di... |
package leetcode
func removeDuplicates(nums []int) int {
if len(nums) <= 1 {
return len(nums)
}
last := nums[0]
j := len(nums)
for i := 1; i < j; {
if last == nums[i] {
nums = append(nums[0:i], nums[i+1:j]...)
j--
} else {
last = nums[i]
i++
}
}
return len(nums)
}
|
package day8
import (
"strconv"
"strings"
"github.com/littleajax/adventofcode/helpers"
)
func ProcessInputs() (instructions []instruction) {
inputs := helpers.FetchInputs("./inputs/day8.txt")
for _, line := range inputs {
split := strings.Split(line, " ")
value, err := strconv.Atoi(split[1])
if err != ni... |
package pathfileops
import "testing"
func TestDirMgr_DeleteSubDirectoryTreeFiles_01(t *testing.T) {
testDir := "../dirmgrtests/DeleteSubDirectoryTreeFiles_01"
sourceDir1 := "../logTest"
testDMgr, err := DirMgr{}.New(testDir)
if err != nil {
t.Errorf("Test Setup Error returned by DirMgr{}.New(testDir... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.