text
stringlengths
11
4.05M
package main import ( "testing" "github.com/testify/assert" ) func TestRandom(t *testing.T) { result := random(0, 10) assert.NotNil(t, result, "result should not null") } func TestGenerateBoardArray(t *testing.T) { x := 3 y := 2 testBoard := generateBoardArray(x, y, 0) for a := 0; a < x; a++ { for b := 0;...
package main import ( "fmt" "flag" "strconv" ) func init_vector (vector *[][]int, fils int, cols int) { for i := 0; i < fils; i++ { for j := 0; j < cols; j++ { (*vector)[i][j] = 1; } } } func print_vector (vector *[][]int, fils int, cols int) { for i := 0; i < fils; i++ { for j := 0; j < cols; j++ { ...
package controllers import ( "fmt" "fairy/storage" "fairy/config" ) type MenuController struct { BaseController } func (this *MenuController) GetMenuList() { fmt.Printf("Call GetMenuList\n") // Set default offset & limit offset, err:= this.GetInt("offset") if err != nil { offse...
package httpclient import ( "bytes" "crypto/tls" "encoding/json" "fmt" "io/ioutil" "net/http" "strings" ) type Client struct { AccessToken string } func NewClient() *Client { return &Client{} } func NewClientWithToken(token string) *Client { return &Client{ AccessToken: token, } } func (c *Client) Get...
// Copyright (c) The Tellor Authors. // Licensed under the MIT License. package cli import ( "context" "math/big" "time" "github.com/ethereum/go-ethereum/crypto" "github.com/go-kit/kit/log" "github.com/go-kit/kit/log/level" "github.com/pkg/errors" "github.com/tellor-io/telliot/pkg/contracts" "github.com/tel...
package client import ( "encoding/json" "fmt" "github.com/wish/ctl/cmd/util/config" "github.com/wish/ctl/pkg/client/types" ) // FindAdhocPodAndAppDetails loops through all valid contexts and returns the first adhoc pod found along with context details about the pod func (c *Client) FindAdhocPodAndAppDetails(appNa...
package main import ( "io/ioutil" "log" "path/filepath" "regexp" "sort" "sync" "github.com/davecgh/go-spew/spew" "github.com/fsnotify/fsnotify" "gopkg.in/yaml.v2" ) const ( configPath = "/defaults/config.yaml" logLevelDebug = "debug" ) // this tool runs in three modes: // controller: which runs in sou...
package queryrange import ( "context" "time" "github.com/weaveworks/common/user" ) const millisecondPerDay = int64(24 * time.Hour / time.Millisecond) // SplitByDayMiddleware creates a new Middleware that splits requests by day. func SplitByDayMiddleware(limits Limits) Middleware { return MiddlewareFunc(func(nex...
package main import ( "fmt" "io" "net/http" "os" "strconv" "time" "github.com/cheggaaa/pb" ) type WriteCounter struct { Total uint64 DownloadSize uint64 ProgressBar *pb.ProgressBar } // PrintProgress prints the progress of a file write func (wc WriteCounter) PrintProgress() { // Clear the line by...
package slack import ( "bytes" "encoding/json" "errors" "net/http" ) type Slack struct { webHookURL string level string userName string icon string channel string content string attachments []Attachment } type Attachment struct { Title string `json:"title"` Color string ...
// The any-orbits program calculates the orbital // speed of any satellite in orbit around Earth. // // This program is incomplete. You need to finish it before it will run. // // You'll need to know the radius of the Earth is 6378km to complete the program. // // Try the program out with these numbers // // The averag...
package skpsilk // silk/src/SKP_Silk_lin2log.go func lin2log(inLin int32) int32 { var lz, frac_Q7 int32 CLZ_FRAC(inLin, &lz, &frac_Q7) return ((31 - lz) << 7) + SMLAWB(frac_Q7, frac_Q7*(128-frac_Q7), 179) }
/* Every month, Microny™️ (a big entertainment corporation) publishes a few free videogames on their web store. You are working on a script that will notify you whenever the new games are available for download. There is not a fixed date for the new releases, but you know that it happens every first Tuesday of every m...
package main import ( "fmt" "html/template" "net/http" "github.com/costap/healthcheckapp/controllers" "github.com/costap/healthcheckapp/repository" "github.com/julienschmidt/httprouter" ) var tpl *template.Template func init() { tpl = template.Must(template.ParseGlob("templates/*")) } func main() { fmt.Pr...
package main import ( "flag" "fmt" "github.com/iyurev/go_dell_emc_unity_api/unity_api" "log" "regexp" "strings" ) func emthyArg(arg *string) bool { if *arg == "" { return true } return false } func sliceFromArg(arg string) []string { res_slice := []string{} raw_list := strings.Split(arg, ",") reg, e :=...
package persistent_storage import ( "hub/framework" "hub/persistent_storage/file_operation_status" "io/ioutil" "os" "testing" ) const ( readme = "README" file1 = "dummy_file.ext" file2 = "dummy_file.ext2" notExistingFile = "not_existing_file.ext" notExistingFile2...
package openapi import ( "encoding/json" "io/ioutil" "testing" "github.com/stretchr/testify/assert" ) // TestTesters tests the testers helpers // that determines the kind of a type. func TestTesters(t *testing.T) { var ( s string m map[string]string n1 uint n2 int ) assert.True(t, isString(rt(s))) ...
//go:generate mockgen -destination=./mock/resize_mock.go github.com/nomkhonwaan/myblog/pkg/image Resizer package image import ( "bytes" "github.com/disintegration/imaging" "image/png" "io" ) // Resizer uses to resize an image file to the given width and height. // The resize function should treat aspect ratio if...
package main import ( "bufio" "encoding/json" "fmt" "os" ) func main() { scanner := bufio.NewScanner(os.Stdin) var name, address string fmt.Println("Enter name : ") if scanner.Scan() { name = scanner.Text() } fmt.Println("Enter address : ") if scanner.Scan() { address = scanner.Text() } idMap := m...
package maprost import ( "github.com/maprost/application/example/maprost/internal" "github.com/maprost/application/example/maprost/internal/google" "github.com/maprost/application/generator/genmodel" "log" ) var allCompanies = map[string]func() genmodel.JobPosition{ "google": google.Google, } func Application(c...
package connect import ( "encoding/binary" "errors" "net" "github.com/xgheaven/localmap/logger" "github.com/xgheaven/localmap/util" ) /* block |type:4, none: 5|other...| hello block 1b |0000xxxx| hello reply block 5b |0001xxxx|server port||client port|| request new connect 1b |0010xxxx| request new rep...
package game import ( "fmt" "sync" "strconv" "runtime" pb "code.google.com/p/goprotobuf/proto" "sofa/proto" "sofa/con" ) // type GameRoom struct { *Uid2Player GameStatus Uid2Seat Seat2UserData Uid2Winner CurNum uint32 GameParam *proto.C2SStartGame ...
package base32 import ( "bytes" "crypto/rand" "math/big" "testing" ) var tests = []struct { decoded, encoded string }{ {"", ""}, {"f", "cr"}, {"fo", "csqg"}, {"foo", "csqpy"}, {"foob", "csqpyrg"}, {"fooba", "csqpyrk1"}, {"foobar", "csqpyrk1e8"}, {"Twas brillig, and the slithy toves", "ahvp2ws0c9s6jv3cd5k...
package server import ( "encoding/json" "fmt" "log" "net/http" ) type serverResponse struct { Message string `json:"message"` } type serverRequest struct{ Name string `json:"name"` } func serverHandler(w http.ResponseWriter, r *http.Request){ var request serverRequest decoder := json.NewDecoder(r.Body) ...
package agency import ( "github.com/bububa/oppo-omni/core" "github.com/bububa/oppo-omni/model/communal/agency" ) // 代理商客户查询 func CustomerList(clt *core.SDKClient, req *agency.CustomerListRequest) (*agency.CustomerListResult, error) { req.SetResourceName("communal") req.SetResourceAction("agency/customer/list") v...
package main import ( "fmt" "math" "github.com/jackytck/projecteuler/tools" ) var log = math.Log10 func m(a, b int) int { return tools.MinInt(a, b) } func over(es ...int) bool { d := 1 for _, v := range es { if v == 0 { continue } d *= 2*v + 1 } return d > 8000000 } func solve() int64 { primes :...
package metre type Task struct { ID string // Type Type of task (user as class prefix in cache) Interval string // Schedule String in cron notation Schedule func(t TaskRecord, s Scheduler, c Cache, q Queue) Process func(t TaskRecord, s Scheduler, c Cache, q Queue) }
package main import ( "bytes" "flag" "fmt" "io" "os" "path/filepath" "strings" "text/template" ) // Command represents a redux command such as redo, ifchange, etc. type Command struct { // Run runs the command. Run func(args []string) error // LinkName is the the name used to link to the executable so it...
package xlsx import ( "github.com/plandem/xlsx/internal/ml" "github.com/plandem/xlsx/internal/ml/primitives" "github.com/plandem/xlsx/options" "github.com/stretchr/testify/require" "testing" ) func TestSheetInfo(t *testing.T) { require.Equal(t, true, isCellEmpty(nil)) require.Equal(t, true, isCellEmpty(&ml.Cel...
package main import ( "encoding/json" "github.com/dearcj/golangproj/bitmask" "github.com/fatih/structs" "go.uber.org/zap" "io/ioutil" "time" ) type MapID = uint32 type Components struct { Unit bitmask.Bitmask Fish bitmask.Bitmask Player bitmask.Bitmask MiscObject bitmask.Bitmask } type Con...
package otf import ( "io" ) func os_2Parser(_ SFNT, r *io.SectionReader) Table { return ReadTable(r, new(OS_2)) } func (_ *OS_2) Tag() TAG { return TAG_OS_2 } func (t *OS_2) Bytes() []byte { return DumpBigEndian(t) } func (t *OS_2) SetUp(f SFNT) error { // FIXME: it must be implemented return nil } type OS_...
package main import ( "fmt" "image" "image/color" "image/color/palette" "image/gif" "os" ) const ( w = 480 h = 84 ) // HandsData 手数 type HandsData struct { img *image.Paletted } // CreateHandsData ... func CreateHandsData() *HandsData { return &HandsData{img: image.NewPaletted(image.Rect(0, 0, w, h), pale...
package it import ( "net/http" ) type itView struct { } func NewItView() *itView { v := new(itView) return v } func (v *itView) Render(responseWriter http.ResponseWriter) error { var err error _, err = responseWriter.Write([]byte("<html><head></head><body>")) if err != nil { return err } _, err = response...
package gadk import ( "encoding/json" "errors" "time" ) //Transaction is transaction structure for adk. type Transaction struct { SignatureMessageFragment Trytes Address Address Value int64 `json:",string"` Tag Trytes Timestamp time.Time...
package gopd import ( "io" "net/http" "fmt" "io/ioutil" "encoding/json" "strings" ) type Response struct { Uuid string `json:"uuid"` Status string `json:"status"` Name string `json:"name"` DateCreated string `json:"date_created"` DateModified string `json:"date_modified"` } type P...
package problem0733 import "testing" func TestSolve(t *testing.T) { t.Log(floodFill([][]int{{0, 0, 0}, {0, 0, 0}}, 0, 0, 2)) }
package main import ( // "log" "github.com/Unknwon/goconfig" "strconv" ) const ( version = "0.3" defaultListenAddrPort = "127.0.0.1:8080" ascii_icon = ` ____==========_______ _--____ | | "" " "| \ / )8} ^^^| 0 | = ...
package transbytes import ( "fmt" "strconv" ) func SizeToString(bytes float64) string { size, form := SizeToFloatAndString(bytes) return fmt.Sprintf("%+v %s", strconv.FormatFloat(size, 'f', 2, 64), form) } func SizeToFloatAndString(bytes float64) (float64, string) { size, sizeForm := transformBytes(bytes, 1) v...
package manifests import ( "encoding/json" "fmt" "os" "path/filepath" "github.com/pkg/errors" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/validation/field" "sigs.k8s.io/yaml" "github.com/openshift/installer/pkg/asset" "github.com/openshift/instal...
// Copyright 2015 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 findKthLargest import "testing" func Test_findKthNum(t *testing.T) { type args struct { nums []int k int } tests := []struct { name string args args wantRet int }{ // TODO: Add test cases. { name: "first", args: args{ nums: []int{5, 4, 3, 2, 1, 6, 7, 8, 9, 0}, k: 1,...
package handler import ( "bytes" "fmt" "github.com/bitmaelum/bitmaelum-suite/internal" "github.com/bitmaelum/bitmaelum-suite/internal/config" "net/http" "strings" ) // HomePage Information header on root / func HomePage(w http.ResponseWriter, req *http.Request) { // Simple enough so things like curl work html...
package main import ( "flag" "fmt" "runtime" "time" "github.com/RoaringBitmap/roaring/roaring64" "github.com/evanj/hacks/trivialstats" ) func main() { numConsecutive := flag.Int("numConsecutive", 5000, "number of consecutive time samples to measure at program start") minInterestingDiff := flag.Duration("mi...
package server import ( "fmt" "os" "strconv" "github.com/gorilla/sessions" "github.com/labstack/echo-contrib/session" "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" "github.com/mixnote/mixnote-api-go/configs" "github.com/mixnote/mixnote-api-go/src/framework/middlewares" "github.com/m...
package lib import ( "math/rand" ) // A Map represents a level in the game. type Map struct { // Depth determines the level of this map in the game. Depth int // Tiles stores the tiles in a 2d matrix. Tiles [][]Tile } // Width returns the width of the map func (m *Map) Width() int { return len(m.Tiles[0]) } ...
package controllers_test import ( "encoding/json" "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" "github.com/GoPex/caretaker/bindings" "github.com/GoPex/caretaker/controllers" "github.com/GoPex/caretaker/helpers" ) // Test the GetPing handler func TestGetPing(t *testing.T) { req, _ := ...
package netutil // IsTemporaryError checks whether the given error should be considered temporary. func IsTemporaryError(err error) bool { tempErr, ok := err.(interface { Temporary() bool }) return ok && tempErr.Temporary() || isPacketTooBig(err) }
package types import ( "encoding/json" "github.com/gorilla/websocket" "time" ) const ( COMMAND_OK int32 = 0 COMMAND_QUIT int32 = 1 COMMAND_RECONNECT int32 = 2 ) type Packet map[string]string type GPSRecord struct { Latitude string Longitude string Message string Speed float64 Heading ...
package main import ( "fmt" "strings" ) func main() { fmt.Println("Nabil") fmt.Println("Nabil Fawwaz") fmt.Println("Nabil Fawwaz Elqayyim") fmt.Println(len("Nabil")) fmt.Println("Nabil"[1]) fmt.Println(strings.Contains("Nabil Fawwaz Elqayyim", "Nabil")) fmt.Println(strings.Split("Nabil Fawwaz Elqayyim", " "...
package saml import ( "encoding/xml" "testing" "github.com/pkg/errors" ) func TestSAMLResponse(t *testing.T) { tests := []struct { Name string SAMLResponseXML string ResIssuer string AssertionIssuer string }{ { Name: "Test when Issuer is only present in the Assertion", SAMLRespo...
package main import ( "context" "fmt" "github.com/alexzimmer96/eventing" "github.com/alexzimmer96/eventing/provider" uuid "github.com/satori/go.uuid" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "log" ) func main() { database := connectToMongo("localhost", "27017", "root", ...
package commandjsonio import ( "context" "encoding/json" "io" "os/exec" ) func setupExecCmd(ctx context.Context, exePath string, cmdArgs, cmdEnvs []string, workDir string) (cmd *exec.Cmd) { cmd = exec.CommandContext(ctx, exePath, cmdArgs...) cmd.Dir = workDir if len(cmdEnvs) > 0 { cmd.Env = cmdEnvs } retur...
package v1 import ( "context" "fmt" "testing" "github.com/asecurityteam/nexpose-vuln-hydrator/pkg/domain" gomock "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" ) func TestHydratorHandleSuccess(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockHydrator := NewMockH...
package model import ( "Seaman/utils" "time" ) type TplExportTypeT struct { Id int `xorm:"not null pk autoincr INT(11)"` ExportType string `xorm:"not null comment('类型') unique VARCHAR(64)"` Description string `xorm:"not null comment('描述') VARCHAR(256)"` TemplateFilePath stri...
package uixt import ( "fmt" "time" "github.com/pkg/errors" "github.com/rs/zerolog/log" "github.com/httprunner/httprunner/v4/hrp/internal/code" ) func assertRelative(p float64) bool { return p >= 0 && p <= 1 } // SwipeRelative swipe from relative position [fromX, fromY] to relative position [toX, toY] func (d...
// 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 in wr...
/* * @lc app=leetcode.cn id=7 lang=golang * * [7] 整数反转 * * https://leetcode-cn.com/problems/reverse-integer/description/ * * algorithms * Easy (32.82%) * Likes: 1231 * Dislikes: 0 * Total Accepted: 164.6K * Total Submissions: 501.7K * Testcase Example: '123' * * 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转...
package log import ( "fmt" "os" "runtime/debug" l4g "github.com/mysll/log4go" ) var ( log l4g.Logger ) func init() { log = make(l4g.Logger) l4g.LogCallerDepth = 3 lw := l4g.NewFormatLogWriter(os.Stdout, "[%D %T] [%L] (%S) %M") log.AddFilter("stdout", l4g.DEBUG, lw) } func SetLogLevel(filtname string, lvl ...
package main import ( "encoding/json" "flag" "io/ioutil" "log" "net/http" "net/url" "os" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" ) type reading struct { CID string `json:"cid"` SID string `json:"sid"` Val...
package validation import ( "fmt" "sort" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/validation/field" "github.com/openshift/installer/pkg/types/azure" "github.com/openshift/installer/pkg/types/azure/defaults" ) const ( enabled = "Enabled" ) var ( validSecurityEncryptionTypes = map[az...
package service import ( "context" "os" "time" "github.com/pkg/errors" "github.com/shharn/blog/logger" "github.com/shharn/blog/session" goOAuth "golang.org/x/oauth2" "golang.org/x/oauth2/google" googleOAuth "google.golang.org/api/oauth2/v2" googleOption "google.golang.org/api/option" ) const ( googleO...
package middleware import ( "github.com/kataras/iris/v12/context" ) func LogMiddleware(ctx context.Context) { ctx.Application().Logger().Infof("Path: %s | IP: %s", ctx.Path(), ctx.RemoteAddr()) ctx.Next() }
package amqp import ( "context" "errors" "sync" "testing" "github.com/Azure/go-amqp" myamqp "github.com/brigadecore/brigade/v2/internal/amqp" "github.com/brigadecore/brigade/v2/scheduler/internal/lib/queue" "github.com/stretchr/testify/require" ) func TestNewReaderFactory(t *testing.T) { const testAddress =...
package sliding_window import ( "fmt" "testing" ) func TestPermutationInString(t *testing.T) { // 包含: 排列为"ba" fmt.Println(PermutationInString("ab", "eidbaoii")) // 不包含: 输出空 fmt.Println(PermutationInString("ab", "eidboaii")) // 包含: 排列为"ii",支持重复字符 fmt.Println(PermutationInString("ii", "e...
/* * @lc app=leetcode.cn id=2171 lang=golang * * [2171] 拿出最少数目的魔法豆 */ package main import ( "sort" ) // @lc code=start func minimumRemoval(beans []int) int64 { sort.Ints(beans) sum := 0 for i := 0; i < len(beans); i++ { sum += beans[i] } ret := sum - len(beans)*beans[0] pre := 0 for i := 1; i < len(bea...
package model import ( "Seaman/utils" "time" ) type TplOrgT struct { Id int64 `xorm:"pk autoincr BIGINT(20)"` PId int64 `xorm:"comment('父ID') BIGINT(20)"` OrgName string `xorm:"not null comment('部门名称') VARCHAR(255)"` OrgCode string `xorm:"not null comme...
package main import ( "encoding/json" "fmt" "log" "net/http" "time" ) func main() { handler := http.NewServeMux() const numEndpoints = 1 for i := 0; i < numEndpoints; i++ { route := fmt.Sprintf("/cluster/%d", i) handler.HandleFunc(route, func(w http.ResponseWriter, r *http.Request) { w.Header().Set...
package main // 翻转字符串 func reverseString(s string) (string ,bool) { str :=[]rune(s) l :=len(str) if l>5000 { return s,false } for i :=0;i<l/2; i++ { str[i],str[l-1-i]=str[l-1-i],str[i] } return string(str),true }
package main import ( "fmt" ) type Person struct { Name string } type Allomancer struct { Name *Person MistingType string Metals string } func NewAllomancer(name, mistingType, metals string) Allomancer { return Allomancer{ Name: &Person{name}, MistingType: mistingType, Metals: me...
package win32 // HResult is a vendor-extensible system for error codes used by WinNT APIs // and COM. // // https://msdn.microsoft.com/en-us/library/cc231198.aspx type HResult uint32 // Various masks for dealing with HResult values. const ( HResultSeverityMask = 0x80000000 HResultReservedMask = 0x40000000 HResultC...
package mathematics import "fmt" func ExampleIsPrime() { for i := 2; i <= 10; i++ { if IsPrime(i) { fmt.Printf("%d is prime!\n", i) } else { fmt.Printf("%d is not prime...\n", i) } } // Output: // 2 is prime! // 3 is prime! // 4 is not prime... // 5 is prime! // 6 is not prime... // 7 is prime! ...
package util import ( "user/db" "github.com/astaxie/beego" "github.com/garyburd/redigo/redis" ) type RedisKGS struct { redis *db.RedisDb nextIdKey string } func (redisKGS *RedisKGS) NextId() int64 { c := redisKGS.redis.Connection() defer c.Close() nextId, _ := redis.Int64(c.Do("INCR", redisKGS.nextIdKey...
package collect import ( "compress/gzip" "encoding/json" "fmt" "io" "net/http" "strconv" "strings" "time" "github.com/kaz/pprotein/internal/storage" ) type ( Snapshot struct { store storage.Storage *SnapshotMeta *SnapshotTarget } SnapshotMeta struct { Type string ID string Da...
package main import ( "encoding/json" "fmt" "net/http" "net/smtp" "strconv" "github.com/domodwyer/mailyak" "github.com/gorilla/mux" "github.com/jinzhu/gorm" ) func Allbus(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Content-Type", "application...
package jpush func (c *Client) FileGetList() (map[string]interface{}, error) { link := c.pushUrl + "/v3/files" resp, err := c.request("GET", link, nil, false) if err != nil { return nil, err } return resp.Map() } func (c *Client) FileView(fileId string) (map[string]interface{}, error) { link := c.pushUrl + "/...
package Framework type RouterSvc struct{} func (this *RouterSvc)
package web_dao import ( "2021/yunsongcailu/yunsong_server/dial" "2021/yunsongcailu/yunsong_server/web/web_model" ) type CategoryDao interface { // 获取所有类别 QueryCategoryAll() (categoryAll []web_model.CategoryModel,err error) // 获取所有激活类别 QueryCategory() (categories []web_model.CategoryModel,err error) // 修改类别 U...
package routes import "net/http" func Redirect(w http.ResponseWriter, req *http.Request) { w.Header().Add("Strict-Transport-Security", "max-age=63072000; includeSubDomains") http.Redirect(w, req, "https://localhost:5000"+req.RequestURI, http.StatusMovedPermanently) }
package core import "net/http" type AppHandler func(http.ResponseWriter, *http.Request) error // Interceptor for errors func (fn AppHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if err := fn(w, r); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } }
package main import ( "nginx-manager/router" "nginx-manager/utils" ) func main() { utils.Logger() r := router.SetupRouter() // Listen and Server in 0.0.0.0:8080 r.Run(":8089") }
package repository import ( "fmt" "github.com/isutton/orchid/pkg/orchid/orm" ) // Nested is responsible by given a Unstructured object it's able to return any field path nested // in object's data. type Nested struct { schema *orm.Schema obj map[string]interface{} lines []orm.Entry } // nestedExtract recur...
// Package linked_list // Node.HasCycle 判断链表中是否有环 // Node.GetCycle 获取环的起始位置 package linked_list // HasCycle 判断链表中是否有环 // 快慢指针遍历 func (head *Node) HasCycle() bool { fast, slow := head, head for fast != nil && fast.next != nil { fast = fast.next.next slow = slow.next // 如果有环,快指针最终会追上慢指针 ...
package services import ( "context" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/ec2/ec2iface" ) type EC2 interface { ec2iface.EC2API DescribeSecurityGroupsAsList(ctx context.Context, input *ec2.DescribeSecurityGroupsInput) ([]*ec2.Security...
// Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 package chainimpl import ( "github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/address" "sync" "time" "github.com/iotaledger/hive.go/events" "github.com/iotaledger/wasp/packages/tcrypto" "github.com/iotaledger/wasp/packages/vm/pr...
//Package binarysearchtree 实现了二叉搜索树数据结构 package binarysearchtree import ( "container/list" "reflect" ) //Item:树节点的数据可以是任意类型 type Item interface{} //TreeNode:结点结构 type TreeNode struct { Val int Left *TreeNode Right *TreeNode } //将传入数组转换成二叉树 func arrayToBinTree(nums []Item) *TreeNode { queue := list.New() i...
package nats import ( "errors" "strings" "sync" pubsub "github.com/zhangce1999/pubsub/interface" ) // DefaultSeparator - var ( DefaultSeparator = '/' ) // Trie - type Trie interface { Empty() bool Size() int Clear() // Trie interface, middlewares will be executed in order Put(route string, handlers ...pu...
package domain var ( _true = true _false = false FreeUndefined *bool FreeTrue = &_true FreeFalse = &_false ) // Catalog is the information for the services provided by a // service broker. type Catalog struct { // Services is a list of services provided by the broker. Services []Service...
/* An array a is called beautiful if for every pair of numbers ai, aj, (i ≠ j), there exists an ak such that ak = ai * aj. Note that k can be equal to i or j too. Find out whether the given array a is beautiful or not! */ package main import ( "fmt" ) func main() { a := []int{0, 1} fmt.Println(beautifulSlow(a),...
package metrics import ( "fmt" "net/url" "strings" "sync" "time" "github.com/lexesjan/go-web-proxy-server/pkg/cache" ) // Metrics represents the metrics stored for the proxy type Metrics struct { timeSaved *sync.Map bandwidthSaved *sync.Map } // NewMetrics returns a new Metrics struct func NewMetrics()...
package database import ( "fmt" "github.com/jmoiron/sqlx" "github.com/pkg/errors" "github.com/spf13/viper" ) var DB *sqlx.DB type DSN struct { Host string Port int User string Password string DBName string } func ConnectPG() (err error) { var dsnObj DSN if err := viper.UnmarshalKey("DB", &d...
// Copyright 2017 The OpenSDS 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 agre...
package softphone import ( "crypto/md5" //nolint "fmt" "math/rand" "strings" "time" "github.com/google/uuid" ) // SIPInfoResponse ... type SIPInfoResponse struct { Username string `json:"username"` Password string `json:"password"` Domain string `json:"domain"` WebsocketURL string `json:"websocket_url"` C...
package Memcache import ( "xwork/BootStrap/Artisan" cache "xwork/Extend/Cache" "xwork/Extend/Gophp" "errors" "fmt" "strconv" "strings" "time" "github.com/bradfitz/gomemcache/memcache" "github.com/dgryski/go-fastlz" "github.com/gookit/validate" "github.com/spf13/viper" ) // Cache Memcache adapter. type Ca...
package ledger import ( txComm "github.com/HNB-ECO/HNB-Blockchain/HNB/common" dbComm "github.com/HNB-ECO/HNB-Blockchain/HNB/db/common" "github.com/HNB-ECO/HNB-Blockchain/HNB/ledger/blockStore" bsComm "github.com/HNB-ECO/HNB-Blockchain/HNB/ledger/blockStore/common" "github.com/HNB-ECO/HNB-Blockchain/HNB/ledger/mer...
package hot100 import "sort" type arrSorts [][]int func (a arrSorts) Len() int { return len(a) } func (a arrSorts) Less(i, j int) bool { return a[i][0] < a[j][0] } func (a arrSorts) Swap(i, j int) { a[i], a[j] = a[j], a[i] } // 关键: // 1. 排序 // 2. for 循环,如果该index的数组的最后一个值比result中的最后一个的数组的最后一个小,则合并 // 3. 合并的时候还有...
package pdu import ( "fmt" "reflect" "strconv" "strings" "unicode" ) var types = map[CommandID]reflect.Type{} var commandIDNames = map[CommandID]string{} func init() { pduTypes := []interface{}{ AlertNotification{}, GenericNACK{}, Outbind{}, BindReceiver{}, BindReceiverResp{}, BindTransceiver{}, BindTra...
//go:build go1.21 package indenthandler import ( "context" "fmt" "io" "log/slog" "runtime" "sync" "time" ) // !+types type IndentHandler struct { opts Options // TODO: state for WithGroup and WithAttrs mu *sync.Mutex out io.Writer } type Options struct { // Level reports the minimum level to log. // L...
package csv import ( "encoding/csv" "encoding/json" "fmt" "github.com/queueup-dev/qup-io/v2/reflection" "io" "reflect" ) func (h headerAndBaseRecord) Unmarshal(input []string, out interface{}) error { return h.UnmarshalValue(input, reflect.ValueOf(out)) } func (h headerAndBaseRecord) UnmarshalValue(csvRecord ...
package repository import ( "github.com/jmoiron/sqlx" "github.com/msvetkov/notes-app/pkg/domain" ) type Authorization interface { CreateUser(user domain.User) (int, error) GetUser(username, password string) (domain.User, error) } type Note interface { Create(note domain.Note) (int, error) GetAll(userId int) ([...
package search import ( "bytes" "encoding/binary" "fmt" "github.com/telyn/midi/korg/korgdevices" ) type Response struct { Channel uint8 EchoBackID uint8 Family uint16 Member uint16 Major uint16 Minor uint16 } func (sr Response) Device() korgdevices.Device { return korgdevices.Device(...