text
stringlengths
11
4.05M
package client import ( "io/ioutil" "log" "net/http" ) func DetectConnection(ip string) bool { log.Println("Connecting to " + ip) test, err := http.Get(ip) if test != nil { log.Println("found in request: ") log.Println(test) } else { log.Println(err) return false } defer test.Body.Close() Output, er...
package main import "fmt" func main() { var grade string switch level:=1; level { case 1: grade = "A" case 2: grade = "B" case 3, 4, 5: grade = "C" default: grade = "D" } switch { case grade == "A": fmt.Println("优秀") case grade == "B", g...
package fieldutils import "strings" func NormalizedStringField(str string) string { return strings.TrimSpace(strings.Join(strings.Fields(str), "")) }
package models import ( "encoding/json" "fmt" "os" "path" "github.com/gofrs/uuid" SMP "github.com/layer5io/service-mesh-performance/spec" "github.com/pkg/errors" "github.com/prologic/bitcask" "github.com/sirupsen/logrus" ) // BitCaskTestProfilesPersister assists with persisting session in a Bitcask store ty...
package core import "sync" type Set map[interface{}]bool func (h Set) Add(key interface{}) { h[key] = true } func (h Set) Delete(key interface{}) { if _, ok := h[key]; ok { delete (h, key) } } func (h Set) Exists(key interface{}) bool { _, ok := h[key] return ok } type AtomSet struct { set Set mutex...
package service import ( "context" "fmt" "sync/atomic" "github.com/go-ocf/cloud/grpc-gateway/pb" pbCQRS "github.com/go-ocf/cloud/resource-aggregate/pb" pbRA "github.com/go-ocf/cloud/resource-aggregate/pb" kitNetGrpc "github.com/go-ocf/kit/net/grpc" "github.com/gofrs/uuid" grpc_auth "github.com/grpc-ecosystem...
package solutions import ( "fmt" "testing" ) func TestSpiralOrder(t *testing.T) { t.Run("Test [[1,2,3],[4,5,6],[7,8,9]]", func(t *testing.T) { input := [][]int{ {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, } want := fmt.Sprint([]int{1, 2, 3, 6, 9, 8, 7, 4, 5}) r := fmt.Sprint(spiralOrder(input)) if want != ...
package message type ErrorMessage string type WalletMessage string type TransactionMessage string const ( DATABASE_ERROR = ErrorMessage("A database error has occured, please check system logs for more details") DB_ERROR_OCCURED = ErrorMessage("Database Error occurred : %v") ) const ( DEBIT_WALLET_DOES_NOT_EXIST...
package lib import ( "github.com/hailongz/kk-lib/dynamic" "github.com/hailongz/kk-logic/logic" ) type ContentLogic struct { logic.Logic } func (L *ContentLogic) Exec(ctx logic.IContext, app logic.IApp) error { L.Logic.Exec(ctx, app) contentType := dynamic.StringValue(L.Get(ctx, app, "contentType"), "") conte...
// Package gate provides primitive to limit number of concurrent goroutine // workers. Useful when sync.Locker or sync.WaitGroup is not enough. package gate import ( "runtime" "sync" ) // A Gate is a primitive intended to help in limiting concurrency in some // scenarios. Think of it as a close sync.WaitGroup analo...
package main import ( "fmt" "log" "time" ) func main() { log.Println(time.Now()) fmt.Println(time.Now()) log.Println(time.Now().Format(time.RFC3339)) fmt.Println(time.Now().Format(time.RFC3339)) } /* // Parse a time value from a string in the standard Unix format. t, err := time.Parse(time.UnixDate, "Sat Mar ...
package main import ( "math/rand" "github.com/goml/gobrain" ) type FizzBuzz []float64 func (f FizzBuzz) Type() int { for i, f := range f { if f > 0.4 { return i } } panic("Wrong") } func teacher(n int) []float64 { switch { case n%15 == 0: return []float64{1, 0, 0, 0} case n%3 == 0: return []flo...
package message // ConfigNotFound should be used if devspace.yaml cannot be found const ConfigNotFound = "Cannot find a devspace.yaml for this project. Please run `devspace init`" // ConfigNoImages should be used if devpsace.yaml does not contain any images const ConfigNoImages = "This project's devspace.yaml does no...
// Copyright 2016 The G3N Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package math32 // Box3 represents a 3D bounding box defined by two points: // the point with minimum coordinates and the point with maximum coordinates...
package client import ( "fmt" "log" "net/rpc" "github.com/samqintw/road2go/rpc/rpc_simple/contract" ) const port = 1234 type MyClient struct { *rpc.Client } func CreateClient() *MyClient { client, err := rpc.Dial("tcp", fmt.Sprintf("localhost:%v", port)) if err != nil { log.Fatal("dialing:", err) } ret...
package workload import ( "github.com/projecteru2/cli/cmd/utils" "github.com/projecteru2/core/strategy" "github.com/urfave/cli/v2" ) const ( workloadArgsUsage = "workloadID(s)" specFileURI = "<spec file uri>" copyArgsUsage = "workloadID:path1,path2,...,pathn" sendArgsUsage = "path1,path2,...path...
package admin type DashboardController struct { BaseController } func (c *DashboardController) Dashboard() { c.Layout = "admin/layout.tpl" c.LayoutSections = make(map[string]string) c.LayoutSections["LayoutSidebar"] = "admin/sidebar.tpl" c.LayoutSections["LayoutHeader"] = "admin/header.tpl" c.TplName = "admi...
package solutions import ( util "./util" ) func Length(ss []string) int { return util.LenWrapperU(ss) } // func NotUsed() { // }
package logengine_test import ( "context" "fmt" "testing" "time" "github.com/direktiv/direktiv/pkg/refactor/logengine" "github.com/google/uuid" "go.uber.org/zap" ) func Test_ChachedSQLLogStore(t *testing.T) { dbMock := make(chan logengine.LogEntry, 1) logger, logWorker, closeLogWorkers := logengine.NewCache...
package cos_test import ( "testing" "github.com/RitchieFlick/cos" ) type testHardCode struct{} func (t testHardCode) GetPhrases() ([]string, error) { var list []string list = append(list, "Remember: YAGNI (You Ain’t Gonna Need It)") list = append(list, "Remember: 3-2-1 Backup Strategy") return list, nil } fu...
package repo import ( "github.com/short-d/app-template/backend/app/entity" ) // ChangeLog accesses changelog from storage, such as database. type ChangeLog interface { GetChangeLog() ([]entity.Change, error) }
package v25 import ( "github.com/giantswarm/versionbundle" ) func VersionBundle() versionbundle.Bundle { return versionbundle.Bundle{ Changelogs: []versionbundle.Changelog{ { Component: "cloudconfig", Description: "Pin calico-kube-controllers to master.", Kind: versionbundle.KindChanged, ...
package decrypt import ( "fmt" "os/exec" "syscall" "emperror.dev/errors" log "github.com/sirupsen/logrus" ) func (h *Handler) StartProcess() (err error) { envv := make([]string, 0) binary, err := exec.LookPath(h.Args[0]) if err != nil { return errors.Wrapf(err, "LookPath %s", h.Args[0]) } for key, val :=...
package main import ( "math/rand" "net/http" "encoding/json" "time" "flag" "bytes" "log" ) func main() { idPtr := flag.Int("id", rand.Int(), "the id of this client") urlPtr := flag.String("url", "http://127.0.0.1:80/", "the url to send events to") seedPtr := flag.Int64("seed", t...
package trigger_service import ( "fmt" "ms/sun/shared/x" "ms/sun_old/base" ) type postTrig int func (postTrig) OnInsert(ins []int) { fmt.Println("OnInsert postTrig", ins) } func (postTrig) OnUpdate(ins []int) { fmt.Println("OnUpdate postTrig", ins) } func (postTrig) OnDelete(ins []int) { fmt.Println("OnDelet...
package server import ( "github.com/gin-gonic/contrib/secure" "github.com/gin-gonic/gin" "github.com/empirefox/esecend/admin" "github.com/empirefox/esecend/captchar" "github.com/empirefox/esecend/cdn" "github.com/empirefox/esecend/config" "github.com/empirefox/esecend/db-service" "github.com/empirefox/esecend...
package models import ( "database/sql/driver" "encoding/json" "strconv" "time" "github.com/lib/pq" "github.com/libp2p/go-libp2p-core/peer" "github.com/pkg/errors" ) type ( JobSpecV2 struct { ID int32 `gorm:"primary_key"` OffchainreportingOracleSpecID int32 OffchainreportingOr...
/* Package callmeback is a generic server-side "come again in ..." middleware for gRPC. In the case where a gRPC stream would be nice to provide but impossible to deploy (see [1]) this interceptor enables a pool-based unary call replacement for push-based streams. It adds a trailer duration value indicating to the cl...
package models import ( u "businessense/utils" "github.com/jinzhu/gorm" ) //IssuePainPointsMap Type type IssuePainPointsMap struct { gorm.Model Issue Issue IssueID int PainPoint PainPoint PainPointID int Relevance float64 } type IssueRelevance struct { IssueID int Name string Relevan...
// DO NOT EDIT. This file was generated by "github.com/frk/gosql". package testdata import ( "github.com/frk/gosql" ) func (q *InsertDefaultAllSliceQuery) Exec(c gosql.Conn) error { var queryString = `INSERT INTO "test_user_with_defaults" AS u ( "email" , "full_name" , "is_active" , "created_at" , "updat...
package frontend import "github.com/getaceres/payment-demo/payment" type Response interface { GetLinks() map[string]string } // PaymentResponse is the response of a REST operation which returns a single payment // swagger:model type PaymentResponse struct { Data payment.Payment `json:"data"` Links map[string]s...
package main import ( "log" "net/http" "os" "github.com/breathingdust/house.api/controllers" "github.com/breathingdust/house.api/db" "github.com/gorilla/mux" "github.com/rs/cors" ) func main() { r := mux.NewRouter().StrictSlash(true) var mgoConn = os.Getenv("MGOCONN") if mgoConn == "" { log.Fatal("No c...
package env import ( "fmt" "os" "strconv" "strings" "github.com/teejays/clog" ) type AppEnv int const ( DEV AppEnv = iota STG PROD TEST ) func (e AppEnv) String() string { switch e { case DEV: return "DEV" case STG: return "STG" case PROD: return "PROD" case TEST: return "TEST" default: r...
// 微信开放平台基类 package base import ( "github.com/MrCHI/gowechat/wxcontext" ) type OpenBase struct { *wxcontext.Context }
package main import ( "net/http" "fmt" "io" ) func d(w http.ResponseWriter,r *http.Request){ //(lne1) //this is the signature of handler interface w.Header().Set("Key","from me") w.Header().Set("Content-type","text/html ; charset=utf-8") io.WriteString(w,` <img src="/aman.jpg"> `) //calls this signa...
package main import ( "encoding/json" "flag" "fmt" "strconv" "github.com/dah8ra/ch4/github" ) var issue github.Issue var n = flag.Bool("n", false, "omit trailing newline") var read = flag.Bool("r", false, "read ticket") var create = flag.Bool("c", false, "create new ticket") var ticketTitle = flag.String("t", ...
package main import ( "fmt" "sync" ) func testBroadCast() { type Button struct { Clicked *sync.Cond } button := Button{Clicked: sync.NewCond(&sync.Mutex{})} subscribe := func(c *sync.Cond, fn func()) { var goroutineRunning sync.WaitGroup goroutineRunning.Add(1) go func() { goroutineRunning.Done() ...
package dushengchen /* Submission: https://leetcode.com/submissions/detail/482442786/ */ func LargestRectangleArea(heights []int) int { return largestRectangleArea(heights) } func largestRectangleArea(heights []int) int { //dp_righ[i]存放i点的右边+1位置 dp_righ := make([]int, len(heights)) //dp_left[i]存放i点的左边-1位置 dp_l...
package framework func NoArgs(cmd *Command, args []string) bool { return len(args) == 0 } func RequiresMinArgs(min int) PositionalArgs { return func(_ *Command, args []string) bool { return len(args) >= min } } func RequiresMaxArgs(max int) PositionalArgs { return func(_ *Command, args []string) bool { retur...
/* Inspired by this SO question As input you will be given a non-empty list of integers, where the first value is guaranteed to be non-zero. To construct the output, walk from the start of the list, outputting each non-zero value along the way. When you encounter a zero, instead repeat the value you most recently add...
package httpclientinterception import ( "net/http" ) type interceptionOptions struct { interceptorBuilder *interceptionBuilder builders []*configurationBuilder PanicOnMissingRegistration OnMissingRegistration } // NewInterceptorOptions creates a new interceptionOptions object used to configure your in...
package mysql import ( "database/sql" "flag" "strings" . "../../base" "../../store" _ "github.com/go-sql-driver/mysql" ) var mysql string func init() { flag.StringVar(&mysql, "mysql", "root@/stock", "mysql uri") store.Register("mysql", &Mysql{}) } func (p *Mysql) Open() (err error) { if p.db != nil { p....
package functions import ( "fmt" "regexp" "strings" igrpc "github.com/direktiv/direktiv/pkg/functions/grpc" corev1 "k8s.io/api/core/v1" "knative.dev/pkg/apis" v1 "knative.dev/serving/pkg/apis/serving/v1" ) const ( regex = "^[a-z]([-a-z0-9]{0,62}[a-z0-9])?$" ) func validateLabel(name string) error { matched...
package hands import ( "fmt" "image" "image/color" "image/color/palette" "image/gif" "os" ) const ( w = 480 h = 84 ) // Data 手数 type Data struct { img *image.Paletted } // CreateData ... func CreateData() *Data { return &Data{img: image.NewPaletted(image.Rect(0, 0, w, h), palette.Plan9)} } // MakeData 价格...
package gorm import ( "errors" "fmt" "sync" "time" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" _ "github.com/jinzhu/gorm/dialects/postgres" "github.com/sunmi-OS/gocore/viper" ) var Gorm sync.Map var defaultName = "dbDefault" var ( // ErrRecordNotFound record not found error, happens ...
// 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 models import ( "dappapi/global/orm" "dappapi/tools" "strings" "golang.org/x/crypto/bcrypt" ) type UserName struct { Username string `gorm:"type:varchar(64)" json:"username" form:"username"` } type PassWord struct { // 密码 Password string `gorm:"type:varchar(128)" json:"password" form:"password"` } t...
package server import ( "encoding/json" "fmt" "github.com/golang/glog" "net/http" "sync" ) type BaseJsonData struct { Message string `json:"message,omitempty"` Code int `json:"code"` Success bool `json:"success"` Data interface{} `json:"data,omitempty"` } type ResponseData struct { Succ...
package hex type HexCode struct { Code [][]int Interval int }
package main import ( "runtime" "time" ) // what you will see, Hello and world will print in a random order depending on which thread is asleep // and how long it takes to print the line out... this is an example of concurrancy and parallelism func main() { godur, _ := time.ParseDuration("10ms") // we are telli...
package main import ( "fmt" "runtime" "time" ) func main() { //1.传统方法 st := time.Now() getSuShu01(72) elapsed := time.Since(st) fmt.Println("传统函数执行完成耗时:", elapsed) //2.运用goroutine后 fmt.Println(runtime.NumCPU(), "核cpu") st2 := time.Now() getSuShu02(72) elapsed2 := time.Since(st2) fmt.Println("传统函数执行完成耗时...
package evaluator import ( "context" "fmt" "net/http" "os" envoy_config_cluster_v3 "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3" "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/rego" "github.com/open-policy-agent/opa/types" "github.com/pomerium/pomerium/authorize/...
package app import ( "io" "log" "net/http" "strconv" "github.com/Maxgis/ToyBrick/conf" ) var mux map[string]func(http.ResponseWriter, *http.Request) func init() { if conf.Globals.IsOpenAdmin { if conf.Globals.AdminPort == 0 { return } server := http.Server{ Addr: ":" + strconv.Itoa(conf.Globals...
package handler import ( "net/http" "github.com/nektro/mantle/pkg/db" "github.com/nektro/mantle/pkg/ws" "github.com/gorilla/mux" ) // InvitesMe reads info about channel func InvitesMe(w http.ResponseWriter, r *http.Request) { _, user, err := apiBootstrapRequireLogin(r, w, http.MethodGet, true) if err != nil {...
package main func main() { // if err := web.FindLinksInHtmlFile("pkg/web/golang.org.html"); err != nil { // fmt.Printf("FindLinksInHtmlFile failed caused by: %v", err) // os.Exit(1) // } // counter, err := web.CountElementsInHtmlFile("pkg/web/golang.org.html") // if err != nil { // fmt.Printf("FindLinksInH...
package main import ( "fmt" "github.com/uniqss/gomsglist" "strings" ) const TEST_PRODUCER_CONSUMER_COUNT = 10000 const TEST_MSG_COUNT_PER_PRODUCER = 100000 var producerDone [TEST_PRODUCER_CONSUMER_COUNT]bool var producerDoneAll = false var consumedmsgs [TEST_PRODUCER_CONSUMER_COUNT][TEST_MSG_COUNT_PER_PRODUCER]bo...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-11-19 19:54 # @File : lt_1423_Maximum_Points_You_Can_Obtain_from_Cards.go # @Description : # @Attention : */ package slide_window import ( "fmt" "testing" ) func Test_maxScore(t *testing.T) { scors := []int{1, 2, 3, 4, 5, 6, 1} max := 3 score := maxScor...
package main import ( "container/heap" "fmt" "sort" ) func main() { fmt.Println(findKthLargest([]int{ 3, 2, 1, 5, 6, 4, }, 2)) fmt.Println(findKthLargest([]int{ 3, 2, 3, 1, 2, 4, 5, 5, 6, }, 4)) } type kheap struct { sort.IntSlice } func (h *kheap) Push(x interface{}) { h.IntSlice = append(h.IntSlice...
/* * @Author: Matt Meng * @Date: 1970-01-01 08:00:00 * @LastEditors: Matt Meng * @LastEditTime: 2020-10-11 11:58:42 * @Description: file content */ package jwt import ( "net/http" "time" "github.com/gin-gonic/gin" "gin-blog/pkg/e" "gin-blog/pkg/util" ) func JWT() gin.HandlerFunc { return func(c *gin.Con...
package main import ( "fmt" "Goforit/015/DogPack" ) func main() { dog := DogPack.New("aaaa") fmt.Println(dog) // p := DogPack.GetNameStr(dog) p := DogPack.GetNameStrA(&dog) fmt.Println(p) *p = "bbbb" fmt.Println(dog) }
package user import ( "testing" "github.com/btnguyen2k/prom" ) type TestSetupOrTeardownFunc func(t *testing.T, testName string) func setupTest(t *testing.T, testName string, extraSetupFunc, extraTeardownFunc TestSetupOrTeardownFunc) func(t *testing.T) { if extraSetupFunc != nil { extraSetupFunc(t, testName) }...
package main import ( "fmt" "math/rand" "time" ) /* rand.Intn(3) [0,3) 左闭右开区间 */ func main() { //fmt.Println(rand.Int()) //rand.Int() // //fmt.Println(rand.Float64()) //rand.Float64() //fmt.Println(rand.Float32()) rand.Seed(time.Now().UnixNano()) for i := 0; i < 100; i++ { fmt.Print(rand.Intn(3),...
// Copyright 2019-present 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 agr...
package cbor import ( "testing" "github.com/polydawn/refmt/tok/fixtures" ) func testBool(t *testing.T) { t.Run("bool true", func(t *testing.T) { seq := fixtures.SequenceMap["true"] canon := b(0xf5) t.Run("encode canonical", func(t *testing.T) { checkEncoding(t, seq, canon, nil) }) t.Run("decode canon...
package main import ( "flag" "fmt" "math/rand" "time" "github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb/opt" ) var ( fPath = flag.String("p", "/tmp/leveldb", "") fSize = flag.Int("s", 200, "") fSizeRange = flag.Int("size-range", 10, "") fLength = flag.Int("l", ...
package main import ( "fmt" "math/rand" "sync" "time" ) func main() { fmt.Println("This is main") ch := make(chan string, 5) go func() { crawl(ch) close(ch) }() analyze(ch) } func crawl(ch chan string) { workers := 10 wg := sync.WaitGroup{} for i := 0; i < workers; i++ { wg.Add(1) go func(i int) ...
package schema import ( "net/url" "time" ) // Server represents the configuration of the http server. type Server struct { Address *AddressTCP `koanf:"address" json:"address" jsonschema:"default=tcp://:9091/,title=Address" jsonschema_description:"The address to listen on"` AssetPath string ...
package crontab import ( "log" "time" "tpay_backend/model" "tpay_backend/payapi/internal/svc" "tpay_backend/utils" ) // 平台收款卡今日已收清零 type PlatformCardReceivedClear struct { CronBase serverCtx *svc.ServiceContext } func NewPlatformCardReceivedClearTask(serverCtx *svc.ServiceContext) *PlatformCardReceivedClear ...
package oauth2 import "context" // authorization request struct type AuthorizationRequest struct { // The grant type identifier GrantType GrantType // The client identifier Client ClientEntityInterface // the User identifier User UserEntityInterface // An array of scope identifiers Scopes []ScopeEntityInterfa...
package repository import ( "context" "errors" "map-friend/src/domain/user" ) func NewIUserRepository() user.IUserRepository { // mock users := map[uint]*user.User{ 1: &user.User{ ID: 1, Name: "ryomak", }, 2: &user.User{ ID: 2, Name: "test user", }, 3: &user.User{ ID: 3, Name: ...
package syntax import ( "testing" "os" "path" ) func TestStreamWriter(t *testing.T) { pdir := "../../logs" filename := "test.txt" p := path.Join(pdir, filename) err := os.MkdirAll(pdir, os.ModePerm) if err != nil { t.Error(err) return } f, err := os.Create(p) if err != nil { t.Error(err) return ...
// +build linux package sysdnotify import ( "net" "os" ) func init() { if notifySocketName := os.Getenv("NOTIFY_SOCKET"); notifySocketName != "" { socket = &net.UnixAddr{ Name: notifySocketName, Net: "unixgram", } } }
/* * @lc app=leetcode.cn id=51 lang=golang * * [51] N 皇后 */ // @lc code=start package main import "fmt" func main() { n := 4 allResult := solveNQueens(n) for i := 0 ; i < len(allResult) ; i++ { for j := 0 ; j < n ; j++ { fmt.Println(allResult[i][j]) } fmt.Println() } } func solveNQueens(n int) [][]...
package main import "fmt" func main() { // 创建管道 ch := make(chan int, 10) // 循环写入值 for i := 0; i < 10; i++ { ch <- i } // 关闭管道 close(ch) // for range循环遍历管道的值(管道没有key) for value := range ch { fmt.Println(value) } // 通过上述的操作,能够打印值,但是出出现一个deadlock的死锁错误,也就说我们需要关闭管道 for i := 0; i < 10; i++ { fmt.Printl...
package core import ( "net/http" "github.com/gin-gonic/gin" ) // addCafes godoc // @Summary Register with a Cafe // @Description Registers with a cafe and saves an expiring service session token. An access // @Description token is required to register, and should be obtained separately from the target // @Descript...
package builder type BuildProcess interface { SetWeels() BuildProcess SetSeats() BuildProcess SetStructure() BuildProcess GetVehicle() VehicleProduct } // Director type ManufacturingDirector struct { builder BuildProcess } func (f *ManufacturingDirector) Construct() { f.builder.SetStructure().SetWeels().SetSe...
package middleware import ( "time" "github.com/valyala/fasthttp" "golang.org/x/time/rate" "github.com/any-lyu/go.library/errors" ) // RateHandler 限流 // bursts of at most b tokens. func RateHandler(h fasthttp.RequestHandler, b int) fasthttp.RequestHandler { return func(ctx *fasthttp.RequestCtx) { limiter := r...
package aoc2019 import ( "fmt" "strconv" aoc "github.com/janreggie/aoc/internal" ) type spaceImage [6][25]int8 // 6 tall, 25 wide func newSpaceImage(raw string) (sp spaceImage, err error) { if len(raw) != 150 { err = fmt.Errorf("raw is length %v, should be 150", len(raw)) return } for ii := 0; ii < 6; ii+...
package main import ( "bytes" "fmt" "io/ioutil" "os" "regexp" ) func main() { byts, err := ioutil.ReadFile("D:\\workspace\\go\\learnGo\\itcast\\src\\01_20H\\day05_异常_文本文件处理\\html\\day21.html") if err != nil { fmt.Print(err) } str := bytes.NewBuffer(byts).String() reg := regexp.MustCompile("<p>(.*)</p>") ...
package main import ( "github.com/aws/aws-lambda-go/lambda" "bartenderAsFunction/model" "bartenderAsFunction/dao" "fmt" ) var DataConnectionManager dao.CommandConnectionInterface func Handler(iotRequest model.CommandRequest) error { // TODO 1. generate id to the command (uuid) see github.com/satori/go.uuid uid...
package app import ( "sync" "github.com/anihouse/bot/config" "github.com/anihouse/bot" "github.com/bwmarrin/discordgo" ) type ( HandlerFunc func(*Context) HandlerChain []HandlerFunc ) type Application struct { middleware modules map[string]*Module } func (chain *HandlerChain) append(handlers ...Handler...
package main import ( "net/http" "net/http/httptest" "testing" ) func TestHello(t *testing.T) { // Create a new request with a GET method and an empty body req, err := http.NewRequest("GET", "/hello", nil) if err != nil { t.Fatal(err) } // Create a new response recorder rr := httptest.NewRecorder() // C...
package tests import ( "context" "encoding/json" "log" "math/big" "strings" "testing" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" "github.com/langzhenjun/go-ethereum-tutorials/contracts" "github.com/langzhenjun/go-...
package termcolor import ( "runtime" ) type Color string const ( // https://github.com/git/git/blob/master/color.h NORMAL = Color("") RESET = Color("\033[m") BOLD = Color("\033[1m") RED = Color("\033[31m") GREEN = Color("\033[32m") YELLOW = Color("\033[33m") BLUE ...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //434. Number of Segments in a String //Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space c...
package acs import ( "crypto/aes" "crypto/cipher" "crypto/rand" "io" "sync" ) // A Writer is an io.WriteCloser. Writes to a Writer are encrypted (AES-CBC) and written to w. type Writer struct { closed bool beginning bool mu sync.Mutex w io.Writer iv []byte block cipher.Block m...
package main import "fmt" func main() { fmt.Println(rob([]int{1, 2, 3, 1})) fmt.Println(rob([]int{2, 7, 9, 3, 1})) } func rob(nums []int) int { switch len(nums) { case 0: return 0 case 1: return nums[0] } _rob := func(nums []int) int { dp := make([]int, len(nums)) // 在第 i 间屋子能获得最大的收益 //1,2,3,1 ...
package main import ( "encoding/json" "flag" "log" "github.com/nats-io/nats" ) type product struct { Name string `json:"name"` SKU string `json:"sku"` } var natsClient *nats.Conn var natsServer = flag.String("nats", "", "NATS server URI") func init() { flag.Parse() } func main() { var err error natsCl...
// Copyright 2020-present Kuei-chun Chen. All rights reserved. package keyhole import "fmt" // CompareClusters compares two clusters, source and target func CompareClusters(cfg *Config) error { if cfg.IsDeepCompare { var err error var comp *Comparator if comp, err = NewComparator(cfg.SourceURI, cfg.TargetURI)...
package main import "fmt" /** 函数示例 */ //闭包1 返回一个函数 func getSeq() func() int { i := 0 return func() int { i++ return i } } //闭包2 带参数 func addFUnc(x1 int, x2 int) func(x3 int, x4 int) (int, int, int) { i := 0 return func(x3 int, x4 int) (int, int, int) { i++ return i, x1 + x2, x3 + x4 } } //结构体类型 圆 ty...
package middlewares import ( "github.com/astaxie/beego" ) func GetBalance(address string) ([]byte, error){ url := beego.AppConfig.String("BasecoinUrl")+"/query/account/balance?address="+address return SendRequest(url) } func FindRelateAccount(address string) ([]byte, error){ url := beego.AppConfig.String("Baseco...
package main import ( "bytes" "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "strings" "golang.org/x/oauth2" "golang.org/x/net/context" ) const ( TOKEN_URL = "https://api.%s.onelogin.com/auth/oauth2/v2/token" AUTH_URL = "https://api.%s.onelogin.com/auth/oauth2/auth" BASE_PATH = "https://api.%s.one...
package server import ( "fmt" . "server/data/datatype" "server/libs/log" "server/libs/rpc" ) var ( vt ViewportCodec ) type ViewportCodec interface { GetCodecInfo() string ViewportCreate(id int32, container Entity) interface{} ViewportDelete(id int32) interface{} ViewportNotifyAdd(id int32, index int32, obje...
package GoMybatisV2 import ( "context" "database/sql" "github.com/agui2200/GoMybatisV2/logger" "github.com/agui2200/GoMybatisV2/sessions" "github.com/agui2200/GoMybatisV2/sqlbuilder" "github.com/agui2200/GoMybatisV2/templete" "github.com/agui2200/GoMybatisV2/templete/ast" "github.com/agui2200/GoMybatisV2/templ...
package main import ( "context" "os" "github.com/andersfylling/disgord" "github.com/andersfylling/disgord/std" ) // replyPongToPing is a handler that replies pong to ping messages func replyPongToPing(s disgord.Session, data *disgord.MessageCreate) { msg := data.Message // whenever the message written is "pin...
package database import ( "errors" "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" "github.com/ubclaunchpad/pinpoint/protobuf/models" ) // AddNewPeriod creates a new period item in the club table func (db *Databas...
package virtualoutbound_test import ( "testing" . "github.com/onsi/ginkgo" "github.com/kumahq/kuma/pkg/test" "github.com/kumahq/kuma/test/e2e/virtualoutbound" "github.com/kumahq/kuma/test/framework" ) func TestE2ERetry(t *testing.T) { if framework.IsK8sClustersStarted() { test.RunSpecs(t, "E2E VirtualOutbou...
package handler import ( "context" "errors" "fmt" "time" "github.com/golang/protobuf/ptypes" "github.com/jinmukeji/go-pkg/v2/age" "github.com/jinmukeji/jiujiantang-services/pkg/rpc" "github.com/jinmukeji/jiujiantang-services/service/auth" "github.com/jinmukeji/jiujiantang-services/service/mysqldb" corepb "...
package main type callback func(params ...string) (interface{}, error)
package test import ( "testing" ) func TestAssertEqual(t *testing.T) { AssertEqual(t, true, true) AssertEqual(t, true, 1 == 1) AssertEqual(t, 2, 3-1) AssertEqual(t, 0, 0) AssertEqual(t, int(0), int64(0)) AssertEqual(t, "hello", "h"+"ello") }