text
stringlengths
11
4.05M
package clitable import "strings" var mapFields = []string{"Key", "Value"} // PrintHorizontal - Prints horizontal table from a map. func PrintHorizontal(m map[string]interface{}) { // Create new table with table := New(mapFields) // Convert map to rows list rows := mapToRows(m) // Add rows to table for _, row ...
package test import ( "fmt" "gengine/builder" "gengine/context" "gengine/engine" "testing" "time" ) type User struct { Name string Age int64 Male bool } func (u *User) GetNum(i int64) int64 { return i } func (u *User) Print(s string) { fmt.Println(s) } func (u *User) Say() { fmt.Println("hello world")...
package main import ( "log" "sync" "time" "github.com/aler9/gomavlib" ) type errorHandler struct { printSingleErrors bool errorCount int errorCountMutex sync.Mutex } func newErrorHandler(printSingleErrors bool) (*errorHandler, error) { eh := &errorHandler{ printSingleErrors: printSingleErrors, }...
package spec // GetDefaultIDAttr returns the default ID attribute for events func GetDefaultIDAttr() Attr { format := "uuid" auto := true minLength := 1 return Attr{ Type: "string", Format: &format, Auto: &auto, MinLength: &minLength, } } var defaultIDAttr = GetDefaultIDAttr() // GetDefault...
package main import ( hue "GoHue" "fmt" "io/ioutil" "os" "strconv" "strings" "github.com/BurntSushi/toml" ) var ( configFile = strings.Join([]string{os.Getenv("HOME"), "/.config/huecli"}, "") colorList = map[string][2]float32{ "DEFAULT": [2]float32{0.4571, 0.4097}, "RED": [2]float32{0.6915, 0.3083}...
package main import ( "flag" "fmt" "image/color" "image/gif" "log" "os" "github.com/martinkirsche/wired-logic/simulation" ) func main() { var startFrame int var frameCount int flag.IntVar(&startFrame, "start", 0, "frame at wich the animation should start") flag.IntVar(&frameCount, "count", 0, "amount of ...
package main import ( "fmt" "time" ) func main() { c := make(chan int, 10) go func() { time.Sleep(2 * 1e9) x := <-c fmt.Println("received", x) }() fmt.Println("sending", 10) c <- 10 fmt.Println("sent", 10) } // Output: // sending 10 // sent 10 // prints immediately // no further output, because mai...
package tasks import ( "bytes" "fmt" "net" "net/http" "os" "time" "github.com/robfig/cron" "github.com/rogierlommers/slack-server/internal/props" "github.com/rogierlommers/slack-server/internal/slack" log "gopkg.in/inconshreveable/log15.v2" ) // ScheduleCronjobs starts the scheduler func ScheduleCronjobs()...
package api import ( "encoding/json" "fmt" "github.com/jmcvetta/neoism" "net/url" "time" ) type Album struct { Name string Year string Submitted int32 } // AlbumSelect represents the data passed up to select // an album from the database type AlbumSelect struct { Name string Year string Arti...
package main import ( "fmt" "math/rand" ) func main() { switch speed := rand.Intn(15) + 16; speed { case 16: fmt.Printf("Slow going at %v km/s\n", speed) case 28, 29, 30: fmt.Printf("Quickly now at %v km/s\n", speed) default: fmt.Println(speed, "km/s") } }
package main import "github.com/estudo/cmd" func main() { cmd.Start() }
package apis import ( "github.com/egnis/server/router/apis/handlers" "github.com/labstack/echo" ) func BindSubscribeGroup(e *echo.Group, dbHandler *handlers.DBHandler) { e.POST("/remove-subs", dbHandler.DeleteSubs) e.GET("/all", dbHandler.FindAllSubs) } // 아래의 함수는 cafe24에서 요청하는 함수로써, // jwt검사를 하지 않을 뿐더러, 이해하기 쉽게...
package criteria import ( "testing" "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" "github.com/pomerium/pomerium/pkg/grpc/session" "github.com/pomerium/pomerium/pkg/grpc/user" ) func TestEmails(t *testing.T) { t.Run("no session", func(t *testing.T) { res, err := evaluate(t, ` allow...
package types // species - a partial spieces from stapi type Species struct { Uid string `json:"uid"` Name string `json:"name"` }
package xgrpc import ( "google.golang.org/grpc" health "google.golang.org/grpc/health" healthv1 "google.golang.org/grpc/health/grpc_health_v1" ) func RegisterHealthServer(grpcServer *grpc.Server) { healthv1.RegisterHealthServer(grpcServer, health.NewServer()) } // ------------------------------------------------...
package cmd import ( "bytes" "crypto/tls" "fmt" "net/http" "os" "path/filepath" "strings" "github.com/direktiv/direktiv/pkg/project" "github.com/gobwas/glob" "github.com/r3labs/sse" "github.com/spf13/cobra" "github.com/spf13/viper" "gopkg.in/yaml.v3" ) const ( DefaultProfileConfigName = ".direktiv.prof...
package main import ( batch "batchProcess" "encoding/json" "log" ) func batchResponse(batch *batch.BatchSpectra) []byte { var errStart []byte = []byte("{\"Error\":") var dataStart []byte = []byte("{\"Data\":") var end []byte = []byte("}") var resp []byte if batch.Error != nil { log.Println("BATCH PROCESSING...
/* * EVE Swagger Interface * * An OpenAPI for EVE Online * * OpenAPI spec version: 0.4.1.dev1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ package swagger // link object type GetCharactersCharacterIdPlanetsPlanetIdLink struct { // destination_pin_id integer DestinationPinId int...
package main import "fmt" //写一个递归吧 //给一个数字 计算这个数字的递归值 func main() { num := 5 s := recursion(num) fmt.Printf("num的阶乘为:%d", s) } //传入的是a是什么类型的,返回的是什么类型的 func recursion(a int) int { if a <= 0 { return 0 } else if a == 1 { return 1 } else { return a * recursion(a-1) } } //另一种写法 func Factorial(n uint64) (re...
package dushengchen /* Submission: https://leetcode.com/submissions/detail/369624404/ */ func tribonacci(n int) int { if n <= 0 { return 0 } else if n <= 2 { return 1 } n0 := 0 n1 := 1 n2 := 1 for i := 3; i < n; i++ { n2, n1, n0 = n1+n2+n0, n2, n1 } return n2 + n1 + n0 }
package binance import ( "context" bin "github.com/adshao/go-binance" "github.com/google/uuid" "github.com/mhereman/cryptotrader/logger" "github.com/mhereman/cryptotrader/types" ) // CancelOrder executes the cancel order request func (b Binance) CancelOrder(ctx context.Context, order types.Order, newUUID uuid.U...
package davepdf type PdfFont struct { id int family string } func (pdf *Pdf) newFont() *PdfFont { font := &PdfFont{} pdf.newObjId() font.id = pdf.n pdf.fonts = append(pdf.fonts, font) return font } func (pdf *Pdf) SetFontFamily(fontFamily string) { validFonts := []string{ "Times-Roman", "Times-Bol...
package stack import ( "errors" "fmt" ) type SliceStack struct { Slice []int stackSize int } //判断栈是否为空 func (p *SliceStack) IsEmpty() bool{ return p.stackSize == 0 } //获取栈的大小 func (p *SliceStack) Size() int{ return p.stackSize } //获取栈顶元素 func (p *SliceStack) Top() int{ if p.IsEmpty() { panic(errors.N...
// Copyright 2019 The Dice Authors. 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by app...
package controllers import ( "github.com/gin-gonic/gin" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" ) var ( //HTTPReqDuration metric:http_request_duration_seconds HTTPReqDuration *prometheus.HistogramVec //HTTPReqTotal metric:http_request_total HTT...
package main import ( "fmt" "math/big" "strconv" ) func sumFactorialDigits(n int) int { var sum int z := big.NewInt(1) for i := 2; i <= n; i++ { z.Mul(z, big.NewInt(int64(i))) } for _, v := range z.String() { v, _ := strconv.Atoi(string(v)) sum += v } return sum } func main() { fmt.Println(sumFactor...
package lambdainvoker // LambdaInvoker will expose and API to invoke Lambda using the official go-aws-sdk type LambdaInvoker interface { InvokeLambda(interface{}) (interface{}, error) } // BaseAWSConfig will hold the values that are generally required by all things for AWS type BaseAWSConfig struct { AWSRegion s...
package main import ( "crypto/tls" "fmt" "net/smtp" "time" ) func SendMail(timeout time.Duration, addr string, from string, to string, msg []byte) error { response := make(chan error, 1) var conn *smtp.Client var err error go func() { conn, err = smtp.Dial(addr) if err != nil { response <- err retu...
package tsrv import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00600101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:tsrv.006.001.01 Document"` Message *UndertakingAmendmentAdviceV01 `xml:"UdrtkgAmdmntAdvc"` } func (d *Document...
package endpoints import ( "encoding/json" "fmt" "net/http" "strconv" cor "github.com/ebikode/eLearning-core/domain/course" usr "github.com/ebikode/eLearning-core/domain/user" md "github.com/ebikode/eLearning-core/model" tr "github.com/ebikode/eLearning-core/translation" ut "github.com/ebikode/eLearning-core...
// Exercise 05_cron guides you through designing a cron-like workflow that triggers logic on each interval. // Note that this is a long running workflow, so it uses the Restart feature. package main import ( "context" "time" "github.com/corverroos/replay/typedreplay" "github.com/luno/fate" "github.com/luno/jetti...
package main import ( "NtBot/uiMngr" "github.com/asticode/go-astilectron" bootstrap "github.com/asticode/go-astilectron-bootstrap" "github.com/pkg/errors" "log" ) var ( AppName string ) func main() { uiMngr.Init() if err := bootstrap.Run(bootstrap.Options{ Asset: Asset, AssetDir: AssetDir, Astilectr...
//go:generate gorunpkg github.com/99designs/gqlgen package api import ( "context" "errors" "github.com/gremlinsapps/avocado_server/api/graph" "github.com/gremlinsapps/avocado_server/api/model" "github.com/gremlinsapps/avocado_server/dal/sql" "github.com/gremlinsapps/avocado_server/helpers" ) type Resolver stru...
package termd import ( "fmt" "github.com/alecthomas/chroma" "github.com/aybabtme/rgbterm" "github.com/tj/go-css/csshex" ) // Style is the configuration used to style a particular token. type Style struct { Color string `json:"color"` Background string `json:"background"` Bold bool `json:"bold"` ...
package main import ( "context" "errors" "flag" "log" "net" "os" "sort" "strconv" "strings" "time" "github.com/jackc/pgx/v4" uuid "github.com/nu7hatch/gouuid" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/google/gopacket/pcap" ) var ifaceName string var debug bool var ...
package main import ( "bytes" "html/template" "io/ioutil" "net/http" "net/http/httptest" "net/url" "testing" entity "github.com/Surafeljava/Court-Case-Management-System/Entity" "github.com/Surafeljava/Court-Case-Management-System/caseUse/repository" "github.com/Surafeljava/Court-Case-Management-System/caseU...
package server import ( "context" "io" "log" "strings" "time" data "github.com/chutommy/crypto-currencies/data" crypto "github.com/chutommy/crypto-currencies/protos/crypto" "github.com/google/uuid" "github.com/pkg/errors" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) // Crypto is a serv...
/** * origin from github.com/lib/pq array * 并非原创 */ package sqly import ( "bytes" "database/sql" "database/sql/driver" "encoding/hex" "fmt" "reflect" "strconv" "strings" "time" ) // parseArray extracts the dimensions and elements of an array represented in // text format. Only representations emitted by th...
package cmd import ( "fmt" "os" "os/signal" "syscall" "github.com/spf13/cobra" "github.com/ubclaunchpad/pinpoint/gateway/api" "github.com/ubclaunchpad/pinpoint/libcmd" ) func (g *GatewayCommand) getRunCommand() *cobra.Command { run := &cobra.Command{ Use: "run", Short: "Spin up service", Long: ``, ...
package main import ( "log" "net/http" "github.com/gorilla/websocket" ) var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, CheckOrigin: func(r *http.Request) bool { return true }, } func handler(w http.ResponseWriter, r *http.Request) { log.Println("upgrading connection") c...
package main import "fmt" func main() { nums := []int{0,1,2,3,4} newNums := nums[:2] newNums[1] = 100 fmt.Printf("%v\n", nums[:2]) fmt.Printf("%v\n", nums[0:]) fmt.Printf("%v\n", nums) }
// Implement encryption/decrytion of Chef encrypted data bag V1 // Super thanks to https://github.com/dgryski/dkeyczar for showing me how to use Go's crypto functions. package lib import ( "crypto/aes" "crypto/cipher" "crypto/sha256" "encoding/json" "fmt" "io/ioutil" "path/filepath" ) const ( dataBagCipherAl...
package bigmux import ( "log" "net" "time" ) const ( maxIPCacheTime = time.Minute ) // NextBackend returns the next backend according to the load balancing strategy func (z *Frontend) NextBackend() *Backend { return z.strategy.NextBackend() } // GetAddress returns the cached ip address of the backend host func...
package images import ( "context" "fmt" "io" "log" "github.com/dollarshaveclub/acyl/pkg/eventlogger" "github.com/dollarshaveclub/acyl/pkg/metrics" "github.com/dollarshaveclub/acyl/pkg/persistence" furan "github.com/dollarshaveclub/furan/rpcclient" "github.com/pkg/errors" ) type FuranBuilderBackend struct { ...
package routes import ( "github.com/gofiber/fiber/v2" "github.com/solrac97gr/cryptoAPI/models" "github.com/solrac97gr/cryptoAPI/services" ) // DecryptTextMessage : Decrypt the information send it throw the api func DecryptTextMessage(c *fiber.Ctx) error { ID := c.Params("id") encryptedMessage := new(models.Retur...
package main import ( "bufio" "fmt" "io/ioutil" "os" ) func main() { writeByUtil() } // 通过openFile 写文件 func writeByOS() { file, err := os.OpenFile("./xx.txt", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) if err != nil { return } defer func() { err := file.Close() if err != nil { fmt.Printf("关闭文件出错:...
package upload import ( "encoding/json" "fmt" "net/http" "nighthawklogger/config" ) const ( job_query = ` SELECT Timestamp, Loglevel, Worker, Body FROM logs WHERE Loglevel = "JOB" ORDER BY DATETIME(Timestamp) Desc ` ) func ListCompletedJobs(w http.ResponseWriter, r *http.Request) { r.Header.Set("Content-Ty...
/* Copyright (c) 2017-2018 Simon Schmidt Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribu...
package main import "fmt" func main() { fmt.Println(minDistance("horse", "ros")) fmt.Println(minDistance("intention", "execution")) } func minDistance(word1 string, word2 string) int { m := len(word1) n := len(word2) dp := make([][]int, m+1) for i := range dp { dp[i] = make([]int, n+1) dp[i][0] = i // 如果前...
package goauth import ( "encoding/json" "net/http" ) // ErrorHandler is a function that accepts a http.ResponseWriter and Error. type ErrorHandler func(w http.ResponseWriter, s int, e error) var ( // DefaultErrorHandler can be overriden in order to implement a custom error handler. DefaultErrorHandler ErrorHandl...
package main import "testing" func Test_Main(t *testing.T) { t.SkipNow() }
package heap var heap = make([]int, 1) func Insert(heap []int, key int) []int { heap = append(heap, key) i := len(heap) - 1 for i > 1 && heap[i] > heap[i/2] { heap[i], heap[i/2] = heap[i/2], heap[i] i /= 2 } return heap[1:] } func Delete(heap []int) (int, []int) { var parent, child int Max, t := heap[1], ...
package mysql import ( "database/sql" "time" "github.com/Tanibox/tania-core/src/assets/query" "github.com/Tanibox/tania-core/src/assets/storage" "github.com/gofrs/uuid" ) type FarmReadQueryMysql struct { DB *sql.DB } func NewFarmReadQueryMysql(db *sql.DB) query.FarmReadQuery { return FarmReadQueryMysql{DB: d...
package str import ( "strconv" "strings" ) func AnyOf(v string, any ...string) bool { for _, s := range any { if v == s { return true } } return false } func Or(a, b string) string { if a == "" { return b } return a } // HasSuffixes tests that string s has any of suffixes. func HasSuffixes(s stri...
package coap import ( //"errors" "net" "time" //"fmt" ) // SendMessageTo sends a CoAP Message to UDP address func SendMessageTo(msg *Message, conn Connection, addr *net.UDPAddr) (CoapResponse, error) { //fmt.Println("SendMessageTo: ", msg.MessageType, msg.MessageID) if conn == nil { return nil, ErrNilConn } ...
package trending import ( "errors" "fmt" "strconv" "strings" "github.com/PuerkitoBio/goquery" ) const ( TrendingEndpoint = "https://github.com/trending/" MainEndpoint = "https://github.com/" Today = "daily" Week = "weekly" Month = "monthly" ) type Trending struct { Repos []Repo // Trending repos l...
package commands import ( "errors" "fmt" "net" "code.cloudfoundry.org/garden" ) type NetOut struct { Protocol string `short:"p" required:"true" long:"protocol" choice:"tcp" choice:"udp" description:"protocol to whitelist, only supports tcp or udp"` StartIP IPFlag `long:"ip-start" required:"true" description...
// Copyright 2017 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 main import ( "database/sql" "encoding/json" "fmt" "log" "net/http" "os" "strconv" "time" _ "github.com/go-sql-driver/mysql" ) type JsonTime time.Time func (t JsonTime) MarshalJSON() ([]byte, error) { location, err := time.LoadLocation("Asia/Tokyo") if err != nil { log.Fatal(err) } return []b...
package main import ( "fmt" consumer2 "github.com/team-bonitto/bonitto/internal/queue/consumer" recorder2 "github.com/team-bonitto/bonitto/internal/recorder" "os" "strconv" "time" ) func main() { addr := os.Getenv("REDIS_URL") interval, _ := strconv.Atoi(os.Getenv("WORKER_INTERVAL_MS")) consumer, err := cons...
// Copyright 2012 The Freetype-Go Authors. All rights reserved. // Use of this source code is governed by your choice of either the // FreeType License or the GNU General Public License version 2 (or // any later version), both of which can be found in the LICENSE file. package truetype // The Truetype opcodes are su...
package backend_service import ( "2021/yunsongcailu/yunsong_server/backend/backend_dao" "2021/yunsongcailu/yunsong_server/web/web_model" ) type ConsumerServer interface { // 获取用户列表 FindConsumers() (consumerList []web_model.Consumers,err error) // 修改用户状态 1删除 0 激活 EditConsumerState(id int64,state int) (err error...
//go:build localtest package demo import ( "testing" "time" "github.com/rs/zerolog/log" "github.com/httprunner/httprunner/v4/hrp/pkg/uixt" ) func TestIOSDemo(t *testing.T) { device, err := uixt.NewIOSDevice( uixt.WithWDAPort(8700), uixt.WithWDAMjpegPort(8800), uixt.WithResetHomeOnStartup(false), // not re...
package repo import ( "api/entities" "database/sql" ) // ChatRepo ... type ChatRepo struct { db *sql.DB } // NewChatRepo ... func NewChatRepo(db *sql.DB) *ChatRepo { return &ChatRepo{ db: db, } } // Create ... func (c *ChatRepo) Create(chat *entities.Chat) error { return c.db.QueryRow(`INSERT INTO chats (na...
/* Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
package main import "fmt" func main() { var n int fmt.Scanf("%d", &n) for i := 0; i < n; i++ { var s string fmt.Scanf("%s", &s) fmt.Printf("%.2f\n", 0.01*float32(len(s))) } }
package xrequestid import ( "crypto/rand" "encoding/hex" "net/http" ) // By default the middleware set the generated random string to this key in the request header const DefaultHeaderKey = "X-Decker-Request-Id" // GenerateFunc is the func used by the middleware to generates the random string. type GenerateFunc f...
package main import ( "net" "fmt" "bytes" ) type Client struct { conn net.Conn username string } var clients = &Clients{ make([]*Client, 0), } type Clients struct { clients []*Client } func (c *Clients) SendAll(message string, from *Client) { var buffer bytes.Buffer buffer.WriteString(from.username) ...
package configuration import ( "github.com/roberthafner/bpmn-engine/domain/model" "os" "testing" ) func TestConfiguration(t *testing.T) { definition := `<definitions> <process id="1" name="test"> <startEvent id="2" name="start"/> <sequenceFlow id="3" name="sequence flow 3" sourceRef="2" targetRef="4"...
package main import ( "encoding/json" "errors" "io/ioutil" "log" "net/http" "os" "strings" ) const ( fallbackTEXT = "text" fallbackJSON = "json" fallbackHTML = "html" fallbackHTMLFile = "html_file" ) var ( errNameEmpty = errors.New("name is required") errBackendWeightNotMatch ...
package main import ( "net/http" "time" "github.com/gorilla/mux" "fmt" ) func main () { r := mux.NewRouter() r.HandleFunc("/", rootHandler) srv := &http.Server{ Handler: r, Addr: ":8080", WriteTimeout: 15 * time.Second, ReadTimeout: 15 * time.Second, } fmt.Println("Serving...") fmt....
package constant_test import "testing" const ( monday = 1 + iota Tuesday Wednesday ) const ( Readable = 1 << iota Writable Executable ) func TestConstantTry(t *testing.T) { t.Log(monday, Wednesday) t.Log(Writable, Executable) } func TestConstantTry1(t *testing.T) { a := 7 t.Log(a & Readable) }
package cmd import ( "fmt" "github.com/spf13/cobra" ) // reqsCmd represents the reqs command var reqsCmd = &cobra.Command{ Use: "reqs", Short: "List rest-client requests", Long: `List rest-client requests If no --http-file options are provided, looks for any files in the current working directory with the '....
package practice import ( "fmt" "testing" ) func Test_numIslands(t *testing.T) { type args struct { grid [][]byte } tests := []struct { name string args args want int }{ { name: "example 1", args: args{ grid: [][]byte{ []byte("11110"), []byte("11010"), []byte("11000"), []...
package main import "fmt" import "strconv" func main() { f, _ := strconv.ParseFloat("12.33", 64) fmt.Println(f) i, _ := strconv.Atoi("12") fmt.Println(i) t := strconv.FormatInt(456, 10) fmt.Printf("%T, %v\n", t, t) }
package handler import ( "fmt" log "github.com/sirupsen/logrus" "github.com/vascocosta/owm" ) func GetCurrentWeather(o *owm.Client, loc []string) (string, error) { l := log.WithFields(log.Fields{ "action": "handler.GetCurrentWeather", }) // Bot ist located in Cologne, Germany... so that's a default var weat...
package watchgod import ( "fmt" "log" ) // Die with an error message. func Fatal(msg string, args ...interface{}) { log.Printf("[FATAL] "+msg, args...) Exit(2) } // Cli dies with an error message, but does not print the timestamp func FatalCli(msg string, args ...interface{}) { fmt.Printf(msg+"\n", args...) Ex...
package main import ( "fmt" ) type WebController struct {} func (wc *WebController)GetName () string { return "Web Controller" } type Indexer interface { Index() } // Anonymous type embedding type AppController struct { *WebController Indexer } type IndexString string func (hs IndexString) Index() { fmt.P...
package main import ( "testing" "github.com/ghodss/yaml" "github.com/stretchr/testify/require" "github.com/xeipuuv/gojsonschema" ) func TestExecTemplate(t *testing.T) { bytes, err := execTemplate( []byte(`hello {{.ID}}`), struct{ ID string }{ID: "world"}, ) require.NoError(t, err) require.Equal(t, []by...
package main import ( "fmt" ) func main() { type tMatrix [5][5]int var matrix tMatrix // Building and printing the matrix for rowIndex, row := range matrix { fmt.Printf("\n ____ ____ ____ ____ ____ \n") for columnIndex := range row { matrix[rowIndex][columnIndex] = calculateFormula(rowIndex+...
package controller import ( "fmt" "ginEssential/common" "ginEssential/dto" "ginEssential/model" "ginEssential/response" "ginEssential/util" "github.com/gin-gonic/gin" "github.com/jinzhu/gorm" "golang.org/x/crypto/bcrypt" "log" "net/http" ) func Register(ctx *gin.Context) { DB := common.GetDB() // 1. 使用ma...
package config import ( "os" "github.com/jinzhu/gorm" "github.com/ranggarifqi/go-ecommerce-api/models" ) // MySQLInit Function to... init Mysql of course func MySQLInit() *gorm.DB { dbName := os.Getenv("DB_NAME") dbUser := os.Getenv("DB_USERNAME") dbPassword := os.Getenv("DB_PASSWORD") db, err := gorm.Open("...
/* Copyright 2021 The KubeVela Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, softw...
package controllers import ( "github.com/astaxie/beego" ) type MusicController struct { beego.Controller } func (c *MusicController) Get() { c.TplNames = "music.html" }
// Copyright 2017 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 filter import ( "errors" "poliskarta/api/helperfunctions" "strings" ) func FilterTitleWords(title string) ([]string, error) { var locationWords []string var err error if HasLocationInTitle(title) { locationWords = strings.Split(title, ",") removeTimeStamp(&locationWords) trimSpecialChars(&locatio...
package sabnzbd import ( "errors" "strings" ) var errorIndicator string = "error:" var ( ErrApikeyIncorrect error = errors.New("API Key Incorrect") ErrApikeyRequired error = errors.New("API Key Required") ) func apiStringError(str string) error { switch { case str == "": return nil case strings.Contains(s...
package main import ( "bufio" "fmt" "io" "os" "strconv" "strings" ) // Complete the designerPdfViewer function below. func designerPdfViewer(h []int32, word []string) int32 { wordIndex := [26]string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w...
package main import ( "context" "fmt" "github.com/sirupsen/logrus" "os" "os/signal" "syscall" "time" "github.com/gin-gonic/gin" "golang.org/x/sync/errgroup" ) const timeoutOpenAPIQuit = 2 * time.Minute func main(){ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) ...
package random_test import ( "strconv" "testing" "github.com/stretchr/testify/suite" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/irisnet/irismod/modules/random" "github.com/irisnet/irismod/module...
package order_notify import ( "strings" "testing" "tpay_backend/utils" ) func TestGetPayNotifyExpireKey(t *testing.T) { orderNo := "7161839048746535761091" t.Logf("key: %s", GetPayNotifyExpireKey(orderNo)) } func TestGetTransferNotifyExpireKey(t *testing.T) { orderNo := "8161839310558589810826" t.Logf("key: %...
package main import ( "context" "encoding/hex" "time" "github.com/golang/protobuf/ptypes/empty" "github.com/inc4/sm-test/spacemesh" "golang.org/x/exp/errors/fmt" "google.golang.org/grpc" ) func testEcho(s string) (value string, err error) { conn, err := grpc.Dial(rpcURL, grpc.WithInsecure()) if err != nil {...
/* Copyright 2021 The KubeVela Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, so...
package kvs import "time" // Node represents an entry in the kvs. type Node struct { CreatedIndex uint64 Dir bool Expiration *time.Time Key string ModifiedIndex uint64 Nodes Nodes Value string } // Nodes is a slice of Node pointers. type Nodes []*Node // KVS is an inte...
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package engine import ( "archive/zip" "bytes" "encoding/base64" "encoding/json" "fmt" "runtime/debug" "sort" "strings" "text/template" "github.com/Azure/go-autorest/autorest/to" "github.com/Azure/aks-engine/pk...
package repository import ( "database/sql" "fmt" "github.com/DATA-DOG/go-sqlmock" "github.com/jinzhu/gorm" "github.com/radyatamaa/loyalti-go-echo/src/domain/model" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "testing" ) type Suite struct { sui...
/* Create a function that returns any of the items you can afford in the store with the money you have in your wallet. Sort the list in alphabetical order. Examples itemsPurchased({ Water: "$1", Bread: "$3", TV: "$1,000", Fertilizer: "$20" }, "$300") ➞ ["Bread", "Fertilizer", "Water"] itemsPurchased({ App...
package qy import ( "context" "database/sql" "errors" "fmt" "log" "reflect" "strconv" "strings" "time" "github.com/bokwoon95/qy/qx" ) type SelectQuery struct { Nested bool Alias string // WITH CTEs qx.CTEs // SELECT SelectType qx.SelectType DistinctOn qx.Fields SelectFields qx.Fields // FROM ...
package repository import ( "bt/project/connect" "bt/project/models" "fmt" ) var db = connect.Connect() func InitData() { defer db.Close() listProducts := []models.Product{ { Name: "A", Description: "Description A", Price: 340, CategoryId: 1, Image: "Hahaha...
package main import ( "fmt" "strings" ) func main() { fmt.Println(strings.Contains("Danil Syah Arihardjo", "Udin")) fmt.Println(strings.Contains("Haykal Dafiansyah", "Haykal")) fmt.Println(strings.Split("Danil Syah Arihardjo", " ")) fmt.Println(strings.ToLower("Nufika Fitriani Setiawan")) fmt.P...