text
stringlengths
11
4.05M
package leetcode import "testing" func TestArrayPairSum(t *testing.T) { if arrayPairSum([]int{1, 4, 3, 2}) != 4 { t.Fatal() } }
package bigdigits import ( "fmt" "log" ) func BigDigits(stringOfDigits string) { for row := range bigDigits[0] { line := "" for column := range stringOfDigits { digit := stringOfDigits[column] - '0' if 0 <= digit && digit <= 9 { line += bigDigits[digit][row] + " " } else { log.Fatal("invalid ...
package main // ------------------------------- 基于快速排序的矩阵对角线排序 (原地排序) ------------------------------- func diagonalSort(mat [][]int) [][]int { if len(mat) == 0 { return [][]int{} } rows, cols := getRowsAndCols(mat) for i := 0; i < rows; i++ { leftX, leftY := i, 0 rightX, rightY := getRightXAndRightY(mat, lef...
package mdware import ( "bufio" "encoding/json" "fmt" "io/ioutil" "net" "net/http" "runtime" "strings" "sync/atomic" "time" "internal/ctxutil" "internal/gzippool" "internal/logger" ) /* Head(uuid) > Auth(auth) > Gzip() > Body() > Exec(API) > Resp() > Fail() > Tail(log) Head(Auth(Gzip(Body(Exec(Resp(Fa...
//go:build windows && amd64 // +build windows,amd64 package es import _ "embed" //go:embed Everything64.dll var everythingDll []byte var everythingMd5 = []byte("\xa1\xdd\xb6\x98\x1a\xc5\xe0\x80\x55\x4b\xd3\x84\xc8\x69\xf5\xf3")
package commands type Project struct { Name string }
package rest import ( mlog "github.com/jinmukeji/go-pkg/v2/log" ) var ( // log is the package global logger log = mlog.StandardLogger() )
package main import ( "fmt" ) // 96. 不同的二叉搜索树 // 给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种? // https://leetcode-cn.com/problems/unique-binary-search-trees/ func main() { fmt.Println(numTrees(3)) // 5 fmt.Println(numTrees2(3)) // 5 } type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // 类似题目注意是否包含空树...
/* Package ratecounter provides a thread-safe rate-counter, for tracking counts in an interval Useful for implementing counters and stats of 'requests-per-second' (for example). // We're recording events-per-1second counter := ratecounter.NewRateCounter(1 * time.Second) // Record an event happening counter.I...
package main import ( "fmt" "strconv" "github.com/dylandreimerink/gobpfld/ebpf" ) // IPv4Field descibes the properties of a IPv4 field type IPv4Field struct { offset int size int } // TODO convert IPv4Field to an interface and implement each field as a seperate struct. Reason for this is that // some fields ...
package commands import ( "context" "os" "os/signal" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/yunify/qscamel/constants" "github.com/yunify/qscamel/migrate" "github.com/yunify/qscamel/model" "github.com/yunify/qscamel/utils" ) var ( taskPath string ) // RunCmd will provide run com...
// 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 cmd import ( "errors" "strings" ) func GitStatusParse(status string) ([]string, error) { if status == "" { return nil, errors.New("status should not be blank") } statusList := strings.Split(status, "\n") var result []string for _, v := range statusList { if len(v) == 0 { continue } if len(v...
package cli import ( "strconv" "github.com/spf13/cobra" "github.com/spf13/cast" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/octalmage/gitgood/x/gitgood/types" ) func CmdCreateAchievement() *cobra.Command { cmd := &co...
package main import ( "fmt" "strconv" ) var sayCh = make(chan string, 300) var endCh = make(chan struct{}, 1) var intCh = make(chan int, 100) var exitCh = make(chan bool, 1) func main() { go WriteData(intCh) go ReadData(intCh) //for { select { case <-exitCh: return } //} // intCh <- 122 // fmt.Printl...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //55. Jump Game //Given an array of non-negative integers, you are initially positioned at the first index of the array. //Each element in the array re...
package main import ( "fmt" "golang.org/x/tour/tree" "reflect" "sync" ) // Walk walks the tree t // Sending all values from the tree to the channel ch. func Walk(t *tree.Tree, ch chan int) { walkTree(t, ch) defer close(ch) } func walkTree(t *tree.Tree, ch chan int) { // Walk the left side of the tree if t.L...
package main import ( "fmt" "io" "log" "os" "path/filepath" "runtime" "strconv" ) var dirCurrent, _ = os.Getwd() // Directory that the binary is in var dirResources = filepath.Join(dirCurrent, "resources") func main() { var choice int Clr() fmt.Println("Welcome to Grognak's Mod Patcher!") if !CheckSafet...
package service import ( "net/http" "github.com/gin-gonic/gin" "otoboni.com.br/customer-webservice/factory" "otoboni.com.br/customer-webservice/model" ) func GetCustomers(c *gin.Context) { var customers []model.Customer customers, err := factory.GetCustomer() if err != nil { c.JSON(http.StatusInternalSer...
package flagV import ( "flag" "fmt" ) // PrintFlags print all parsed flags func PrintFlags() { // prevent users from forgetting if !flag.Parsed() { flag.Parse() } visitor := func(a *flag.Flag) { fmt.Println("flag =", a.Name, "\t", " value =", a.Value, "\t", "default =", a.DefValue, "\t", a.Usage) } fmt....
package main import ( "fmt" "log" "os" "strconv" "github.com/uhuaha/game-of-life/grid" ) func main() { x, y, err := parseArguments() if err != nil { log.Fatalf("error: Cannot parse arguments: %v", err) } grid := grid.NewGrid(x, y) grid.Draw() // Calculate next five generations of the grid for i := 0; ...
package main import ( "fmt" "math/rand" "time" ) func main() { c := make(chan int) // チャネルを作成 callNum := 5 for i := 0; i < callNum; i++ { go sleepyGopher(i, c) // goroutine } for i := 0; i < callNum; i++ { gopherID := <-c // チャネルで値を受信 fmt.Println("gopher", gopherID, "はスリープを終えました。") } //time.Sleep...
package format import ( "github.com/plandem/xlsx/internal/ml/primitives" ) //List of all possible values for VAlignType const ( _ primitives.VAlignType = iota VAlignTop VAlignCenter VAlignBottom VAlignJustify VAlignDistributed ) func init() { primitives.FromVAlignType = map[primitives.VAlignType]string{ VA...
package rtrserver import ( "bytes" "encoding/binary" "errors" "github.com/cpusoft/goutil/belogs" "github.com/cpusoft/goutil/jsonutil" ) func ParseToAsa(buf *bytes.Reader, protocolVersion uint8) (rtrPduModel RtrPduModel, err error) { /* ProtocolVersion uint8 `json:"protocolVersion"` PduType uint8...
package main import "fmt" func main() { // **GOTO STATEMENT **// //the following piece of code creates a loop like a for statement does i := 0 loop: // label if i < 5 { fmt.Println(i) i++ goto loop } // goto todo //ERROR it's not permitted to jump over the declaration of x // x := 5 // todo: // fm...
package models type User2text struct { Userid *User `orm:"column(userid);rel(fk)"` Textid *Activity `orm:"column(textid);rel(fk)"` }
package main import ( "ethos/syscall" "ethos/altEthos" "ethos/kernelTypes" "log" ) type queueStruct struct { _type string FDValue syscall.Fd transactionID int64 variableName string variableValue string } var path = "/user/" + altEthos.GetUser() + "/server/" var pathTypeServer kernelTypes.String var logTyp...
package camt import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document05200101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:camt.052.001.01 Document"` Message *BankToCustomerAccountReportV01 `xml:"BkToCstmrAcctRptV01"` } func (d *Doc...
package caaa import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document01500103 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:caaa.015.001.03 Document"` Message *AcceptorRejectionV03 `xml:"AccptrRjctn"` } func (d *Document01500103) AddMessage() ...
package main import "fmt" func main() { // 1、bool 类型的默认值为 false var a bool fmt.Println("a = ", a) a = true fmt.Println("a = ", a) // 2、自动推导类型 var b = false fmt.Println("b = ", b) c := false fmt.Println("c = ", c) }
package type__test import ( "github.com/chaitya62/noobdb/tests/helpers" "github.com/chaitya62/noobdb/type" "testing" ) func TestVarchar(t *testing.T) { varchar := &type_.Varchar{} t.Run("Implements Type interface", func(t *testing.T) { _, ok := interface{}(varchar).(type_.Type) if ok != true { t.Errorf("...
package sharding import ( "tantan-demo/util" "tantan-demo/model" "fmt" ) func ListRelations(userId int) (model.Relations, error) { db, tableName := util.CaculateDbAndTable(userId) var relations model.Relations query := fmt.Sprintf("SELECT * FROM %s WHERE user_id = ?", tableName) _, err := db.Query(&relations, ...
package app import ( "fmt" "log" "net" "github.com/piotrpersona/saga/broker" "github.com/piotrpersona/saga/config" "github.com/piotrpersona/saga/order" "github.com/piotrpersona/saga/service" "google.golang.org/grpc" ) func createBroker(config config.Config, brokerName string) (b broker.Broker, err error) { ...
package RateLimiter type LimiterGroupOr struct { limiters []ILimiter } func NewLimiterGroupOr(limiters ...ILimiter) ILimiter { return &LimiterGroupOr{limiters: limiters} } func (l LimiterGroupOr) AddTally() bool { for _, ls := range l.limiters { if ls.TryAddTally() { return l.HasRemainingTally() } } if v...
// Copyright 2018 Kuei-chun Chen. All rights reserved. package mdb import ( "bufio" "bytes" "context" "errors" "fmt" "io/ioutil" "os" "path/filepath" "sort" "strings" "time" "github.com/simagix/gox" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mo...
package main import ( "fmt" "pribadi/reflect/library" "reflect" ) /* Reflect teknik untuk inspeksi sebuah variabel, mengambil informasi dari variabel tersebut atau bahkan memanipulasinya. Cakupan informasi yang bisa didapatkan lewat reflection sangat luas, seperti melihat struktur variabel, tipe, nilai pointe...
// Copyright (c) 2014-2015 José Carlos Nieto, https://menteslibres.net/xiam // // 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 righ...
package controller import ( "context" "image-clone-controller/pkg/utility" appsv1 "k8s.io/api/apps/v1" v1 "k8s.io/api/core/v1" v12 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-r...
// Copyright 2017 The LUCI 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...
// +build rpi package main import ( // Modules _ "github.com/djthorpe/gopi-hw/sys/gpio" _ "github.com/djthorpe/gopi-hw/sys/hw" _ "github.com/djthorpe/gopi-hw/sys/metrics" _ "github.com/djthorpe/gopi-hw/sys/spi" _ "github.com/djthorpe/gopi/sys/logger" _ "github.com/djthorpe/sensors/protocol/ook" _ "github.com/...
package template import ( "reflect" "testing" "github.com/AlecAivazis/survey" ) func TestNewTemplate(t *testing.T) { testCases := [...]struct { name string input string expected Template hasError bool }{ { name: "Basic Template", input: "test_fixture/basic", expected: Template{ ba...
package main import ( . "github.com/protosam/go-libnss" . "github.com/protosam/go-libnss/structs" ) // Placeholder main() stub is neccessary for compile. func main() {} func init(){ // We set our implementation to "TestImpl", so that go-libnss will use the methods we create SetImpl(TestImpl{}) } // We're creat...
package main import ( "fmt" "time" "github.com/tideland/golib/redis" ) var ( rds *redis.Database rdsCircularBuffer string rdsGetIPCache string rdsSetIPCache string ) // how many log lines to buffer for the scrollback const CHATLOGLINES = 150 func redisGetConn() *redi...
// All material is licensed under the Apache License Version 2.0, January 2004 // http://www.apache.org/licenses/LICENSE-2.0 // This program shows how to launch a web server then shut it down gracefully. package main import ( "context" "log" "math/rand" "net/http" "os" "os/signal" "time" ) // app is our appli...
package origin import ( "testing" "github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/address" "github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/address/signaturescheme" valuetransaction "github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/transaction" "github.com/iotaledger/gos...
package main import ( "context" "fmt" "log" "net" "net/http" pb "proto-example/pb" "strings" "github.com/grpc-ecosystem/grpc-gateway/runtime" "google.golang.org/grpc" "google.golang.org/grpc/metadata" ) const ( grpcAddress = 10000 httpAddress = 9000 ) type server struct { pb.UnimplementedAuthServer } ...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-08-16 13:16 # @File : buble_sort.go # @Description : # @Attention : */ package sort func BubbleSort(data []int) { for i := 0; i < len(data); i++ { for j := 0; j < len(data)-1-i; j++ { if data[j] > data[j+1] { data[j], data[j+1] = data[j+1], data[...
package main import ( "fmt" "os" "github.com/Cloud-Foundations/Dominator/imageserver/client" "github.com/Cloud-Foundations/Dominator/lib/log" ) func checkImageSubcommand(args []string, logger log.DebugLogger) error { imageSClient, _ := getClients() imageExists, err := client.CheckImage(imageSClient, args[0]) ...
package main /* #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys/ioctl.h> #include <unistd.h> #include <string.h> #include <netinet/in.h> #include <linux/if.h> #include <linux/if_tun.h> int tun_alloc(char *dev, int flags) { struct ifreq ifr; int fd, err; char *clonedev = "/dev/net/tun"; ...
package models import ( "GOLANG/entities" "crypto/sha256" "encoding/base64" "encoding/hex" "errors" ) var ( listUser = make([]*entities.User, 0) // make a slice with init len(listUser) = 0 ) func HashString(s string) string { h := sha256.New() h.Write([]byte(s)) sha256_hash := hex.EncodeToString(h.Sum(nil))...
// Implement atoi to convert a string to an integer. func myAtoi(str string) int { i, n := 0, len(str) if n == 0 { return 0 } c_space, c_0, c_9 := " "[0], int("0"[0]), int("9"[0]) for i < n && str[i] == c_space { i += 1 } first, signal, re := str[i], 1, 0 if first == '+'...
package telex import ( "strconv" ) type TelexParseError struct { err error line int context string } func (tpe TelexParseError) Error() string { return strconv.Itoa(tpe.line) + ": " + tpe.err.Error() + " While parsing: " + tpe.context }
package service import ( "fmt" "io/ioutil" "os" "reflect" "sort" "strings" e "sample.com/book/error" "sample.com/book/model" "sample.com/book/util" ) // closure function to represent true:1 and false:-1 // due to use in sorting of []Book var boolToInteger = func() func(bool) int { innerMap := map[bool]int{...
package main import "log" func myLog(format string, args ...interface{}) { const prefix = "[my]" log.Printf(prefix+format, args...) }
// Copyright The OpenTelemetry 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 ag...
package encio import ( "crypto/aes" "crypto/cipher" "fmt" "io/ioutil" "log" "os" ) func ExampleHello() { block, err := aes.NewCipher(make([]byte, 16)) if err != nil { log.Fatalf("Failed to make AES: %s", err) } aead, err := cipher.NewGCM(block) if err != nil { log.Fatalf("Failed to make AEAD: %s", err)...
package models import ( "testing" "github.com/google/go-cmp/cmp" ) func TestRenderCommitStatusTemplates(t *testing.T) { cases := []struct { name string inputTemplate CommitStatusTemplate inputData NotificationData expectedOutput *RenderedCommitStatus }{ { name: "No template variables...
// Package blockingreader implements an io.Reader that can block the first // read for an arbitrary amount of time. package blockingreader import ( "context" "errors" "io" "math/rand" "sync" "time" ) // BlockingReader is a reader that blocks on read calls until a receive // completes from a given channel. type ...
package 深度优先搜索 import "sort" func makesquare(nums []int) bool { sum := 0 for i := 0; i < len(nums); i++ { sum += nums[i] } if sum%4 != 0 || sum == 0 { return false } // 因为是形成4根,所以下面要传入 []int{0,0,0,0} return makeSequareExec(nums, []int{0, 0, 0, 0}) } // nums: 表示原数组 (DFS过程中不变) // le...
package routes import ( "controller" "reflect" "regexp" ) type Route struct { Regex *regexp.Regexp Methods map[string]string Params map[int]string ControllerType reflect.Type } type app interface { AddRoute(pattern string, m map[string]string, c controller.ControllerInterface) } func...
package crawler import ( "github.com/PuerkitoBio/goquery" "fmt" "log" "regexp" "strconv" ) type NovelContentType int type Novel struct { Tcode string `json:"tcode"` ContentList []NovelContent `json:"content_list"` } const ( // NovelContent Type Chapter NovelContentType = iota Sublis...
// Cobra commandline console driver package main import ( "fmt" "log" "os" "github.com/grrtrr/clcv2/examples/clconsole/cmd" "github.com/spf13/cobra" ) func main() { // Logging format - we don't need date/file log.SetFlags(log.Ltime) // Do sort the commands alphabetically cobra.EnableCommandSorting = true ...
package tls import ( "crypto/x509" "crypto/x509/pkix" "github.com/openshift/installer/pkg/asset" ) // RootCA contains the private key and the cert that acts as a certificate // authority, which is in turn really only used to generate a certificate // for the Machine Config Server. More in // https://docs.openshi...
/* Tencent is pleased to support the open source community by making Basic Service Configuration Platform available. Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain...
package web import ( "fmt" "log" "math/rand" "os" "os/exec" "time" ) func failOnError(err error, msg string) { if err != nil { log.Fatalf("%s: %s", msg, err) } } const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" func RandString(n uint8) string { buf := make([]byte, n) for i := range...
package main import "fmt" //接口 type Usb interface { //声明两个没有实现的接口的方法 Start() Stop() //Test方法,Phone,Camer都没有实现,如果再用Phone去调用接口的方法,将会报错 //Test() } type Phone struct { } //结构体Phone实现Usb接口的方法,Phone感觉不到实现了Usb接口,所有不存在显式实现 func (p Phone) Start() { fmt.Println("Phone start.......") } func (p Phone) Stop() { fmt.Printl...
package eod import ( _ "embed" "strings" "sync" eodb "github.com/Nv7-Github/Nv7Haven/db" "github.com/Nv7-Github/Nv7Haven/eod/base" "github.com/Nv7-Github/Nv7Haven/eod/basecmds" "github.com/Nv7-Github/Nv7Haven/eod/categories" "github.com/Nv7-Github/Nv7Haven/eod/elements" "github.com/Nv7-Github/Nv7Haven/eod/po...
package graph // 图的连通分量 // 引用interface{},充当泛型 type I interface { VersNum() int EdgeNum() int AddEdge(v1, v2 int) //hasEdge(v1, v2 int) bool AdjVertexs(v int) (slice []int) } type Component struct { graph I // 图 visited []bool // 节点是否被访问过 ccount int // 连通分量个数 id []int // 两节点相连:id相同 } func N...
package main import "fmt" const ( _ = iota alcool gasolina diesel fim ) var nomes = []string{" ", "Alcool", "Gasolina", "Diesel"} func main() { var escolha int var qntd [4]int for { fmt.Scanf("%d", &escolha) if escolha < 1 || escolha > 4 { continue } else if escolha == fim { break } switc...
/** * @Author: DollarKiller * @Description: * @Github: https://github.com/dollarkillerx * @Date: Create in 23:05 2019-09-17 */ package config import ( "gopkg.in/yaml.v2" "io/ioutil" ) type basisConf struct { App struct { Corn string `yaml:"corn"` Email string `yaml:"email"` } Mysql struct { Dsn...
package main import ( "fmt" "io" "log" "net" "os" "os/exec" "os/signal" "syscall" "github.com/creack/pty" ) func handleConn(conn net.Conn) { ptmx, tty, _ := pty.Open() // Handle pty size. 否则类似于 htop 的命令,图像界面就无法正常显示 ch := make(chan os.Signal, 1) signal.Notify(ch, syscall.SIGWINCH) go func() { for ran...
// Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Elasticsearch B.V. licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use ...
// Note: the example only works with the code within the same release/branch. package others import ( "context" "flag" "fmt" "k8s.io/apimachinery/pkg/fields" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/informers" "k8s.io/client-...
func countPrimes(n int) int { return sol1(n) } // time: O(?), space: O(n) func sol1(n int) int { if n < 2 { return 0 } nums := make([]bool, n) nums[0] = true nums[1] = true for i := 2; i*i < n; i++ { if nums[i] == true { continue } for j := i*i; j...
package main import ( "github.com/lnhote/hello-thrift/gen-go/bill" "git.apache.org/thrift.git/lib/go/thrift" "log" "fmt" "os" "context" ) const ( NetworkAddr = "127.0.0.1:9090" ) type BillImpl struct { } func (b *BillImpl) GetBillList(ctx context.Context, userID string) ([]*bill.BillInfo, error) { bills := ...
package spa import ( "errors" "os" ) type Config struct { SPADirectory string NPMScript string } var ( defaultScript = "start" ) func (c *Config) validate() error { if _, err := os.Stat(c.SPADirectory); os.IsNotExist(err) { return errors.New("spa directory does not exist") } return nil } func newConfi...
//go:build go1.21 // +build go1.21 package log import ( "context" runtimeext "github.com/go-playground/pkg/v5/runtime" "log/slog" "runtime" ) var _ slog.Handler = (*slogHandler)(nil) type slogHandler struct { // List of Groups, each subsequent group belongs to the previous group, except the first // which are...
package state import "errors" // Process switches on operation type // Then does work func Process(wr *WorkRequest) *WorkResponse { resp := WorkResponse{Wr: wr} switch wr.Operation { case Add: resp.Result = wr.Value1 + wr.Value2 case Subtract: resp.Result = wr.Value1 - wr.Value2 case Multiply: resp.Result...
package mockgen import ( "fmt" "testing" gomock "github.com/golang/mock/gomock" mock_mockgen "github.com/mitooos/thesis/mockgen/mocks" "github.com/mitooos/thesis/mockgen/model" ) func TestInsertUser(t *testing.T) { t.Run("inserts user succesfully", func(t *testing.T) { usr := &model.User{ Email: "email...
package config import ( "testing" "github.com/stretchr/testify/assert" ) func TestConfig(t *testing.T) { conf, err := NewConfiguration("config", "..") assert.NoError(t, err) t.Log(conf) }
package solution_test import ( "testing" "github.com/dnogueir/golang-dojo/solution" "github.com/stretchr/testify/require" ) func TestSolution(t *testing.T) { sum := solution.Multi_threaded() require.Equal(t, 319600, sum) }
package boshio_test import ( "errors" "io/ioutil" "net/http" "net/http/httptest" "strings" "time" "github.com/concourse/bosh-io-stemcell-resource/boshio" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) type tempError struct { error } func (te tempError) Temporary() bool { return true } func (te...
package cfglite import ( "bufio" "os" "strings" ) type smplConfStruct struct { cfgPath string params map[string]string } func ReadConf(path string) (*smplConfStruct, error) { var config = new(smplConfStruct) cfgFile, err := os.Open(path) if err != nil { return config, nil } defer cfgFile.Close() confi...
package parsing import ( "github.com/s2gatev/sqlmorph/ast" ) const UpdateWithoutTargetError = "UPDATE statement must be followed by a target class." // UpdateState parses UPDATE SQL clauses along with the target table. // UPDATE User u ... type UpdateState struct { BaseState } func (s *UpdateState) Name() string ...
package SLB import ( "fmt" "testing" ) func TestRandom(t *testing.T) { nodes := make(map[int]string) nodes[0] = "0" nodes[1] = "1" nodes[2] = "2" res := make(map[string]int) for i :=0; i < 10; i++ { node := Random(nodes) if _, ok := res[node]; ok { res[node] += 1 } else { res[node] = 1 } } for...
/* Copyright (C) 2018 Expedia Group. 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 ...
package entity import ( "bytes" "fmt" "io" "strings" // "io/ioutil" "github.com/fabric-lab/hyperledger-fabric-manager/server/pkg/client" "github.com/fabric-lab/hyperledger-fabric-manager/server/pkg/util" "os" "os/exec" "path/filepath" "strconv" ) const ( ALLINFO = iota OUTINFO ERRINFO ) type CMD interf...
package dependency import ( "context" "errors" "log" "net" "net/http" "os" "cloud.google.com/go/firestore" "github.com/99designs/gqlgen/graphql" "github.com/99designs/gqlgen/graphql/handler" "github.com/99designs/gqlgen/graphql/playground" "github.com/dwaynelavon/es-loyalty-program/config" "github.com/dwa...
package recurring import ( mgo "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "time" ) const ( MONGO_URL = "localhost" ) type DB struct { coll *mgo.Collection } type KeyValue struct { Key string Value interface{} } func ConnectDB(dbName, collectionName string) *DB { sess, err := mgo.Dial(MONGO_URL) if ...
package get import ( "errors" "os" "os/exec" "path/filepath" "strings" . "github.com/xeha-gmbh/homelab/shared" "github.com/spf13/cobra" ) const ( flagFlavor = "flavor" flagTargetDir = "target-dir" flagReuse = "reuse" defaultTargetDir = "/tmp" defaultReuse = false flavorUbuntuBionic64Live ...
package compatibility import ( "fmt" "strings" "time" "github.com/gruntwork-io/terratest/modules/helm" "github.com/gruntwork-io/terratest/modules/k8s" "github.com/gruntwork-io/terratest/modules/random" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/kumahq/kuma/pkg/config/core" . "github....
package version // Base version information. // // This is the fallback data used when version information from git is not // provided via go ldflags. var ( version = "dev" commit = "none" buildDate = "unknown" )
// Copyright 2022 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 g2gin import ( "github.com/gin-gonic/gin" "github.com/atcharles/gof/v2/j2rpc" ) // ItfGinRouter ...gin router interface type ItfGinRouter interface { Router(g *gin.RouterGroup) J2rpc(jsv j2rpc.RPCServer) }
package main import ( "fmt" "html/template" "io/ioutil" "net/http" ) type myMux struct { } func (m myMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/" { myHello(w, r) } } func myHello(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello vegetable540") fmt.Println(r.U...
package main import ( "bufio" "fmt" "net/http" "os" "strings" "github.com/gorilla/websocket" "github.com/mrWinston/knuffon/backend/manager" log "github.com/sirupsen/logrus" ) func readStdinLine(question string) (string, error) { reader := bufio.NewReader(os.Stdin) fmt.Println(question) read, err := reade...
package main /** 95. 不同的二叉搜索树 II 给定一个整数 n,生成所有由 1 ... n 为节点所组成的 二叉搜索树 。 示例1: ``` 输入:3 输出: [   [1,null,3,2],   [3,2,null,1],   [3,1,null,null,2],   [2,1,3],   [1,null,2,null,3] ] 解释: 以上的输出对应以下 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 ...
package kata import ("fmt" // "strings" ) func CreatePhoneNumber(numbers [10]uint) string { result:="(" for i:=0;i<10;i++{ str := fmt.Sprint(numbers[i]) result+=str if(i==2){ result+=") " } if(i==5){ result+="-" } } // result = strings.Replace(result, " ", "", -1...
package function import ( "fmt" ) // ErrFunctionNotFound occurs when function couldn't been found in the discovery. type ErrFunctionNotFound struct { ID ID } func (e ErrFunctionNotFound) Error() string { return fmt.Sprintf("Function %q not found.", string(e.ID)) } // ErrFunctionAlreadyRegistered occurs when func...
//go:build amd64 || arm64 // +build amd64 arm64 package as_test import ( "math" "testing" "github.com/lunemec/as" ) func TestInt16(t *testing.T) { assertNoError(t, as.Int16, int8(math.MinInt8)) assertNoError(t, as.Int16, int8(math.MaxInt8)) pointerToMaxInt8 := int8(math.MaxInt8) assertNoError(t, as.Int, &poi...