text stringlengths 11 4.05M |
|---|
package main
import "fmt"
func main() {
field := generateEmptyField(1001)
field = fillField(field)
fmt.Printf("Sum of diagonal: %d\n", diagonalSum(field))
}
func generateEmptyField(size int) [][]int {
field := make([][]int, size)
for i := 0; i < size; i++ {
field[i] = make([]int, size)
}
return field
}
f... |
package models
import (
"github.com/s-matyukevich/centurylink_sdk/base"
)
type LinkModel interface {
GetConnection() base.Connection
SetConnection(base.Connection)
GetLinks() []Link
}
|
/*
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 controllers
import (
"github.com/gin-gonic/gin"
"github.com/hunterhug/fafacms/core/flog"
"github.com/hunterhug/fafacms/core/model"
"github.com/hunterhug/parrot/util"
)
type LoginRequest struct {
UserName string `json:"user_name"`
PassWd string `json:"pass_wd"`
Remember bool `json:"remember"`
}
fun... |
// 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 utils
import (
"errors"
"github.com/nfnt/resize"
"golang.org/x/image/bmp"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io"
"os"
)
func GenSmallImage(src, dst string) error {
fIn, _ := os.Open(src)
defer fIn.Close()
fOut, _ := os.Create(dst)
defer fOut.Close()
if err := scale(fIn, fOut, 0, 0, ... |
package main
import (
"fmt"
"log"
"time"
"os"
"strconv"
"runtime"
"runtime/debug"
"io/ioutil"
"github.com/syndtr/goleveldb/leveldb"
)
//f
func main() {
fmt.Println("testing LSM(leveldb) PerfInsert...")
b, err := ioutil.ReadFile(os.Args[1])
if err != nil {
fmt.Println("error occured"... |
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
"runtime"
"runtime/pprof"
"github.com/golang/protobuf/proto"
event_go_proto "github.com/tensorflow/tensorflow/tensorflow/go/core/util/event_go_proto"
tbio "github.com/wchargin/tensorboard-data-server/io"
)
var cpuprofile = flag.String("cpuprofile", "", ... |
package webapi
import (
"context"
"errors"
"net"
"net/http"
"sync"
"time"
"github.com/iotaledger/hive.go/daemon"
"github.com/iotaledger/hive.go/logger"
"github.com/iotaledger/hive.go/node"
"github.com/iotaledger/wasp/packages/parameters"
"github.com/iotaledger/wasp/packages/util/auth"
"github.com/iotaledg... |
package pie
import (
"context"
"os"
"testing"
"time"
testify_stats "github.com/elliotchance/testify-stats"
"github.com/elliotchance/testify-stats/assert"
)
func TestMain(m *testing.M) {
os.Exit(testify_stats.Run(m))
}
func assertImmutableStrings(t *testing.T, ss *Strings) func() {
before := (*ss).JSONString... |
package models
import (
"encoding/json"
"fmt"
g "github.com/vseledkin/gortex"
"github.com/vseledkin/gortex/assembler"
"log"
"math"
"os"
)
type PyramidClassifier struct {
Height int // defines the input capacity of the model
Levels []*g.Matrix
Biases []*g.Matrix
EmbeddingSize int
H... |
package main
import (
"fmt"
"io"
"log"
"net"
)
func HandleConn(conn net.Conn) {
fmt.Println("on cline connection!")
conn.Write([]byte("fuck you!!!\n"))
conn.Write([]byte("is very good!\n"))
buf := make([]byte, 1024)
for {
n, err := conn.Read(buf)
if err == io.EOF {
conn.Close()
}
fmt.Print(string... |
package main
import (
"fmt"
"net/http"
"regexp"
"strings"
"github.com/gin-gonic/gin"
strip "github.com/grokify/html-strip-tags-go"
)
/*
Tasks
1. create/update name info
2. fetch info for a given name
3. delete all name info
4. /annotate endpoint
*/
/*
separating url into a struct
to use it for data bin... |
package app
import (
"github.com/patrickmn/go-cache"
"github.com/ubinte/goutils/strutils"
)
type application struct {
Static []string
channels *cache.Cache
}
func (self *application) AddChannelKey(key, name string) {
self.channels.Add(key, name, cache.DefaultExpiration)
}
func (self *application) AddChannel(... |
package main
import (
"bufio"
"crypto/sha256"
"fmt"
"github.com/fatih/color"
"github.com/go-yaml/yaml"
"os"
"path/filepath"
"strconv"
"strings"
)
const banner = `
.---------------------------------------------------.
| Made With Love By github.com/AlmightyFloppyFish |
'-------------------------------------... |
package models
import (
"errors"
"sync"
"time"
)
type User struct {
mu sync.Mutex
UserID int
PersonalInfo Person
Capital float32
}
func (u *User) GetCapital() float32 {
var transaction Transactions
transaction.TID = time.Now() //Hashear
transaction.UserID = u.UserID
transaction.Amount... |
package api
import (
"encoding/json"
"net/http"
"strconv"
"time"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
// Router defines all functionality for our api service router
type Router interface {
HandleEndpoint(pattern string, endpoint Endpoint) *mux.Route
ListenAndServe(port string) error
}
//... |
package main
import (
"fmt"
"github.com/gorilla/websocket"
"net/http"
)
func echo(writer http.ResponseWriter, request *http.Request) {
//升级websocket
conn,err :=(&websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}).Upgrade(writer,request,nil)
if err!=nil{
fmt.Println(err.Er... |
package main
import (
"os"
"sort"
"strconv"
"time"
"github.com/apex/log"
apexcli "github.com/apex/log/handlers/cli"
"github.com/urfave/cli"
"github.com/davidsbond/mona/internal/cmd"
)
var (
version string
compiled string
compileTime int64
)
func init() {
compileTime, _ = strconv.ParseInt(compile... |
/* parser.go
* author: roshan maskey <roshanmaskey@gmail.com>
*
* Entrypoint to parse all audit files
*/
package audit
import (
"fmt"
"strings"
"nighthawk/audit/audittype"
"nighthawk/audit/parser"
nhlog "nighthawk/log"
nhs "nighthawk/nhstruct"
)
func ParseAuditFile(caseinfo nhs.CaseInformation, auditinfo n... |
// Copyright 2023 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
package cloudflare
import (
"context"
"fmt"
"net/http"
)
type RevokeAccessUserTokensParams struct {
Email string `json:"email"`
}
// RevokeAccessUserTokens revokes any outstanding tokens issued for a specific user
// Access User.
func (api *API) RevokeAccessUserTokens(ctx context.Context, rc *ResourceContainer, ... |
package model
import (
"server-monitor-admin/model/base"
)
type SysUser struct {
base.BaseModel
Email string `json:"email"`
UserName string `json:"userName"`
Avatar string `json:"avatar"`
NickName string `json:"nickName"`
Password string `json:"password"`
Mobile string `json:"mobile"`
Gender int ... |
package main
import (
n "github.com/dearcj/golangproj/msutil"
pb "github.com/dearcj/golangproj/network"
"github.com/gofrs/uuid"
"reflect"
"time"
)
type ConnectionData struct {
*pb.ConnectionData
}
func (c ConnectionData) Insert(s *n.XServerDataMsg) {
s.WriteToMsg().ConData = c.ConnectionData
}
func ParamsSiz... |
package atomix
import (
"sync/atomic"
)
// Error is an atomic wrapper around error.
type Error struct {
atomicType
value atomic.Value
}
var _ error = &Error{}
// NewError creates an Error.
// Cannot store nil after first non-nil store.
func NewError(err error) *Error {
e := &Error{}
e.Store(err)
return e
}
f... |
package main
import (
"fmt"
"regexp"
"strconv"
)
var input string = "input.txt"
var regx1 = regexp.MustCompile(`^(.+) bag.? contain (.+)$`)
var regx2 = regexp.MustCompile(`^.+contain (.+)$`)
var regx3 = regexp.MustCompile(`^ *(\d+) (.+) bag.*$`)
var regx4 = regexp.MustCompile(`no other bags$`)
type bag struct {
... |
// Copyright 2018 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... |
package turn_off_lights
import (
elevio "../elev_driver"
"../network_module/drivers/bcast"
)
// Turns off light in the other elevators workspace.
var turnOffId int
var lastMessageId int
type LightOff struct {
Floor int
MessageId int
}
var turnOffLightTX = make(chan LightOff)
var turnOffLightRX = make(chan... |
package fileIO
import (
"encoding/json"
"fmt"
"log"
"os"
"github.com/rDybing/SignFindBackEnd/types"
)
var ipFile = "./credentials/privateIP.json"
var credFile = "./credentials/pgCred.json"
var wordsDir = "./media/lists/"
var symbolsDir = "./media/symbols/"
var fullchain = "/etc/letsencrypt/live/a... |
package etcd
import (
"context"
"encoding/json"
"errors"
clientv3 "go.etcd.io/etcd/client/v3"
"log"
"time"
)
type ServiceInfo struct {
Name string
IP string
}
type Service struct {
ServiceInfo ServiceInfo
stop chan error
leaseId clientv3.LeaseID
client *clientv3.Client
}
func NewServic... |
package game
import (
"math"
)
func accelerate(v, accel, dt float32) float32 {
val := v + (accel * dt)
return val
}
func easeIn(a, b, percent float32) float32 {
return a + (b-a)*float32(math.Pow(float64(percent), 2))
}
func easeOut(a, b, percent float32) float32 {
return a + (b-a)*(1-float32(math.Pow(1-float64... |
// This file was generated for SObject ListViewChart, API Version v43.0 at 2018-07-30 03:48:09.776494328 -0400 EDT m=+56.121206580
package sobjects
import (
"fmt"
"strings"
)
type ListViewChart struct {
BaseSObject
AggregateField string `force:",omitempty"`
AggregateType string `force:",omitempty"`
ChartT... |
package nmserial
import (
"bytes"
)
type Packet struct {
expectedLen uint16
buffer *bytes.Buffer
}
func NewPacket(expectedLen uint16) (*Packet, error) {
pkt := &Packet{
expectedLen: expectedLen,
buffer: bytes.NewBuffer([]byte{}),
}
return pkt, nil
}
func (pkt *Packet) AddBytes(bytes []byte) boo... |
// +build OMIT
package sample
import "encoding/json"
//START OMIT
type JSONData struct {
Name string `json:"command"`
Body json.RawMessage `json:"body"`
}
func LoadStruct(data []byte) (output JSONData) {
json.Unmarshal(data, &output)
return output
}
func LoadArray(data []byte) (output []JSONData)
//... |
/*
Copyright 2017 The Kubernetes Authors.
SPDX-License-Identifier: Apache-2.0
*/
package oimcsidriver
import (
"context"
"os"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/intel/oim/pkg/log"
"github.com/intel/oim/pkg/mount"
"github.com/intel/oim/pkg/spec... |
/*
* @file
* @copyright defined in aergo/LICENSE.txt
*/
package p2pcommon
import (
"github.com/aergoio/aergo/types"
)
const (
UnknownVersion = ""
)
// PeerMeta contains non changeable information of peer node during connected state
type PeerMeta struct {
ID types.PeerID
// IPAddress is human readable form of ... |
package ws
import (
"log"
"net/http"
"strings"
)
type Service struct {
host string
port string
}
var manager = &ClientManager{
message: make(chan *Message),
register: make(chan *Client),
unregister: make(chan *Client),
clients: make(map[string]*Client),
}
func (this *Service) SetServer (host, port st... |
package metricscharts
import (
"log"
"net/http"
"github.com/aalpern/go-metrics-charts/bindata"
)
func Register() {
http.HandleFunc("/debug/metrics/charts/", handleAsset("static/index.html"))
http.HandleFunc("/debug/metrics/charts/main.js", handleAsset("static/main.js"))
}
func handleAsset(path string) func(htt... |
package main
import "fmt"
func main() {
fmt.Printf("Func type nil:%#v\n", (func())(nil))
fmt.Printf("Map type nil:%#v\n", map[string]string(nil))
fmt.Printf("Slice type nil:%#v\n", []string(nil))
fmt.Printf("Interface{} type nil:%#v\n", nil)
fmt.Printf("Channel type nil:%#v\n", (chan struct{})(nil))
fmt.Printf(... |
package main
import (
"testing"
)
func TestSmallerNumbersThanCurrent(t *testing.T) {
}
|
package dpos
import (
"sync"
"time"
"github.com/bluele/gcache"
"github.com/qlcchain/go-qlc/common"
"github.com/qlcchain/go-qlc/common/types"
"github.com/qlcchain/go-qlc/consensus"
"github.com/qlcchain/go-qlc/ledger"
"github.com/qlcchain/go-qlc/ledger/process"
"github.com/qlcchain/go-qlc/p2p"
cabi "github.co... |
// Copyright 2015-2018 trivago N.V.
//
// 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 ... |
package models
import (
"encoding/json"
"strconv"
"time"
"github.com/GoAdminGroup/go-admin/modules/db"
"github.com/GoAdminGroup/go-admin/modules/db/dialect"
)
// MenuModel is menu model structure.
type MenuModel struct {
Base
Id int64
Title string
ParentId int64
Icon string
Uri str... |
package pci
import (
"fmt"
"runtime"
"unsafe"
"apic"
)
type legacy_disk_t struct {
rbase uintptr
allstat uintptr
}
func (d *legacy_disk_t) init(base, allst uintptr) {
d.rbase = base
d.allstat = allst
ide_init(d.rbase)
}
func (d *legacy_disk_t) Start(ibuf *Idebuf_t, writing bool) {
ide_start(d.rbase, d.... |
// Given an array S of n integers, find three integers in S
// such that the sum is closest to a given number,
// target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
// For example, given array S = {-1 2 1 -4}, and target = 1.
// The sum that is closest to t... |
package main
import "github.com/ekotlikoff/gochess/pkg/chessserver"
func main() {
chessserver.RunServer()
}
|
// +build js
// +build go1.16
package embed
func appendData(f *FS, name string, data string, hash [16]byte) {
var files []file
if f.files != nil {
files = *f.files
}
files = append(files, file{
name: name,
data: data,
hash: hash,
})
f.files = &files
}
|
package proxy
import (
"io/ioutil"
"net/http/httptest"
"testing"
"time"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/utils"
)
// go test -run Test_Proxy_Empty_Host
func Test_Proxy_Empty_Upstream_Servers(t *testing.T) {
defer func() {
if r := recover(); r != nil {
utils.AssertEqual(t, "Serve... |
package copyfile
import (
"errors"
"fmt"
"io"
"os"
"github.com/cheggaaa/pb"
)
const bufferSize = 1024 * 1024 * 10
// Copy from <from> file from <offset> position to <to> file <limit> bytes
func Copy(from, to string, limit, offset int) error {
if offset < 0 {
return errors.New("offset of source file must be ... |
package cascade
import (
"net/http"
"github.com/sirkon/goproxy/internal/errors"
"github.com/sirkon/goproxy"
"github.com/sirkon/goproxy/internal/module"
)
// NewPlugin plugin returning source pointing to another proxy
func NewPlugin(url string) goproxy.Plugin {
return &plugin{url: url, client: &http.Client{}, p... |
package auth
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document00100101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:auth.001.001.01 Document"`
Message *InformationRequestOpeningV01 `xml:"InfReqOpng"`
}
func (d *Document00100101... |
package main
import (
"fmt"
"runtime"
"sync"
"sync/atomic"
)
func main() {
var np sync.WaitGroup
fmt.Println("1st GR:", runtime.NumGoroutine())
var increment int64
ps := 100
np.Add(ps)
for i := 0; i < ps; i++ {
go func() {
atomic.AddInt64(&increment, 1)
fmt.Println(atomic.LoadInt64(&increment))
... |
package sync
import (
"encoding/json"
"fmt"
"github.com/spf13/viper"
"log"
"mbui/models"
"time"
)
func Start() {
key := viper.GetString("redis.key")
for {
item,err := models.Redis.RPop(key).Result()
if err != nil {
log.Println(err)
time.Sleep(time.Second)
continue
}
fmt.Println(item)
//入库... |
/*
* @lc app=leetcode.cn id=1051 lang=golang
*
* [1051] 高度检查器
*/
package main
import (
"sort"
)
// @lc code=start
func heightChecker(heights []int) int {
excepted := make([]int, len(heights))
for i := 0; i < len(heights); i++ {
excepted[i] = heights[i]
}
sort.Ints(excepted)
count := 0
for i := 0; i < len... |
package main
import "fmt"
// People START OMIT
type People struct {
name string
}
// People END OMIT
// Greet START OMIT
func (p People) Greet() string {
return fmt.Sprintf("Hello, my name is %s ", p.name)
}
// Greet END OMIT
// main START OMIT
func main() {
p := People{"Finch"}
fmt.Println(p.Greet())
fmt.Pr... |
// Copyright 2023 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
package shard
import (
"fmt"
"hash/crc32"
"sort"
"strconv"
)
const (
virtualNodeNum = 10
)
type HashRing []uint32
func (hr HashRing) Len() int {
return len(hr)
}
func (hr HashRing) Less(i, j int) bool {
return hr[i] < hr[j]
}
func (hr HashRing) Swap(i, j int) {
hr[i], hr[j] = hr[j], hr[i]
}
type Node str... |
package main
func isSymmetric(root *TreeNode) bool {
if root == nil || (root.Left == nil && root.Right == nil) {
return true
}
return help(root.Left, root.Right)
}
func help(t1, t2 *TreeNode) bool {
if t1 == nil && t2 == nil {
return true
}
if t1 == nil || t2 == nil {
return false
}
return t1.Val == t2.... |
package web
import (
"net/url"
"testing"
)
func Test_countFromQuery(t *testing.T) {
type args struct {
query url.Values
}
tests := []struct {
name string
args args
want int64
wantErr bool
}{
{"count exists", args{map[string][]string{"count": []string{"5"}}}, 5, false},
{"non-number count"... |
package binance
import (
"context"
"strconv"
bin "github.com/adshao/go-binance"
"github.com/mhereman/cryptotrader/logger"
"github.com/mhereman/cryptotrader/types"
)
// GetAccountInfo executes the get account info request
func (b *Binance) GetAccountInfo(ctx context.Context) (info types.AccountInfo, err error) {... |
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package redact
import (
"encoding/hex"
"strings"
"github.com/pingcap/errors"
)
// InitRedact inits the enableRedactLog
func InitRedact(redactLog bool) {
errors.RedactLogEnabled.Store(redactLog)
}
// NeedRedact returns whether to redact log
func NeedRed... |
package distribution
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"runtime"
"github.com/Sirupsen/logrus"
"github.com/docker/distribution"
"github.com/docker/distribution/digest"
"github.com/docker/distribution/manifest/schema1"
"github.com/docker/distribution/reference"
"github.com/docke... |
package nv7
import (
"context"
address "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
"github.com/ipfs/go-cid"
cbor "github.com/ipfs/go-ipld-cbor"
"golang.org/x/xerrors"
"github.com/filecoin-project/specs-actors/v2/ac... |
// Package user deletes, updates and returns an user.
package user
import (
"encoding/json"
"github.com/MerinEREN/iiPackages/api"
"github.com/MerinEREN/iiPackages/cookie"
"github.com/MerinEREN/iiPackages/datastore/account"
"github.com/MerinEREN/iiPackages/datastore/user"
"github.com/MerinEREN/iiPackages/session"... |
package main
import "fmt"
func main() {
fmt.Printf("%d is the sum of primes below 2 million\n", sumPrimes())
}
// Will loop through to 2 million
func sumPrimes() int {
var total int
for i := 2; i < 2000000; i++ {
if checkPrime(i) {
total += i
}
}
return total
}
// Checks if the number is prime or not
... |
package bidi
/*
Scanner:
✓ L EN → L // e.g., variable names: "var1"
✓ WS → NI // whitespace to neutral
✓ S → NI //
✓ NI ON → NI // except brackets
W1.
✓ AL NSM NSM → AL AL AL // done by scanner
✓ sos NSM → sos R // done by ... |
package crawlers
type OjuzCrawler struct {
}
|
package entity
import (
"go-tp-docker/db"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"log"
)
type Person struct {
ID primitive.ObjectID `bson:"_id, omitempty"`
Name string `bson:"name" json:"name"`
}
func Get() (*[]Person, error) {
client, ctx, cancel := db.GetMongoConnect... |
// 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 atomix
import (
"testing"
)
func TestUintptr(t *testing.T) {
a := NewUintptr(10)
mustEqual(t, a.String(), "10")
mustEqual(t, a.Load(), uintptr(10))
mustEqual(t, a.Add(5), uintptr(15))
mustEqual(t, a.Sub(3), uintptr(12))
mustEqual(t, a.CAS(12, 0), true)
mustEqual(t, a.Load(), uintptr(0))
mustEqual(... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2021/12/10 6:31 下午
# @File : lt_8_字符串转换整数atoi.go
# @Description :
# @Attention :
*/
package hot100
import "math"
// 关键是多种极端情况下的测验
func myAtoi(s string) int {
ret := 0
// 1. 去除前导前缀
index := 0
for ; index < len(s); {
if s[index] == ' ' {
index++
contin... |
package main
import (
"flag"
"fmt"
"github.com/gin-gonic/gin"
"log"
"net/http"
"net/http/httputil"
)
var remoteHost string
var localPort int
var httpsEnable bool
var simpleHostProxy = httputil.ReverseProxy{
Director: func(req *http.Request) {
req.URL.Scheme = "http"
req.URL.Host = remoteHost
req.Host = ... |
package main
import "fmt"
func main() {
// for <bool> == while <bool>
var x int
for x < 10 {
fmt.Println(x)
x++
}
for {
// infinity loop
}
}
|
package main
import "fmt"
func main() {
for i := 0; i <= 9; i++ {
fmt.Printf(" %v ", Fibonacci(i))
}
}
//Fibonacci function to generate fibonacci sequence
func Fibonacci(num int) int {
if num <= 1 {
return num
}
return Fibonacci(num-1) + Fibonacci(num-2)
}
|
package ssh
import (
"golang.org/x/crypto/ssh"
"log"
"bytes"
)
// Run command on remote server by ssh.
func Run(ip, user, pw, cmd string) (string, string, error) {
config := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.Password(pw),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
cli... |
package gui
import (
"github.com/faiface/pixel"
"github.com/faiface/pixel/imdraw"
"github.com/faiface/pixel/pixelgl"
"github.com/steelx/go-rpg-cgm/utilz"
"image/color"
)
type ProgressBarIMD struct {
x, y float64
Background color.RGBA
Foreground color.RGBA
foregroundPosition,
backgroundPosition pixel.V... |
package main
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
)
// TestEndpoint allows an easy way to test HTTP end points in unit testing
func TestEndpoint(method string, endpoint string, data io.Reader, handler http.HandlerFunc, valid bool) (code int, body *bytes.Buffer, err erro... |
package controllers
import (
ctx "context"
"hw8/models"
"net/http"
"strings"
"github.com/astaxie/beego"
"github.com/pkg/errors"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)
// MainController controller
type MainController struct {
bee... |
package main
import (
"fmt"
"math/rand"
"time"
"golang.org/x/net/context"
"github.com/Sirupsen/logrus"
"github.com/coreos/etcd/raft"
"github.com/coreos/etcd/raft/raftpb"
)
func save(rd raft.Ready, st *raft.MemoryStorage) error {
if !raft.IsEmptyHardState(rd.HardState) {
if err := st.SetHardState(rd.HardSt... |
package blocking
import (
"context"
"github.com/go-chi/render"
"github.com/ivansukach/bets/internal/tools"
log "github.com/sirupsen/logrus"
"net/http"
)
func (b *Blocking) BlockUsers(w http.ResponseWriter, r *http.Request) {
users := &BlockUsersReqModel{}
if err := render.Bind(r, users); err != nil {
log.Err... |
package main
import (
"os"
"github.com/therecipe/qt/core"
"github.com/therecipe/qt/gui"
"github.com/therecipe/qt/quick"
)
func main() {
core.QCoreApplication_SetAttribute(core.Qt__AA_EnableHighDpiScaling, true)
gui.NewQGuiApplication(len(os.Args), os.Args)
var translator = core.NewQTranslator... |
package pkg_test
import (
"testing"
"time"
"github.com/kyma-incubator/milv/pkg"
"github.com/stretchr/testify/assert"
)
func TestLimit(t *testing.T) {
//GIVEN
backoff := 1 * time.Second
waiter := pkg.NewWaiter(backoff)
before := time.Now()
expected := before.Add(backoff)
//WHEN
waiter.Wait()
//THEN
aft... |
package main
import (
"flag"
// "github.com/google/gopacket/afpacket"
"net"
"time"
"github.com/lflxp/sflowtool/collected"
)
var Con collected.Collected = collected.Collected{
DeviceName: "en0",
SnapShotLen: 65535,
Promiscuous: true,
Timeout: 30 * time.Second,
}
func main() {
wait := make(chan int)
i... |
// 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 model
import (
"fmt"
)
type Generic struct{}
func (g Generic) SendEmail(email string) {
fmt.Println("Sorry but were not in that time!!!")
}
func (g *Generic) Evaluation(c *Candidate) {
if len(c.GetKnowledge()) == 0 {
g.SendEmail(c.GetEmail())
}
}
func NewGeneric() *Generic {
return &Generic{}
}
|
package service
import (
"github.com/Surafeljava/Court-Case-Management-System/caseUse"
entity "github.com/Surafeljava/Court-Case-Management-System/Entity"
)
type LoginServiceImpl struct {
loginRepo caseUse.LoginRepository
}
func NewLoginServiceImpl(logRepo caseUse.LoginRepository) *LoginServiceImpl {
return &Lo... |
package goNBT
import (
"fmt"
// "os"
"io"
"strings"
)
const (
TAG_END byte = iota
TAG_BYTE
TAG_SHORT
TAG_INT
TAG_LONG
TAG_FLOAT
TAG_DOUBLE
TAG_BYTE_ARRAY
TAG_STRING
TAG_LIST
TAG_COMPOUND
TAG_INT_ARRAY
)
const (
NONE byte = 0
GZIP byte = 1
ZLIB byte = 2
FLATE byte = 3
LZW byte ... |
// Copyright 2019 Yunion
//
// 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 writi... |
package netgo
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
)
// ReaderFunc represents request body type
type ReaderFunc func() (io.Reader, error)
// Request ..
type Request struct {
body ReaderFunc
*http.Request
}
type lenner interface {
Len() int
}
// NewRequest ..
func NewRequest(method,... |
// Copyright 2023 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applica... |
package data
type Session struct {
Id int
Uuid string
Email string
UserId int
UserIdStr string
CreatedAt string
}
// Check the session for an existing user
func (session *Session) Check() (valid bool, err error) {
db := NewDB()
defer db.Close()
query := `SELECT * FROM sessions
WHERE u... |
package gates
import (
"context"
"github.com/go-kit/kit/log"
"github.com/jmoiron/sqlx"
)
type OpaqueRepository interface {
FindToken(context.Context, string) (*Opaque, error)
SaveToken(context.Context, int, string) (*Opaque, error)
RemoveToken(context.Context, string) error
}
type GateRepo struct {
Db *sqlx.... |
package explorerutils
import (
"bytes"
"encoding/json"
"fmt"
"log"
"os"
)
type ConnectionProfile struct {
Name string `json:"name"`
Version string `json:"version"`
License string `j... |
package main
import (
"fmt"
)
func main () {
var a []int
printSlice("a", a)
a = append(a, 0)
printSlice("a", a)
a = append(a, 1, 2, 3, 4, 5, 6, 7)
printSlice("a", a)
a = append(a, 0)
printSlice("a", a)
var fib = []int{1, 1, 2, 3, 5, 8, 13, 21, 34, 55}
for i, v := range fib {
fmt.Printf("[i,v] = [%d,... |
package client
import (
"net"
"os"
log "github.com/sirupsen/logrus"
_ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
// getConfig returns a kubernetes config for configuring a client from a kubeconfig string
func getConfig(kubeconfig string) (*rest.C... |
package day8
import "errors"
type PhoneBook struct {
contacts map[string]int
}
func (p PhoneBook) NewPhoneBook() PhoneBook {
return PhoneBook{contacts: make(map[string]int)}
}
func (p *PhoneBook) Add(name string, number int) {
p.contacts[name] = number
}
func (p PhoneBook) GetSize() int {
return len(p.contacts... |
package trace
import (
"fmt"
"time"
)
// A trace
type Trace interface {
Timestamp()(time.Time)
Context()(interface{})
Message()(string)
Error()(error)
}
// A non-error message trace
type messageTrace struct {
when time.Time
message string
context interface{}
}
func NewMessage(m string) Trace {
... |
package main
import "fmt"
// Structs are a way to construct a collection of items together for a similar purpose
// Point contains 2 ints to represent a coordinate point
// An important note is if you want the struct to be used outside its file, it has to start with an uppercase letter
type Point struct {
x int
y i... |
package config
// appSettings is the api url for admin information
type appSettings struct {
// URL admin url for dashboard
Url string
// Token Connection token / license
Token string
// maxT maximum number of threads to use
MaxT int
}
// Init initialize the config
func Init() {
conf := appSettings{}
//get ... |
/*****************************************************************
* Copyright©,2020-2022, email: 279197148@qq.com
* Version: 1.0.0
* @Author: yangtxiang
* @Date: 2020-08-17 15:24
* Description:
*****************************************************************/
package xhttpServer
import (
"bytes"
"encoding/json"
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.