text
stringlengths
11
4.05M
/* Copyright 2019 The Skaffold 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, sof...
package main import "fmt" var deferSummary = ` 1、defer虽然是在return之前执行的,但是如果return后面接的是函数,那么这个函数还是先于defer执行的 2、defer会在return指令之前执行,而go中的“return **”不是原子操作,其返回值放在栈而不是寄存器(比如C),所以“return **”执行时会被拆解为“$返回变量 = ** return”,所以defer后面的语句会在“$返回变量 = **“ 和 ”return”之间执行 ` // 返回值应该是1 func deferF1() (result int) { defer func() { re...
/* Copyright 2021 The KodeRover 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, s...
package main import ( "fmt" "strconv" "strings" "github.com/spf13/cobra" ) //GetBlockCountCmd get block count var GetBlockCountCmd = &cobra.Command{ Use: "getblockcount", Short: "get block count", Example: ` getblockcount `, Args: cobra.NoArgs, Run: func(cmd *cobra.Command, args []string) { params ...
package arrayStack import "testing" func Test(t *testing.T) { arrayStack := NewArrayStack() arrayStack.Add(0, 0) // [0] arrayStack.Add(1, 1) // [0 1] arrayStack.Add(2, 2) // [0 1 2] arrayStack.Add(3, 3) // [0 1 2 3] arrayStack.Add(3, 33) // [0 1 2 33 3] arrayStack.Add(4, 4) // [0 1 2 33 4 3] arrayStack....
// Copyright © 2017 Casey Marshall // // 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 test import ( queue_server "algori/queue/queue-server" "encoding/json" "io/ioutil" "log" "net/http" "strings" "testing" ) var( ctx=queue_server.InitServer() ) type KVData struct { Key string Val string } func TestQueueServer(t *testing.T) { http.HandleFunc("/put", putData) http.HandleFunc("/get",...
package usecase import ( "errors" "fmt" "marketplace/transactions/domain" "github.com/go-pg/pg/v10" ) type CancelTransactionCmd func(db *pg.DB, transacId int64, userId int64) (domain.Transaction, error) func CancelTransaction() CancelTransactionCmd { return func(db *pg.DB, transacId int64, userId int64) (doma...
// Copyright 2019 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package bst type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func rangeSumBST(root *TreeNode, low int, high int) int { s := 0 nodes := []*TreeNode{root} for len(nodes) > 0 { level := []*TreeNode{} for _, n := range nodes { if low <= n.Val && n.Val <= high { s += n.Val } if n.L...
package Tournament import ( "encoding/csv" "fmt" "io" "sort" "strings" "text/tabwriter" ) // Team is a football team in the League type Team struct { Name string MP, W, D, L, P int } // League represents the score board type League struct { teams []*Team } // ParseData reads input data and delega...
package storage import ( "btcnetwork/common" "btcnetwork/p2p" "context" "encoding/binary" "github.com/syndtr/goleveldb/leveldb" "reflect" "sync" ) const ( UtxoTxChanSize = 2000 ) type utxoMgr struct { tx chan p2p.TxPayload dbUtxo *leveldb.DB } var defaultUtxoMgr *utxoMgr func newUtxoMgr(cfg *common...
package main import ( "fmt" "github.com/micro/go-micro/v2" "github.com/micro/go-micro/v2/broker" "github.com/micro/go-plugins/broker/rabbitmq/v2" "go-micro-demos/broker/rabbitmq/config" "go-micro-demos/broker/rabbitmq/subscriber" "log" ) var ( conf = config.Config() topic = conf.To...
package docker import ( "container/list" "fmt" "fp-dynamic-elements-manager-controller/internal/db/persistence" "fp-dynamic-elements-manager-controller/internal/docker/structs" "fp-dynamic-elements-manager-controller/internal/docker/utils" "fp-dynamic-elements-manager-controller/internal/notification" "github.c...
package test import ( "log" project "github.com/cakazies/project-service/grpc" "github.com/joho/godotenv" "google.golang.org/grpc" ) func loadEnv() { err := godotenv.Load("../.env") if err != nil { log.Fatal("Error loading .env file error : ", err) } } func serviceProject() project.ProjectsClient { port ...
// Copyright 2019 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 main import ( "fmt" "os" ) func main() { if len(os.Args) != 2 { os.Exit(1) } password := os.Args[1] next := []rune(password) for { next = Increment(next) if HasStraight(next) && HasTwoPairs(next) { fmt.Printf("Next password: %s\n", string(next)) break } } } func Increment(input []rune)...
package cache import ( "context" "fmt" "strings" "github.com/go-redis/redis/v7" "github.com/rickbassham/example-go/pkg/logging" "go.uber.org/zap" ) // LoggerHook is used to log all calls to redis. type LoggerHook struct { } // BeforeProcess is called before the call to redis for a single command. func (h Logg...
package main import ( "github.com/gin-gonic/gin" "github.com/labstack/gommon/log" "tweb/global" "tweb/handler" "tweb/model" ) func main() { conf, err := global.LoadConfig() if err != nil { log.Fatalf("load config failed, %s", err) } router := gin.Default() //init data model model.Init(conf.DBType, con...
// Copyright (c) 2016-2019 Uber Technologies, 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...
// Copyright 2016 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
// By naming this file with _test suffix it is not measured // in the coverage report, although we do end-up with a strange file name... package validate import ( "fmt" . "github.com/onsi/gomega" ) func assertNoValidationErrors(errors []YamlValidationIssue) { Ω(len(errors)).Should(Equal(0), fmt.Sprintf("Validatio...
package main import "fmt" /* Given a binary array, find the maximum number of consecutive 1s in this array. Example 1: Input: [1,1,0,1,1,1] Output: 3 Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. Note: The input array will only contain ...
/* Copyright 2019 The Skaffold 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, sof...
package main import ( "flag" "fmt" "html/template" "log" "net/http" "net/url" "strconv" "droprate" ) var ( certFile = flag.String("cert_file", "", "Full path to cert.pem") keyFile = flag.String("key_file", "", "Full path to privkey.pem") templateFile = flag.String("template_file", "", "Full path ...
package main import ( "fmt" "math/rand" "sync" "time" ) const ( numberGoroutines = 4 tasks = 10 ) var ( wg3 sync.WaitGroup ) func init() { rand.Seed(time.Now().UnixNano()) } func main() { taskChan := make(chan string, tasks) wg3.Add(numberGoroutines) for i := 1; i <= numberGoroutines; i++ {...
// Copyright 2017 Baidu, 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...
package input import ( "encoding/json" ) type DOKS struct { DORegion string `json:"do_region"` DOToken string `json:"do_token"` ClusterName string `json:"cluster_name"` } func (doks *DOKS) GetInput() ([]byte, error) { return json.Marshal(doks) } func GetDOKSInput(bytes []byte) (*DOKS, error) { res := &...
package utils import ( "strings" "unicode" ) // CleanElements clean whitespaces in strings. func CleanElements(strList []string) []string { for index, each := range strList { each = strings.TrimSpace(each) strList[index] = each } return strList } // RemoveChar removes rune from string. func RemoveChar(str s...
package main import ( "net/http" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.StaticFS("/assets/", http.Dir("assets")) r.LoadHTMLGlob("templates/*.tmpl") r.GET("/", func(c *gin.Context) { c.HTML(http.StatusOK, "index.tmpl", nil) }) r.StaticFS("/waveform", h...
package crudcontracts import ( "context" "github.com/adamluzsi/testcase/assert" "github.com/adamluzsi/testcase/pp" "testing" "github.com/adamluzsi/frameless/pkg/pointer" . "github.com/adamluzsi/frameless/ports/crud/crudtest" "github.com/adamluzsi/frameless/ports/crud" "github.com/adamluzsi/frameless/ports/c...
package main import ( "os" "log" "encoding/csv" "io" "fmt" ) func main(){ irisFile,err:=os.Open("readingcsv/data/iris_unexpected_fields.csv") if err!=nil{ log.Fatal(err) } var irisData [][] string reader:=csv.NewReader(irisFile) reader.FieldsPerRecord=5 for { record,err:=reader.Read() if er...
package main import ( "fmt" ) // data[:6:8] 每个数字前都有个冒号, slice内容为data从0到第6位,长度len为6,最大扩充项cap设置为8 // a[x:y:z] 切片内容 [x:y] 切片长度: y-x 切片容量:z-x func main() { slice := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} d1 := slice[6:8] fmt.Println(d1, len(d1), cap(d1)) d2 := slice[:6:8] fmt.Println(d2, len(d2), cap(d2)) }
package storageos import ( "context" "net/http" api "github.com/storageos/go-api/v2" ) type fakeReadCloser struct{} func (f fakeReadCloser) Read(p []byte) (n int, err error) { return 0, nil } func (f fakeReadCloser) Close() error { return nil } // Fake returns a client that uses a fake Contr...
package main import ( "bufio" "fmt" "os" "github.com/Supro/mail_ru" "github.com/Supro/mail_ru/database" ) func main() { reader := bufio.NewReader(os.Stdin) db := &database.Database{Links: make(map[string]*mail_ru.Link)} ls := database.LinkService{db} w := mail_ru.NewWorker() w.Match = "go" w.Limit = 5 ...
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //go:generate protoc -I . --go_out=plugins=grpc:../../../../.. os_install_service.proto // Package osinstall provides the OsInstallService package osinstall // Run the foll...
package request import ( "fmt" "net/http" ) type HTTPError struct { statusCode int message string } func (h *HTTPError) Error() string { return fmt.Sprintf("[%d] %s", h.statusCode, h.message) } func NewHTTPError(statusCode int, message string, format ...interface{}) *HTTPError { return &HTTPError{statusCod...
package main import ( "log" "encoding/json" ) type JSONExport struct {} func (export *JSONExport) Export(e *Experiment) ([]byte, error) { content, err := json.Marshal(e) if err != nil { log.Printf("[export|json] experiment marshalling failed! Error: '%s'\n", err) return []byte{}, err } return content, nil...
package commands import ( "github.com/brooklyncentral/brooklyn-cli/net" ) type CatalogPolicy struct { network *net.Network } func NewCatalogPolicy(network *net.Network) (cmd *CatalogPolicy) { cmd = new(CatalogPolicy) cmd.network = network return }
// 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 core import ( "errors" "log" pb "github.com/merryChris/docDropper/protos" "golang.org/x/net/context" "google.golang.org/grpc" ) type PlatformClient struct { initialized bool client pb.PlatformClient fitStream pb.Platform_FitClient conn *grpc.ClientConn } // NewPlatformClient 生成 Platfo...
package delta import ( "github.com/valyala/gorpc" "time" "os" "log" ) func (dc *DeltaCore) NewRPClient() { server_url := os.Getenv("DELTA_SERVER") if server_url == "" { server_url = "127.0.0.1:12345" } log.Println("Connecting to: ", server_url) dc.Rpc = &gorpc.Client{ Addr...
package postgres import ( "context" "database/sql" "errors" "fmt" "strings" "github.com/guregu/null" "github.com/lib/pq" "github.com/pganalyze/collector/state" "github.com/pganalyze/collector/util" ) // pg_stat_statements 1.3+ (Postgres 9.5+) const statementSQLOptionalFieldsMinorVersion3 = "queryid, min_tim...
package util import ( "io/ioutil" "strings" "github.com/prometheus/common/log" ) var productName string func GetProductName() string { // Get product_name from /sys/devices/virtual/dmi/id/product_name if bv, err := ioutil.ReadFile("/sys/devices/virtual/dmi/id/product_name"); err == nil { productName = strings...
package campain import ( "fmt" "github.com/tapvanvn/go-chain-wrapper/export" ) //MARK:Client type ClientBlackSmith struct { Campain *Campain } //Make make tool func (blacksmith *ClientBlackSmith) Make(origin string, meta interface{}) interface{} { endpoint := string(blacksmith.Campain.GetEndpoint(origin)) if ...
// Copyright 2018 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package launcher import ( "context" "chromiumos/tast/local/chrome" "chromiumos/tast/local/chrome/ash" "chromiumos/tast/local/chrome/uiauto" "chromiumos/tast/local/chro...
// Copyright 2020 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package policy import ( "context" "github.com/golang/protobuf/ptypes/empty" "google.golang.org/grpc" "chromiumos/tast/errors" "chromiumos/tast/local/chrome" pb "chro...
package function import ( "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/httptest" "testing" ) func TestParserCanParsePagesCount(t *testing.T) { testFileContent, err := ioutil.ReadFile("handler_test_page.html") if err != nil { t.Errorf(err.Error()) } mux := http.NewServeMux() mux.HandleFunc("/t...
/* * Copyright 2018, Oath Inc. * Licensed under the terms of the MIT license. See LICENSE file in the project root for terms. */ package util import ( "log" "time" ) func RetryOrPanicDefault(call func() (interface{}, error)) *interface{} { return RetryOrPanic(5, 1, call) } func RetryOrPanic(attempts int, slee...
package static import ( "context" "errors" "fmt" "sync" "github.com/upfluence/pkg/discovery/balancer" "github.com/upfluence/pkg/discovery/peer" "github.com/upfluence/pkg/discovery/resolver" ) var errNoPeer = errors.New("balancer/static: No Peer available") type Balancer struct { resolver resolver.Resolver ...
package channels import "testing" func BenchmarkMultiSend(b *testing.B) { for i := 0; i < b.N; i ++ { multiSend() } } func BenchmarkBlockSend(b *testing.B) { for i := 0; i < b.N; i ++ { blockSend() } }
// Copyright 2020 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package assistant import ( "context" "fmt" "strconv" "time" "chromiumos/tast/common/shillconst" "chromiumos/tast/errors" "chromiumos/tast/local/apps" "chromiumos/ta...
package service import "github.com/airdb/sls-default/internal/app/domain/valueobject" // IExchange is interface of bitcoin exchange type IExchange interface { GetUser() valueobject.User Ticker(p valueobject.Pair) valueobject.Ticker }
package main import "errors" func (s *Server) Do(request *ClientRequest, response *ClientResponse) error { return errors.New("Not yet implemented") } func (s *Server) AppendEntries(request *AppendEntriesRequest, response *AppendEntriesResponse) error { return errors.New("Not yet implemented") } func (s *Server) R...
package sysinfo import ( "io/ioutil" "os" "strings" ) // New returns a new SysInfo, using the filesystem to detect which features the kernel supports. func New(quiet bool) *SysInfo { sysInfo := &SysInfo{} sysInfo.IPv4ForwardingDisabled = !readProcBool("/proc/sys/net/ipv4/ip_forward") sysInfo.BridgeNfCallIptabl...
/* * Created on Wed Apr 24 2019 15:9:9 * Author: WuLC * EMail: liangchaowu5@gmail.com */ // dp, O(nlgn) time, O(n) space // next great element with TreeMap, but leetcode platform do not install this package import "github.com/emirpasic/gods/maps/treemap" func oddEvenJumps(A []int) int { n := len(A) m := treema...
package prompt import "github.com/AlecAivazis/survey/v2" func customPrompt(icons *survey.IconSet) { icons.Question.Text = ">" }
/* Copyright 2021 The KodeRover 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, s...
package utils import ( "crypto/rand" "crypto/sha256" "encoding/hex" "log" "github.com/gliderlabs/ssh" ) func Check(message string, err error) { if err != nil { log.Fatalln(message, " : ", err) } } func HexFingerprintSHA256(pubKey ssh.PublicKey) string { sha256sum := sha256.Sum256(pubKey.Marshal()) return...
// Copyright (C) 2021 Storj Labs, Inc. // See LICENSE for copying information. package main import ( "fmt" "os" "storj.io/common/version" ) func main() { versionstr, err := version.FromBuild("storj.io/common") if err != nil { fmt.Fprintln(os.Stderr, err.Error()) os.Exit(1) } fmt.Printf("%#v", versionstr...
package tyVpnServer import ( "crypto/tls" "fmt" "github.com/tachyon-protocol/udw/tyTls" "github.com/tachyon-protocol/udw/tyVpnProtocol" "github.com/tachyon-protocol/udw/tyVpnRouteServer/tyVpnRouteClient" "github.com/tachyon-protocol/udw/udwBinary" "github.com/tachyon-protocol/udw/udwBytes" "github.com/tachyon-...
package binary import ( "bytes" "encoding/binary" "github.com/woobest/network/codec" ) type binaryCodec struct { binary.ByteOrder } func (self *binaryCodec) Name() string { return "binary" } func (self *binaryCodec) Encode(msgObj interface{}) ([]byte, error) { buf := new(bytes.Buffer) err := binary.Write(bu...
package main import "fmt" var x int var y float64 var z int8 = -128 // -129 causes compile error func main() { x = 42 // x = 2.354 Causes compile error due to type mismatch y = 42.34534 fmt.Println(x, y, z) fmt.Printf("%T\n", x) fmt.Printf("%T\n", y) fmt.Printf("%T\n", z) }
package main import ( "github.com/astaxie/beego" _ "webserver/config" _ "webserver/prepare" _ "webserver/routers" _ "webserver/runbackend" ) func main() { beego.SetStaticPath("/static", "static") beego.SetStaticPath("/views", "views") beego.Run() }
package server import ( "io" "net" "github.com/sintell/mmo-server/packet" ) func noop() {} type DummyPacketHandler struct { HeadLength uint } func (dph DummyPacketHandler) ReadHead(c io.Reader) (uint, error) { return 0, nil } func (dph DummyPacketHandler) ReadBody(id uint, c io.Reader, pl *packet.PacketsList...
package exec import ( "fmt" "github.com/pkg/errors" "github.com/spf13/cobra" "path" "strings" cfg "github.com/cloudposse/atmos/pkg/config" "github.com/cloudposse/atmos/pkg/schema" s "github.com/cloudposse/atmos/pkg/stack" u "github.com/cloudposse/atmos/pkg/utils" ) // ExecuteValidateStacksCmd executes `vali...
package mongo import ( "github.com/I-Reven/Hexagonal/src/framework/logger" "github.com/go-bongo/bongo" "github.com/juju/errors" ) type Mongo struct { Log logger.Log } func (m *Mongo) Connection(config bongo.Config) *bongo.Connection { c, err := bongo.Connect(&config) if err != nil { err = errors.NewNotSuppo...
package graph import ( "context" "github.com/sebastianvera/ghreviews" "github.com/sebastianvera/ghreviews/pkg/graph/generated" "github.com/sirupsen/logrus" ) type Resolver struct { reviewService ghreviews.ReviewService logger *logrus.Logger hub *hub } func NewResolver(logger *logrus.Logger, ...
package main import ( "database/sql" "net/http" "time" permission "./permission/controller" task "./task/controller" user "./user/controller" "github.com/gin-gonic/gin" _ "github.com/go-sql-driver/mysql" ) func main() { router := gin.Default() dbConn, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:8...
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package policy import ( "context" "net/http" "net/http/httptest" "net/url" "path/filepath" "chromiumos/tast/common/fixture" "chromiumos/tast/common/pci" "chromiumos...
/* Copyright 2017 WALLIX 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 distribu...
package backTrack import ( "fmt" "testing" ) func TestCoinChangeElegant(t *testing.T) { var arr []int var minNum, amount int arr = []int{9, 1, 3, 5} arr = []int{2, 1, 4, 7} // arr = []int{90, 10, 30, 50} amount = 9 cce := NewCoinChangeElegant(arr, len(arr), amount) minNum = cce.getMinNum(amount) fmt.Pri...
package main import ( "fmt" "os" "os/user" "log" "time" "syscall" "github.com/olivere/elastic" ) func escConnect() *elastic.Client { if ( debug == true ) { log.Printf("Connecting to http://%v:%v ...\n", esIp, esPort) } var esUrl string esUrl = fmt.Sprintf("http:/...
package main import ( "encoding/base64" "fmt" "net/http" "os" "strconv" "syscall" "unsafe" "github.com/alexbrainman/sspi/ntlm" "golang.org/x/sys/windows" ) type HTTPNTLMNegotiator struct { Host string Port int Context *ntlm.ServerContext Chan chan NegotiatorResult Authe...
package main import ( "github.com/julienschmidt/httprouter" "net/http" "time" "github.com/urfave/negroni" "fmt" ) func main() { router := httprouter.New() router.POST("/test", func(writer http.ResponseWriter, request *http.Request, params httprouter.Params) { writer.Write([]byte("test")) }) router.POST("...
package dockerveth import ( "bytes" "context" "errors" "net" "strconv" "strings" "github.com/docker/docker/api/types" "github.com/docker/docker/client" "github.com/docker/docker/pkg/stdcopy" ) var ( ErrEmptyExecID = errors.New("empty exec id") ) // Client wrap docker client type Client struct { *client.C...
package cmd import ( "github.com/SennaSemakula/tfstate-lookup/pkg/terraform" "github.com/spf13/cobra" "log" "os" ) var ( account string bucketName string rootCmd = &cobra.Command{ Use: "tfstate-lookup", Short: "Check what terraform infra deployed on AWS", Long: `CLI tool to query what terraform r...
package fileutil import ( "testing" "github.com/stretchr/testify/assert" ) func TestIsFile(t *testing.T) { assert.Equal(t, true, IsFile("../../test/Readable.txt")) assert.Equal(t, true, IsFile("../../test/symbolic.txt")) assert.Equal(t, false, IsFile("../../test")) assert.Equal(t, true, IsFile("../../test/AllZ...
package main import ( "bufio" "fmt" "log" "os" "github.com/mochi8k/domain-name-generator/thesaurus" ) func main() { apiKey := os.Getenv("BHT_APIKEY") if apiKey == "" { log.Fatalln("please export BHT_APIKEY={your api key}") } thesaurus := &thesaurus.BigHuge{APIKey: apiKey} s := bufio.NewScanner(os.Stdin...
package goexec import ( "bufio" "io" "os" "os/exec" "strings" ) type cmd struct { c *exec.Cmd stdout chan string stderr chan string } type ExecCommand struct { } func (ExecCommand) Command(name string, args ...string) Command { return NewCommand(name, args...) } type Command interface { Start() error W...
// Copyright 2020 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package systemlogs calls autotestPrivate.writeSystemLogs and parses the results. package systemlogs import ( "context" "chromiumos/tast/errors" "chromiumos/tast/local...
package dm_event import ( eh "github.com/looplab/eventhorizon" ) const ( HealthEvent = eh.EventType("HealthEvent") InstPowerEvent = eh.EventType("InstPowerEvent") DataManagerEvent = eh.EventType("DataManagerEvent") FanEvent ...
package main import "fmt" //010 OMIT func onlyPositive(i int) { if i < 0 { panic(i) // Drop everything. Scream for help,yelling out "i"! } fmt.Printf("Thanks, I got %v.\n", i) } //020 OMIT func main() { defer func() { // HL if r := recover(); r != nil { fmt.Printf("Hmm, I heard someone yelling out '%v'!\n...
package main import ( "fmt" "io" "io/ioutil" "log" "net/http" "os" "strings" "time" "github.com/dutchcoders/go-clamd" ) var opts map[string]string func init() { log.SetOutput(ioutil.Discard) } func home(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "...running...") } //This is where the a...
package main import ( "encoding/json" "fmt" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "github.com/wano/buchiage" "io/ioutil" "log" "os" "os/signal" "sync" "syscall" ) func main() { if len(os.Args) < 2 { log.Println("must be specify config file.") os.Exit(1) } f,...
package factogo /* AfterPersist registers a callback, which is called after the Persist function is executed. AfterPersist receives the product Struct which should have been duly persisted using the Persist function. If any Persist function is registered or NotPersist() was called over the designed Factory, then the...
package utils import ( "fmt" "reflect" ) func ConvertParamType(v interface{}, targetType reflect.Type) ( targetValue reflect.Value, ok bool) { defer func() { if re := recover(); re != nil { ok = false fmt.Println(re) } }() ok = true if targetType.Kind() == reflect.Interface || targetType.Kind() =...
package view import ( caos_errs "github.com/caos/zitadel/internal/errors" global_model "github.com/caos/zitadel/internal/model" grant_model "github.com/caos/zitadel/internal/usergrant/model" "github.com/caos/zitadel/internal/usergrant/repository/view/model" "github.com/caos/zitadel/internal/view/repository" "git...
// Copyright (c) 2020 - for information on the respective copyright owner // see the NOTICE file and/or the repository at // https://github.com/hyperledger-labs/perun-node // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may...
package main import ( "context" "fmt" globalvariables "github.com/NeerajKomuravalli/dummy_workflow_handler_using_go_kafka_neo4j_redis/src/globalVariables" "github.com/NeerajKomuravalli/dummy_workflow_handler_using_go_kafka_neo4j_redis/src/models" neo4jmanager "github.com/NeerajKomuravalli/dummy_workflow_handler_...
package main import ( "fmt" "github.com/gin-gonic/gin" "github.com/oceanho/gw" "github.com/oceanho/gw/conf" "github.com/oceanho/gw/contrib/apps/tester" "github.com/oceanho/gw/logger" "strings" "time" ) func main() { bcs := conf.DefaultBootConfig() opts := gw.NewServerOption(bcs) opts.Name = "my-tester-api"...
// Copyright 2018 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package main import ( // "flag" "fmt" "github.com/sakthipriyan/go/queue" ) func main() { /* listen := flag.String("listen", "127.0.0.1:64001", "host:port") dir := flag.String("dir", "/tmp/go-queue/", "go queue directory") flag.Parse() queue.Serve(*listen, *dir) */ q,_ := queue.NewQueue("/tmp/queue/test3/url...
package Lecture01 //队列 数据结构 //节点 type QueueNode struct { Item interface{} Next *QueueNode } //队列结构体 type Queue struct { First *QueueNode Last *QueueNode Len int } //为空 func (Q *Queue) Isempty() bool { if Q.First == nil { return true } return false } //入队 func (Q *Queue) Push(item interface{}) { oldl...
package main import "testing" type tuple struct { n, m int } func TestLocks(t *testing.T) { for k, v := range map[tuple]int{ tuple{3, 1}: 2, tuple{100, 100}: 50, tuple{10, 10}: 5, tuple{10, 7}: 7} { if r := locks(k.n, k.m); r != v { t.Errorf("failed: locks %d %d is %d, got %d", k.n, k.m, ...
package main import ( twodee "../libs/twodee" "os" "sort" "strings" "time" ) func NewRain() *twodee.AnimatingEntity { return twodee.NewAnimatingEntity( 0, 0, 32.0/PxPerUnit, 32.0/PxPerUnit, 0, twodee.Step10Hz, []int{ 56, 57, 58, 59, 60, 61, 62, 64, 65, 66, 67, 68, 69, 70, }, ) } func NewWate...
package main import ( "fmt" "github.com/gin-gonic/gin" "log" "net/http" ) func main() { //1.创建路由 //默认使用两个中间件 Logger Recovery r := gin.Default() //r:gin.New() //2.绑定路由规则,执行函数 /** context param 方法获取 api 参数 */ r.GET("/gin", func(context *gin.Context) { context.String(http.StatusOK, "hello gin") }) r.GET...
package repo import ( "path/filepath" "testing" "github.com/pkg/errors" "github.com/izumin5210/scaffold/infra/fs" "github.com/izumin5210/scaffold/domain/scaffold" repotesting "github.com/izumin5210/scaffold/infra/scaffold/repo/testing" ) func Test_GetTemplates(t *testing.T) { ctx := repotesting.NewRepoTestC...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package ui import ( "context" "fmt" "time" "chromiumos/tast/errors" uiperf "chromiumos/tast/local/bundles/cros/ui/perf" "chromiumos/tast/local/chrome" "chromiumos/ta...