text
stringlengths
11
4.05M
package main import "fmt" func main() { for a := 1; a <= 1000; a++ { for b := 1; a+b <= 1000; b++ { if c := 1000 - a - b; a*a+b*b == c*c { fmt.Println(a * b * c) return } } } }
package internal_test import ( "archive/tar" "bytes" "fmt" "io" "os" "path/filepath" "strings" "testing" "time" "github.com/paketo-buildpacks/packit/cargo/jam/internal" "github.com/paketo-buildpacks/packit/scribe" "github.com/sclevine/spec" . "github.com/onsi/gomega" ) func testTarBuilder(t *testing.T,...
package solutions func plusOne(digits []int) []int { for i := len(digits); i > 0; i-- { if digits[i - 1] < 9 { digits[i - 1] += 1 return digits } digits[i - 1] = 0 if i == 1 { digits = append([]int{1}, digits...) } } return dig...
package wsqueue import ( "encoding/json" "os" "reflect" "strconv" "time" "github.com/satori/go.uuid" ) type Header map[string]string //Message message type Message struct { Header Header `json:"metadata,omitempty"` Body string `json:"data"` } func newMessage(data interface{}) (*Message, error) { m := Me...
package tree import ( "math" "testing" ) //二叉树的最小深度 func minDepth(root *TreeNode) int { if root == nil { return 0 } if root.Left == nil && root.Right == nil { return 1 } min := func(a int, b int) int { if a < b { return a } else { return b } } depth := math.MaxInt32 if root.Left != nil { ...
package main import ( "net/http" "github.com/gorilla/mux" ) // Route describes a specific route to handle unique requests type Route struct { Name string Method string Pattern string HandlerFunc http.HandlerFunc } // Routes is a collection of Route types type Routes []Route // NewRouter creat...
package main import "net/http" func main() { r := SetRouter() http.ListenAndServe(":3456", r) }
package api import ( "net/http" "testing" ) func TestUpdateAlertPolicy(t *testing.T) { c := newTestAPIClient(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write([]byte(` { "policy": { "id": 1234...
package local import ( "k8s.io/apimachinery/pkg/types" "github.com/tilt-dev/tilt/internal/store" ) type CmdCreateAction struct { Cmd *Cmd } func NewCmdCreateAction(cmd *Cmd) CmdCreateAction { return CmdCreateAction{Cmd: cmd.DeepCopy()} } var _ store.Summarizer = CmdCreateAction{} func (CmdCreateAction) Action...
package main import ( "fmt" "bufio" "os" "strings" "time" "sync" "github.com/go-errors/errors" "gomfc/models" "gomfc/ws_client" "gomfc/rtmpdump" ) const stateChanCap = 10000 type ModelState struct { models.MFCModel ChangeStateTime time.Time } type ModelMapType struct { sync.RWMutex Data map[uint64]...
package middleware import ( "fmt" "net/http" "time" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" ) func MyTimeMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { now := time.Now() next.ServeHTTP(writer, request) p...
package main import "github.com/gin-gonic/gin" func routerEntry(router *gin.Engine) { v1 := router.Group("/v1") { v1.POST("/api", chinSelectCaseFunc) } v2 := router.Group("/v2") { v2.POST("/api", chinSelectFunc) } v3 := router.Group("/v3") { v3.POST("/api/deduct", DeductWalletController) v3.POST("/a...
package solutions func findMin(nums []int) int { left, right := 0, len(nums) - 1 for left < right { middle := (right + left) / 2 if nums[middle] < nums[right] { right = middle } else if nums[middle] > nums[right] { left = middle + 1 } else if nums[middle...
package lifxlan // ProductMap is the map of all known hardwares. // // If a new product is added and this file is not updated yet, // you can add it to the map by yourself, for example: // // func init() { // key := lifxlan.ProductMapKey(newVID, newPID) // lifxlan.ProductMap[key] = ParsedHardwareVe...
package handlers import ( "encoding/json" "net/http" "strconv" "bitbucket.org/Sanny_Lebedev/test6/fibb" "github.com/satori/go.uuid" ) type ( answer struct { UID string `json:"UID"` Success bool `json:"success"` Done bool `json:"done"` Meta meta `json:"meta"` } meta struct { Last in...
// Copyright 2018 The gVisor 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 agree...
// https://leetcode.com/problems/k-closest-points-to-origin/ package leetcode_go import ( "container/heap" "math" ) type PointHeap [][]int func (h PointHeap) Len() int { return len(h) } func (h PointHeap) Less(i, j int) bool { return math.Sqrt(float64(h[i][0]*h[i][0]+h[i][1]*h[i][1])) < math.Sqrt(float64(h[j][...
// Copyright 2014 Dirk Jablonowski. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* bricker is a API for the Tinkerforge Hardware based on the brick daemon (brickd). A bricker is a manager. It uses one or more connectors to send and recei...
package main import ( "github.com/asim/go-micro/plugins/client/grpc/v3" "github.com/asim/go-micro/plugins/server/http/v3" "github.com/asim/go-micro/v3" "github.com/asim/go-micro/v3/logger" "github.com/gin-gonic/gin" pb "github.com/xpunch/go-micro-example/v3/helloworld/proto" ) func main() { srv := micro.NewSer...
package localcache import ( "encoding/base64" "fmt" "os" "path/filepath" "sync" "github.com/loft-sh/devspace/pkg/devspace/env" "github.com/loft-sh/devspace/pkg/util/encryption" "gopkg.in/yaml.v3" ) type Cache interface { ListImageCache() map[string]ImageCache GetImageCache(imageConfigName string) (ImageCac...
// This file is part of CycloneDX GoMod // // 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 raw import ( "time" "github.com/docker/docker/api/types" ) // Metrics holds containers raw metric values as they are extracted from the system type Metrics struct { Time time.Time ContainerID string Memory Memory Network Network CPU CPU Pids Pids Blkio Blkio } /...
package services import "github.com/jceatwell/bookstore_users-api/domain/users" // CreateUser service method to create user func CreateUser(user users.User) (*users.User, error) { return nil, nil }
package rbac import ( "fmt" //"errors" m "cms_admin/admin/src/models" "github.com/astaxie/beego/logs" ) type ChannelController struct { CommonController } func (this *ChannelController) Index() { // 写入日志测试 logs.Warn("json is a type of kv like", map[string]int{"key": 2016}) // redis redis := m.GetRedis() d...
package scalars_test import ( "testing" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) func TestSessions(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Sessions Suite") }
package config import ( "os" "strconv" ) type config struct { GrpcPort uint16 MongoDbHost string MongoDbDatabase string } var configInstance config func init() { port, err := strconv.Atoi(os.Getenv("WALLET_PORT")) if err != nil { port = 50051 } configInstance.GrpcPort = uint16(port) configIn...
package main import ( "fmt" ds "github.com/deepak-muley/golangexamples/prefix-transform" ) /* Input { "1": "ABC", "2": "AB", "3", "B", "4", "ABCD" } * Transform into the below Output: { "1": "2C", "2": "AB", "3": "B", "4": "1D" } */ func createGraph(input map[string][]string) *ds.Graph { gr := d...
package utreexo import ( "fmt" "testing" ) // Add 2. delete 1. Repeat. func Test2Fwd1Back(t *testing.T) { f := NewForest() var absidx uint32 adds := make([]LeafTXO, 2) for i := 0; i < 100; i++ { for j := range adds { adds[j].Hash[0] = uint8(absidx>>8) | 0xa0 adds[j].Hash[1] = uint8(absidx) adds[j...
package storage import ( "context" "fmt" "os" "testing" "github.com/databrickslabs/terraform-provider-databricks/access" "github.com/databrickslabs/terraform-provider-databricks/compute" "github.com/databrickslabs/terraform-provider-databricks/internal" "github.com/databrickslabs/terraform-provider-databrick...
package keptn import ( "errors" "fmt" "github.com/keptn-contrib/dynatrace-service/internal/common" keptnmodels "github.com/keptn/go-utils/pkg/api/models" api "github.com/keptn/go-utils/pkg/api/utils" log "github.com/sirupsen/logrus" ) // ConfigResourceClientInterface defines the methods for interacting with res...
package routes import ( "bytes" "encoding/json" "errors" "flag" "fmt" "net" "net/http" "os" "strings" "ark/store" ) const ( routesCmd = "routes" backendsCmd = "backends" ) var errNotImplemented = errors.New("not implemented") // CanRun ... func CanRun(args []string) bool { return args[0] == routesCm...
package partition_test import ( "fmt" "testing" "time" "github.com/Workiva/go-datastructures/queue" "github.com/stretchr/testify/assert" "github.com/zhuangzhi/go-programming/partition" ) func TestPartitionTable(t *testing.T) { table := partition.NewPartitionTable(1024) for i := 0; i < 1024; i++ { for j :...
package main import ( "fmt" "math" ) type Point struct { X, Y float64 } func (p Point) Distance(q Point) float64 { return math.Hypot(q.X-p.X, q.Y-p.Y) } // 指针方式的接收器 func (p *Point) ScaleBy(factor float64) { p.X *= factor p.Y *= factor } type Line struct { Start Point End Point // Length float64 } func ...
package leetcode func isHappy(n int) bool { nmap := make(map[int]int) var sum int for { for _, v := range strconv.Itoa(n) { num, _ := strconv.Atoi(string(v)) square := num * num sum += square _, ok := nmap[sum] if ok { return false } } if sum == 1 { return true } nmap[sum] = 1 n...
package heaps import ( "fmt" "reflect" "testing" ) func TestHeap(t *testing.T) { array := []int{9, 7, 8, 5, 6, 4, 3, 2, 0, 1} maxHeapify(array, 0, len(array)) fmt.Printf("Max Heap:\n") String(array) sortedArray := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} HeapSort(array) if !reflect.DeepEqual(array, sortedArray)...
package main import ( "log" "net/http" "github.com/gorilla/mux" controller "./controller" help "./helper" model "./model" config "./config" ) func main() { model.InitBdd() defer model.Bdd.Close() router := mux.NewRouter() /** ENDPOINT /ping */ { /** * @api {get} /ping Get * @apiDescription P...
//go:build stacktrace // +build stacktrace package ierrors import ( "strings" "testing" "github.com/stretchr/testify/require" ) func TestErrors(t *testing.T) { var errWithStacktrace *errorWithStacktrace // check that there is no stacktrace included err1 := New("err1") require.False(t, Is(err1, &errorWithSta...
package typgo_test import ( "flag" "strings" "testing" "github.com/stretchr/testify/require" "github.com/typical-go/typical-go/pkg/typgo" "github.com/urfave/cli/v2" ) func TestGoBuild_Command(t *testing.T) { cmpl := &typgo.GoBuild{} command := cmpl.Task().CliCommand(&typgo.Descriptor{}) require.Equal(t, "...
package app import "errors" // InvalidRequestError is special error type returned when any request params are invalid. type InvalidRequestError string // Error implements error interface. func (e InvalidRequestError) Error() string { return string(e) } // IsInvalidRequest tells that this error is 'invalid request'...
package main import ( "flag" "fmt" "log" "os" "text/template" "github.com/dominicbarnes/terraform-provider-mongodb/mongodb" "github.com/hashicorp/terraform/terraform" ) var tmpl = flag.String("template", "", "template file to render with") var output = flag.String("output", "", "destination file") func init(...
package entities import ( "encoding/json" "io/ioutil" "os" "testing" ) var initialSymbol = Symbol{ Text: "Lorum ipsum", } func TestItUnmarshalsSymbolJson(t *testing.T) { data, err := ioutil.ReadFile("testdata/symbol.json") if err != nil { panic(err) } var symbol Symbol json.Unmarshal(data, &symbol) ...
package graph import "testing" func TestPathStringRepresentation(t *testing.T) { a := &Node{ID: "A"} b := &Node{ID: "B"} c := &Node{ID: "C"} pOne := Path{a, b, c} pTwo := Path{a, c, b} pThree := Path{b, a} pFour := Path{c} pFive := Path{} if pOne.String() != "A -> B -> C" { t.Errorf("Path string represent...
package env import ( "fmt" "os" "strconv" ) func Get(key string) string { value := os.Getenv(key) if len(value) == 0 { fmt.Printf("Environment variable '%s' not set\n", key) } return value } func GetBool(key string) bool { if Get(key) == "yes" { return true } return false } func GetInt(key string) in...
package ravendb import ( "encoding/json" "io" "strconv" ) const ( outOfRangeStatus = -1 dropStatus = -2 ) func negotiateProtocolVersion(stream io.Writer, parameters *tcpNegotiateParameters) (*supportedFeatures, error) { v := parameters.version currentRef := &v for { sendTcpVersionInfo(stream, paramet...
// sortgen holds the implementations of the most common sorting and permutation algorithms. package sortgen import ( "math/rand" "time" "github.com/paulidealiste/goalgs/datagen" "github.com/paulidealiste/goalgs/rangen" "github.com/paulidealiste/goalgs/utilgen" ) // Bubble sort proceeds by traversing the target ...
package crawler import ( "github.com/l-dandelion/cwgo/spider" "sync" ) var ( crawler Crawler once sync.Once ) type Crawler interface { GetSpider(name string) spider.Spider AddSpider(sp spider.Spider) error DeleteSpider(name string) error InitSpider(name string) error StartSpider(name string) error StopS...
package main import ( "beego_url/controllers" "github.com/astaxie/beego" ) func main() { beego.SetStaticPath("/images", "static/images") beego.SetStaticPath("/css", "static/css") beego.SetStaticPath("/js", "static/js") beego.Router("/:shorturl:string", &controllers.RedirectController{}) beego.Router("/", &con...
package durationdata import ( "io" "net/http" "sync" "github.com/BerryHub/helpers/request" "github.com/BerryHub/config" ) // WeatherRemoteData - Definisce il tipo di duration data specifico per il meteo // implementa RemoteData type WeatherRemoteData struct{} var weatherData *DurationData var onceWeather sync...
// Copyright 2020 The gVisor 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 agree...
package nebula import ( "errors" "net" "sync" "sync/atomic" "time" "github.com/rcrowley/go-metrics" "github.com/sirupsen/logrus" "github.com/slackhq/nebula/cert" "github.com/slackhq/nebula/cidr" "github.com/slackhq/nebula/header" "github.com/slackhq/nebula/iputil" "github.com/slackhq/nebula/udp" ) // con...
package logger import ( "fmt" "io" "os" "path" "path/filepath" "sync" "time" "github.com/mattn/go-colorable" "github.com/rs/zerolog" fallbacklog "github.com/rs/zerolog/log" "github.com/urfave/cli/v2" "golang.org/x/term" "gopkg.in/natefinch/lumberjack.v2" "github.com/cloudflare/cloudflared/features" "g...
package snailframe import ( "github.com/CloudyKit/jet" log "github.com/sirupsen/logrus" "io" "os" "path/filepath" ) type tpl struct { tplSet *jet.Set tplSuffix string } type tplConfig struct { Dir string Suffix string Reload bool } func newTpl(cfg tplConfig) *tpl { if cfg.Dir == "" { cfg.Dir = "templa...
package template import ( "fmt" "net/mail" "github.com/jrapoport/gothic/config" "github.com/matcornic/hermes/v2" ) // ChangeEmailAction confirm email action const ChangeEmailAction = "change/email" // ChangeEmail mail template type ChangeEmail struct { MailTemplate newAddress string } var _ Template = (*Chan...
// ===================================== // // author: gavingqf // // == Please don'g change me by hand == // //====================================== // /*you have defined the following interface: type IConfig interface { // load interface Load(path string) bool // clear interface Clear() }...
package main import ( "bytes" "flag" "fmt" "image" "image/color" "os" "github.com/marianina8/expression/azure" "gocv.io/x/gocv" ) func check(msg string, e error) { if e != nil { panic(fmt.Errorf("%s: %s", msg, e.Error())) } } func main() { video := flag.String("video", "", "video for emotion analysis")...
package core_test import ( core "github.com/misostack/ezgo/core" "testing" "fmt" ) func TestParseWebServerConfig(t *testing.T) { cfg := core.WebServerConfig{} core.ParseWebServerConfig(&cfg) fmt.Printf("%v\n", cfg) } // func TestConfigStructToMap(t *testing.T) { // // test with Config struct // cfg := core....
package crypto import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/x509" "encoding/asn1" "encoding/pem" "errors" "fmt" "github.com/dgrijalva/jwt-go" "io/ioutil" "log" "math/big" "os" ) var TEST_ENV = false var keyName = "private.pem" func newPrivateKey() *ecdsa.PrivateKey { log.Println("cr...
package confsvr import ( "fmt" "github.com/oceanho/gw/sdk/confsvr/param" "sync" "time" ) var st *state type state struct { sync.Once state *setting } func init() { st = &state{} } type setting struct { AccessKeyId string AccessKeySecret string OnChangedCallback func(data []byte) Namespa...
// https://leetcode.com/problems/find-the-town-judge/ package leetcode_go func findJudge(N int, trust [][]int) int { indegree := make(map[int]int) outdegree := make(map[int]int) for _, line := range trust { indegree[line[1]]++ outdegree[line[0]]++ } for i := 1; i <= N; i++ { if indegree[i] == N-1 && outdeg...
// 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 main import ( "crypto/sha256" "fmt" ) func popCount(x byte) int { num := 0 var i uint for ; i < 8; i++ { num += int((x >> i) & 1) } return num } func countDifference(c1 string, c2 string) int { c1Hash := sha256.Sum256([]byte(c1)) c2Hash := sha256.Sum256([]byte(c2)) num := 0 for index, char := ra...
package main import ( "fmt" "net/http" Controllers "./controllerClasses" ) func handleRequests() { fmt.Println("Server started on: http://localhost:8080") http.HandleFunc("/hash/", Controllers.GetHashedValue) http.HandleFunc("/hash", Controllers.SetHashedValue) http.HandleFunc("/stats", Controllers.ReadStats) ...
package Model import ( _struct "1/struct" ) func DeleteVideo(uid, vid string) error { err := DB.Where("id=? and uid=?", vid, uid).Delete(_struct.Video{}).Delete(_struct.VideoInfo{}).Error //stmt, err := DB.Prepare("DELETE FROM videos WHERE id=? and uid=?") //if err != nil { // return err //} //defer stmt.Clos...
package controllers import ( "net/http" m "github.com/fullstacktf/Narrativas-Backend/models" "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" ) func Register(context *gin.Context) { var newUser m.User if err := context.ShouldBindWith(&newUser, binding.JSON); err != nil { context.JSON(http.Stat...
package main import ( "fmt" ) type Phone struct{} func (p *Phone) Call() string { return "a call" } type Camera struct{} func (c *Camera) TakeAPicture() string { return "a picture" } type CameraPhone struct { Phone Camera } func main() { cp := new(CameraPhone) fmt.Printf("give a call. %s \n", cp.Call()) ...
package httpbot import ( "bytes" "encoding/binary" "fmt" "log" "os" "strings" "sync/atomic" "util" "webbot" "golang.org/x/net/websocket" ) type Client struct { r *Robot msgChan chan []byte errChan chan error groupMap map[uint64]uint64 name string clientID uint64 cookie string debug ...
package inmemory import ( "context" "github.com/go-redis/redis/v8" "github.com/pkg/errors" "os" ) type MemStore interface { init() error Set(key, value string) error Get(key string) (string, error) } type storage struct { client *redis.Client } func NewStorage() (MemStore, error) { s := &storage{} err := ...
package provider import ( "net/http" "net/http/httptest" "net/url" "testing" "github.com/evcc-io/evcc/util" "github.com/samber/lo" "github.com/stretchr/testify/assert" ) type httpHandler struct { val string req *http.Request } func (h *httpHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { h.r...
package main import "fmt" //arrays are a number of elements //of a specific type and cannot change their length(unlike slices) //arrays are not commonly used //they are an underlying datatype //that are relied upon by other datatypes //such as slices which are the more common option func main() { //if you define a n...
package kth_missing_positive_number import ( "testing" "github.com/stretchr/testify/assert" ) func Test_findKthPositive(t *testing.T) { tests := []struct { arr []int k int want int }{ { arr: []int{2, 3, 4, 7, 11}, k: 5, want: 9, }, { arr: []int{1, 2, 3, 4}, k: 2, want: 6...
package libldbrest import ( "bytes" "github.com/syndtr/goleveldb/leveldb/opt" ) func iterate(start []byte, include_start, backwards bool, handle func([]byte, []byte) (bool, error)) error { iter := db.NewIterator( nil, &opt.ReadOptions{ DontFillCache: true, }, ) if bytes.Equal(start, []byte{}) { if b...
package fakes import ( "sync" "github.com/gophercloud/gophercloud/openstack/compute/v2/servers" ) type ComputeClient struct { DeleteCall struct { sync.Mutex CallCount int Receives struct { InstanceID string } Returns struct { Error error } Stub func(string) error } ListCall struct { sync....
package virtualmachinevolume import ( "context" goerrors "errors" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/klog" hc "kubevirt-image-service/pkg/apis/hypercloud/v1alpha1" "kubevirt-image-service/pkg/util" "sigs.k...
/* Copyright 2020 Huawei Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dis...
// Copyright 2018 NetApp, Inc. All Rights Reserved. package rest import ( "net/http" "time" "github.com/rs/xid" log "github.com/sirupsen/logrus" ) func Logger(inner http.Handler, name string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() requestId...
package solutions func jump(nums []int) int { maxStep := len(nums) - 1 currentPosition := 0 steps := 0 if maxStep == 0 { return 0 } for { nextMaxStep := nums[currentPosition] steps++ if nextMaxStep >= maxStep { break } max := 0 ...
package kata func Arithmetic(a int, b int, operator string) int{ //your code here switch operator { case "add": return a + b case "subtract": return a - b case "multiply": return a*b case "divide" : return a/b } return 0 }
package main import ( "io/ioutil" ) func main() { http.HandleFunc("/", handler) http.ListenAndServe(":3000", nil) } func handler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html") dat, err := ioutil.ReadFile("index.html") check(err) w.Write(dat) } func check(e error) { if ...
// Copyright (C) 2016-Present Pivotal Software, Inc. All rights reserved. // This program and the accompanying materials are made available under the terms of the 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 Licen...
// Copyright (C) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed t...
package day08 import ( "errors" "fmt" "log" ) func process(code []string, pc int, acc int) (int, int) { op := "" arg := 0 n, err := fmt.Sscanf(code[pc], "%s %d", &op, &arg) if err != nil { panic(err) } if n != 2 { panic(fmt.Sprintf("Error parsing instruction on line %v: %q", pc, code[pc])) } switch op ...
/* author:admin createTime: */ package main import "testing" func TestAdd(t *testing.T) { sum := Add(1, 2) if sum == 3 { t.Log("the result is ok") } else { t.Fatal("the result is wrong") } } func Add(i int, i2 int) int { return i + i2 } func BenchmarkRemoveEles(b *testing.B) { b.ResetTimer() numbs := []i...
package main import ( "context" "fmt" "github.com/lack-io/vine/service" pb "github.com/lack-io/vine-example/helloworld/proto" ) func main() { srv := service.NewService(service.Name("go.vine.helloworld")) service := pb.NewHelloworldService("go.vine.helloworld", srv.Client()) rsp, err := service.Call(context....
package main import "fmt" import "unicode/utf8" func main() { s := "文旭" fmt.Printf("% x\n", s) //byte r := []rune(s) // unicode fmt.Printf("%x\n", r) fmt.Println(string(r)) fmt.Println(utf8.RuneCountInString(s)) }
package models type Comment struct { CommentID int `json:"cid"` Content string `json:"content"` OnIssue int `json:"issue"` } type Comments []Comment
// @title bitsongms API Docs // @version 0.1 // @description Swagger documentation for the BitSong Media Server service API. // @contact.name BitSong // @contact.email hello@bitsong.io // @license.name CC0 // @license.url https://creativecommons.org/share-your-work/public-domain/cc0/ // @host localhost:8081 // @Base...
package configure import ( "bytes" _ "embed" "text/template" "github.com/Masterminds/sprig/v3" "github.com/evcc-io/evcc/util/templates" ) type device struct { Name string Title string Yaml string ChargerHasMeter bool // only used with chargers to detect if we need to ask for ...
// Copyright 2021 The Perses 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 ...
package leetcode73 import "testing" type matrix [][]int func TestSetZeroes(t *testing.T) { tests := []struct { input matrix want matrix }{ {matrix{{}}, matrix{{}}}, {matrix{{1}}, matrix{{1}}}, {matrix{{0}}, matrix{{0}}}, {matrix{{0, 1}, {1, 1}}, matrix{{0, 0}, {0, 1}}}, {matrix{{0, 0}, {1, 1}}, matr...
package main import "net" type _TtcpNodeDataRece struct { TnrRaddr string // string of net.Addr TnrLen int TnrId128 []byte // channel id TnrK256 []byte // AES key 256 using when receive if not nil TnrBuf []byte TnrOffset int64 } func (__Vtndr *_TtcpNodeDataRece) String() string { return _Spf( "add...
package raft import ( "fmt" "math/rand" "os" "reflect" "testing" "github.com/hashicorp/raft" "github.com/hashicorp/raft-boltdb" ) // Fuzz tester comparing this to hashicorp/raft-boltdb. func TestRaft_Fuzz(t *testing.T) { logdb := assertOpen(t, dbTypes["lock free chunkdb"], false, true, "fuzz") defer assertC...
package yamltojson import ( "fmt" // This is a fork of gopkg.in/yaml.v2 that fixes anchors with MapSlice "github.com/buildkite/yaml" ) // Unmarshal YAML to map[string]interface{} instead of map[interface{}]interface{}, such that // we can Marshal cleanly into JSON // Via https://github.com/go-yaml/yaml/issues/139...
package sitter_test import ( "testing" sitter "github.com/kiteco/go-tree-sitter" "github.com/kiteco/go-tree-sitter/javascript" ) var ( ResultUint32 uint32 ResultSymbol sitter.Symbol ResultPoint sitter.Point ResultString string ResultNode *sitter.Node ) func BenchmarkNode(b *testing.B) { src := []byte("l...
package comutil // ContainsStr accepts an array of string and another string under test, it returns true if // string under exists in the given array. func ContainsStr(s []string, e string) bool { for _, a := range s { if a == e { return true } } return false }
package main import "fmt" const myName string = "Aleks" func main() { fmt.Println("Hello, my name is", myName) }
// https://tour.golang.org/concurrency/8 package main import ( "fmt" "golang.org/x/tour/tree" ) // Walk walks the tree t sending all values // from the tree to the channel ch. func Walk(t *tree.Tree, ch chan int) { _walk(t, ch) close(ch) } func _walk(t *tree.Tree, ch chan int) { if t == nil { return...
package ravendb import ( "net/http" ) var _ IVoidMaintenanceOperation = &StartIndexingOperation{} type StartIndexingOperation struct { Command *StartIndexingCommand } func NewStartIndexingOperation() *StartIndexingOperation { return &StartIndexingOperation{} } func (o *StartIndexingOperation) GetCommand(convent...
// Copyright 2018 gf Author(https://gitee.com/johng/gf). All Rights Reserved. // // This Source Code Form is subject to the terms of the MIT License. // If a copy of the MIT was not distributed with this file, // You can obtain one at https://gitee.com/johng/gf. // 定时任务. package gcron import ( "errors" "fmt" ...
package data import ( "database/sql" "log" "time" ) import _ "github.com/go-sql-driver/mysql" var Db *sql.DB func init() { Db, err := sql.Open("mysql", "monstar-lab:password@tcp(localhost:3306)/todo?parseTime=true") // To avoid client-side timeout Db.SetConnMaxLifetime(time.Second) if err != nil { log.Print...
package altrudos import ( vinscraper "github.com/Vindexus/go-scraper" "testing" "github.com/monstercat/golib/expectm" ) func TestParseSourceURL(t *testing.T) { type sourceTest struct { URL string ExpectedType string ExpectedKey string Error error ExpectedMeta *expectm.ExpectedM } te...