text
stringlengths
11
4.05M
package main import "fmt" type User struct { Name string Pets []string } func (u *User) newPet() { u.Pets = append(u.Pets, "Lucy") fmt.Println(u) } func main() { u := &User{Name: "Anna", Pets: []string{"Bailey"}} u.newPet() fmt.Println(u) var age int = 20 var sex string = "male" fmt.Printf("The person is...
package web import ( "time" ) // Status is the structure returned by the status API endpoint. type Status struct { Status ControllerStatus `json:"status"` Devices []*DeviceInfo `json:"devices,omitempty"` } // ControllerStatus provides the current state of the Controller. type ControllerStatus struct { // If ...
package models import ( "strings" ) var ( ServerURL string Minutes int IgnorAppName string IsOne bool IsThree bool IsFive bool IsSlow bool IsError bool OneSum int64 ThreeSum int64 FiveSum int64 SlowSum int64 ErrorSum int64 LogLevel string...
package runner import ( "fmt" "time" ) // Limit represents the resource limit for traced process type Limit struct { TimeLimit time.Duration // user CPU time limit (in ns) MemoryLimit Size // user memory limit (in bytes) } func (l Limit) String() string { return fmt.Sprintf("Limit[Time=%v, Memory=%v]...
package e2e import ( "bytes" "encoding/json" "fmt" "net/http" "path/filepath" "testing" "time" "github.com/sensu/sensu-go/testing/testutil" "github.com/sensu/sensu-go/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) type eventsTest struct { bep *backendProcess cle...
package main import ( "errors" "fmt" "log" "os" "github.com/truggeri/go-sudoku/cmd/go-sudoku/input" "github.com/truggeri/go-sudoku/cmd/go-sudoku/solver" ) func main() { if err := run(); err != nil { log.Println("error :", err) os.Exit(1) } } func run() error { argsWithoutProg := os.Args[1:] if len(arg...
package mysql import ( "errors" "log" entity_book "my-app/domain/entity/book" myerror "my-app/error" "regexp" "strconv" "testing" "github.com/DATA-DOG/go-sqlmock" "github.com/jinzhu/gorm" "github.com/stretchr/testify/assert" ) func OpenTestDB() (Database, sqlmock.Sqlmock, func()) { mdb, mock, err := sqlmo...
package house import ( "testing" ) var WinnerBids []Auction func TestWinnerBid(t *testing.T) { var WinnerBids []Auction for i, item := range sellItemsTest { WinnerBids = append(WinnerBids, WinnerBid(item, bidsTest)) // check received price if WinnerBids[i].Status != itemStatsTests[i].status { t.Fatalf...
package importer import ( "fmt" "io" "os" "path" "path/filepath" "strconv" "strings" "sync" "github.com/DexterLB/mvm/library" "github.com/DexterLB/mvm/types" "github.com/DexterLB/osdb" ) // SubtitleDownloader downloads subtitles for each file, using information // from its associated show. func (c *Contex...
package main import ( "fmt" "bufio" "flag" "os" "sync" "crypto/tls" "net" "net/http" "net/url" "time" "strings" "io/ioutil" "regexp" ) func init() { flag.Usage = func() { h := []string{ "", "Urlive (Check url is live *HTTP status code \"200 ok\" only)", "", "By : viloid [Sec7or - Surabaya...
package main import ( "crypto/tls" "flag" "fmt" "log" "net/http" ) var ( addrFlag = flag.String("addr", ":5555", "server address:port") ) func main() { flag.Parse() cert, err := tls.X509KeyPair(serverCert, serverKey) if err != nil { log.Fatal(err) } cfg := &tls.Config{ Certificates: []tls.Certificat...
package main import ( "errors" "strings" ) type userRequest struct { Requestor string Target string } func (u userRequest) subscribeUpdates() error { if u.Requestor == "" { return errors.New("no requestor was provided") } if u.Target == "" { return errors.New("no target was provided") } requestor :=...
package graphql import ( "errors" "fmt" "regexp" "strings" ) var reLegalFields = regexp.MustCompile(`(ID|String|Int|Float|Boolean|AWS(Date(Time)?|Time(stamp)?|Email|URL|Phone|IPAddress|JSON))`) const defaultFieldType = "String" // Custom errors var ( ErrFieldHasNoName = errors.New("fields must have ...
/* * Copyright (c) 2020 - present Kurtosis Technologies LLC. * All Rights Reserved. */ package testsuite import ( "github.com/palantir/stacktrace" "testing" ) func TestFatalOnError(t *testing.T) { defer func() { if r := recover(); r == nil { t.Fatal("The code did not panic when it should") } }() TestC...
// Copyright 2023 Google LLC. 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applica...
package config import ( "fmt" "gopkg.in/yaml.v2" "io/ioutil" "learning_notes/app/utils" ) type Config struct { Env string Development AppConfig Production AppConfig } type AppConfig struct { Mysql Redis } type Mysql struct { DbType string `yaml:"dbType"` DbName string `yaml:"dbName"` User ...
package handlers import ( "encoding/json" t "github.com/button-tech/gram-testnet/wrappers/types" "github.com/gin-gonic/gin" "github.com/imroc/req" "io" "io/ioutil" "net/http" "os" "os/exec" "strconv" "strings" ) var ( // workdir in docker container workdir = os.Getenv("WORKDIR") header = req.Header{ ...
package main // mainパッケージであることを宣言 import ( "context" "fmt" // fmtモジュールをインポート "log" firebase "firebase.google.com/go" "firebase.google.com/go/messaging" ) func sendToToken(app *firebase.App) { ctx := context.Background() client, err := app.Messaging(ctx) if err != nil { log.Fatalf("error getting Messaging c...
package azblob import ( "context" "github.com/Xuanwo/storage" "github.com/Xuanwo/storage/types" "github.com/Xuanwo/storage/types/pairs" "github.com/yunify/qscamel/constants" "github.com/yunify/qscamel/model" ) // List implement source.List func (c *Client) List(ctx context.Context, j *model.DirectoryObject, fn...
package rtutils import ( "bytes" "fmt" "io" ) // InAny of the arguments, a string "e" we expect. func InAny(e string, args ...string) bool { for _, a := range args { if a == e { return true } } return false } func RCloser2String(stream io.ReadCloser) string { buf := new(bytes.Buffer) if _, err := buf....
package main import ( "fmt" "strings" ) func getDatabaseCommands(desiredList []string, currentList []string) ([]string, []string) { var createDatabaseCommands []string var deleteDatabaseCommands []string if len(currentList) == 0 { createDatabaseCommands = getCreateDatabaseCommands(desir...
package controllers import ( "Users/pingjing/docker/goPractice/owning/app/model" "encoding/json" "net/http" "github.com/gorilla/mux" "go.mongodb.org/mongo-driver/bson" ) func GetProducts(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() w.Header().Set("Content-Type", "application/json") model ...
package service import ( "net/http" "time" "github.com/ONSdigital/dp-api-clients-go/v2/health" "github.com/ONSdigital/dp-healthcheck/healthcheck" dphttp "github.com/ONSdigital/dp-net/v2/http" "github.com/ONSdigital/florence/config" ) // ExternalServiceList holds the initialiser and initialisation state of exte...
package scanner import ( "strings" "time" ) const ( // ScannerAddScanEndpoint is a string representation of the current endpoint for scanner add scan ScannerAddScanEndpoint = "v1/scanner/addScanResult" // ScannerGetProjectsStates is a string representation of the current endpoint getting requested projects scan ...
// // Copyright (c) 2017, Stardog Union. <http://stardog.com> // // 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 b...
package divide_conquer import ( "fmt" "testing" ) func Test_findKthLargest(t *testing.T) { res := findKthLargest([]int{3, 2, 3, 1, 2, 4, 5, 5, 6}, 4) fmt.Println(res) }
package post import ( "golang-demo/api/common" "golang-demo/api/user" "io" "net/http" "os" "strconv" "time" "github.com/gorilla/mux" ) func AddPost(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) var userID = vars["id"] var postImageName string postContent := r.FormValue("postContent") f...
package lang import ( "fmt" "testing" ) func Test_initB(t *testing.T) { var b = B{b: 2, A: A{a: 3}} fmt.Println("b value ", b.A.a, b.b) }
package main import ( "strings" "encoding/json" "os" "net" "fmt" ) //use weberr/(isDebug,config) //use dispatcher/(start,stop) //provide TcpCtrlServer type TcpCtrlMessageProcess struct { Command []string `json:"comand"` State string `json:"state"` } type TcpCtrlMessageUser map[string]TcpCtrlMessageProc...
package main import ( "fmt" "github.com/hoisie/web" "net" "os" "strings" ) func getFaces(host string) string { var ifaces []string addrs, _ := net.LookupIP(host) for _, addr := range addrs { if ipv4 := addr.To4(); ipv4 != nil { ifaces = append(ifaces, fmt.Sprintf("\tIPv4: %s\n", ipv4)) } } return str...
package main import ( "context" "fmt" "log" "net" "strings" "time" _ "github.com/lib/pq" "github.com/joho/godotenv" "github.com/mcculleydj/currency-trader/exchange/pkg/common" "github.com/mcculleydj/currency-trader/exchange/pkg/proto" "github.com/mcculleydj/currency-trader/exchange/pkg/rates" "github.com...
package vault import ( "encoding/json" "errors" "io" "os" "sync" "github.com/balaji-dongare/gophercises/secret/cipher" ) // Vault struct for store keys type Vault struct { encodingKey string filepath string mutex sync.Mutex keyValues map[string]string } // GetVault get vault struct func GetVau...
package constant const ConstantExample = "Contoh Wow" const ( StatusSuccess = "Success" MessageSuccess = "Berhasil Insert Data" )
package main import ( "math" "os" "testing" ) func Test_InterpeterPure(t *testing.T) { // testing functionality that doesn't involve i/o t.Run("single cell ops", func(t *testing.T) { cases := []struct { in string expected uint64 }{ {"+++", 3}, {"----", math.MaxUint64 - 4}, } for _, t...
package rand import ( "github.com/vlorc/lua-vm/base" "math/rand" "time" ) type RandFactory struct{} var __rand = rand.New(rand.NewSource(time.Now().UnixNano())) func (RandFactory) New(seed int64) *rand.Rand { return rand.New(rand.NewSource(seed)) } func (RandFactory) Shuffle(n int, swap func(i, j int)) { __ra...
package main import ( "bufio" "bytes" "io" "io/ioutil" "net/http" "github.com/Shopify/toxiproxy/stream" "github.com/Shopify/toxiproxy/toxics" ) type HttpResponseToxic struct { HttpBody string `json:"body"` HttpStatusCode int `json:"code"` HttpStatusText string `json:"status"` } func (t *HttpRespo...
package schema import ( "themis/models" ) func createWorkItemTypeTask() models.WorkItemType { workItemType := models.NewWorkItemType() workItemType.RefID = "task" workItemType.Name = "Task" workItemType.Description = "A story task." workItemType.Version = 0 workItemType.Icon = "fa fa-bolt" workItemType.Fields...
package intercom import ( "testing" "github.com/pborman/uuid" ) func TestContactFindByID(t *testing.T) { contact, _ := (&ContactService{Repository: TestContactAPI{t: t}}).FindByID("46adad3f09126dca") if contact.ID != "46adad3f09126dca" { t.Errorf("Contact not found") } } func TestContactFindByUserID(t *testi...
// Package rados provides Go bindings for the CEPH RADOS client library (librados) // We attempt to adhere to the style of the Go OS package as much as possible // (for example, our Object type implements the FileStat and ReaderAt/WriterAt // interfaces). package rados /* #cgo LDFLAGS: -lrados #include "stdlib.h" #inc...
// Copyright Amazon.com Inc. or its affiliates. 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. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file ...
package handler import ( "encoding/json" "encoding/xml" "errors" "io/ioutil" "net/http" "regexp" "strings" ) // AtomLink Type type AtomLink struct { XMLName xml.Name `xml:"atom-link" json:"-"` HREF string `xml:"href,attr" json:"href"` Rel string `xml:"rel,attr" json:"rel"` Type string `xml:...
// Skeleton to part 7 of the Whispering Gophers code lab. // // This program extends part 6 by adding a Peers type. // The rest of the code is left as-is, so functionally there is no change. // // However we have added a peers_test.go file, so that running // go test // from the package directory will test your imple...
package main import ( "fmt" "strings" ) // 290. 单词规律 // 给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。 // 这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。 // 示例1: // 输入: pattern = "abba", str = "dog cat cat dog" // 输出: true // 说明: // 你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。 // https://leetcode-cn.co...
package main import ( "database/sql" "encoding/json" "fmt" "log" "os" _ "github.com/lib/pq" ) func getDbConn() string { var connStr string connStr = os.Getenv("POSTGRES_CONNECTION") if connStr == "" { log.Fatal("DB connection not configured") } return connStr } func dbInit() { db, err := sql.Open("p...
// Copyright 2021 Google LLC. 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applica...
package proto import ( "errors" "github.com/gholt/store" ) func TranslateError(err error) string { if store.IsDisabled(err) { return "::github.com/gholt/store/ErrDisabled::" } else if store.IsNotFound(err) { return "::github.com/gholt/store/ErrNotFound::" } return err.Error() } func TranslateErrorString(e...
package handler import ( "context" "errors" "fmt" "strconv" "time" "github.com/golang/protobuf/ptypes" "github.com/jinmukeji/go-pkg/v2/mac" "github.com/jinmukeji/jiujiantang-services/device/mysqldb" proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/device/v1" ) // UserGetUsedDevices 用户使用过的设备 f...
package sockguard import ( "bytes" "encoding/json" "errors" "fmt" "io/ioutil" "log" "net/http" "path" "path/filepath" "regexp" "strings" "github.com/buildkite/sockguard/socketproxy" ) const ( apiVersion = "1.32" ownerKey = "com.buildkite.sockguard.owner" ) var ( versionRegex = regexp.MustCompile(`^...
package controllers import ( "app/base/core" "app/base/database" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func TestHealthRoute(t *testing.T) { core.SetupTestEnvironment() w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/", nil) initRouter(HealthHandler)....
package main func main() { for i := 1; i <= 100; i++ { print(i) if isEvenNum(i) { println("-偶数") } else { println("-奇数") } } } func isEvenNum(n int) bool { return (n % 2) == 0 }
package query import ( "reflect" "testing" ) func TestStringToQuery(t *testing.T) { rawString := "a[aa]=11&a[ab]=12&c=3" query, err := StringToQuery(rawString) if err != nil { t.Errorf("stringToQuery failed: %s", err.Error()) } expectedQuery := map[string]interface{}{ "a": map[string]interface{}{ "aa":...
package virtualbox import ( "archive/tar" "bufio" "bytes" "fmt" "io/ioutil" "net" "os" "path/filepath" "runtime" "strconv" "strings" "time" "github.com/boot2docker/boot2docker-cli/driver" flag "github.com/ogier/pflag" ) type Flag int // Flag names in lowercases to be consistent with VBoxManage options...
/* * Copyright © 2018-2022 Software AG, Darmstadt, Germany and/or its licensors * * SPDX-License-Identifier: Apache-2.0 * * 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://...
package util import ( "bytes" "crypto/cipher" "crypto/sm4" "errors" "fmt" ) //SM4加密 func SM4Encrypt(key, origData []byte) ([]byte, error) { block, err := sm4.NewCipher(key) if err != nil { fmt.Println(err) } origData = PKCS7Padding(origData) blockMode := cipher.NewCBCEncrypter(block, key) encrypted := ma...
package controllers import ( "github.com/go-pg/pg" "github.com/go-pg/pg/orm" "github.com/goadesign/goa" "github.com/odiak/MoneyForest/app" "github.com/odiak/MoneyForest/store" "github.com/odiak/MoneyForest/util" ) // UserController implements the user resource. type UserController struct { *CommonController d...
package game const ( bulletSpeed = 500 ) type Bullet struct { *Sprite } func newBullet(x, y, rot float32) *Bullet { vectorx := sin(rot) vectory := -cos(rot) bullet := &Bullet{} bullet.Sprite = NewSprite(bullet, "bullet", x+(vectorx*10), y+(vectory*10), 1, []float32{ -1, 0, 1, 0, }, false) bullet.ro...
package service import ( "context" "net/http" "github.com/go-ocf/cloud/http-gateway/uri" "github.com/go-ocf/kit/codec/json" "github.com/go-ocf/kit/log" kitNetCoap "github.com/go-ocf/kit/net/coap" kitNetGrpc "github.com/go-ocf/kit/net/grpc" "github.com/gorilla/mux" "github.com/gorilla/websocket" ) func (requ...
// Package browser contains mocked Executor implementations for the use in unit tests. package browser import ( "context" "github.com/chromedp/chromedp" "github.com/stretchr/testify/mock" ) // TestExecutor implements the Executor interface and can be used in tests as a // testify mock object. type TestExecutor st...
package suboption // Suboption is a single byte type Suboption uint8 // All suboptions const ( MACAddress Suboption = 0x01 IPParameter Suboption = 0x02 FullIPSuite Suboption = 0x03 ManufacturerSpecific Suboption = 0x01 NameOfStation Suboption = 0x02 DeviceID Suboption = 0x03 DeviceRole ...
package cmd import ( "fmt" "os" "time" "github.com/dkorittki/loago/pkg/instructor/config" "github.com/rs/zerolog" "github.com/spf13/cobra" ) var ( cfgFile string instructorCfg *config.InstructorConfig logger = zerolog.New( zerolog.ConsoleWriter{ Out: os.Stdout, TimeFormat: time.R...
package pie import ( "fmt" "time" ) type Company struct { Id int `json:"id"` GroupId int `json:"group_id"` Domain string `json:"domain"` Logo string `json:"logo"` Name string `json:"name"` CreatedAt time.Time `json:"created_at"` } func buildCompanyRequest(id int, token string) *request { return &req...
package main import ( "testing" "io/ioutil" "os" ) func TestGetKeyFromFile(t *testing.T) { var data []byte fileName := "./test/test_getKeyFromFile.txt" data = []byte("KEY: abc123") err := ioutil.WriteFile(fileName, data, 0644) if err != nil { panic(err) } file, err := os.Open(fileName) if err !=...
package controllers import ( "encoding/json" "github.com/kataras/iris/context" "gocherry-api-gateway/admin/models" "gocherry-api-gateway/components/common_enum" "gocherry-api-gateway/components/etcd_client" "gocherry-api-gateway/components/utils" ) type APiSaveReq struct { AppName string `json:"app_name"` ...
package queue import ( "encoding/json" "strconv" "time" "github.com/steam-authority/steam-authority/db" "github.com/steam-authority/steam-authority/helpers" "github.com/steam-authority/steam-authority/logging" "github.com/streadway/amqp" ) type RabbitMessageProfile struct { Time time.Time PlayerID int64...
package readers import ( "fmt" "io" "io/ioutil" "os" ) func UploadFileUsingTempFile(file io.Reader) (err error) { // 在当前目录下创建临时文件 f, err := ioutil.TempFile(".", "upload") // f: *os.File if err != nil { return err } // 调度移除临时文件 defer func() { filename := f.Name() f.Close() fmt.Printf("REMOVE file[%s...
package main import ( "github.com/bddbnet/gospy/config" "github.com/bddbnet/gospy/engine" "github.com/bddbnet/gospy/fetcher" "github.com/bddbnet/gospy/parser/h.bilibili.com" "github.com/bddbnet/gospy/persist" "github.com/bddbnet/gospy/scheduler" ) func main() { //url := "https://api.vc.bilibili.com/link_draw/...
package io import ( . "github.com/zxh0/jvm.go/jvmgo/any" "github.com/zxh0/jvm.go/jvmgo/jvm/rtda" rtc "github.com/zxh0/jvm.go/jvmgo/jvm/rtda/class" ) func init() { _fd(fd_set, "set", "(I)J") } func _fd(method Any, name, desc string) { rtc.RegisterNativeMethod("java/io/FileDescriptor", name, desc, method) } func...
package handler import ( "context" "errors" "path/filepath" "testing" proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/user/v1" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) // UserSetSecureQuestionsTestSuite 用户设置密保问题测试 type UserSetSecureQuestionsTestSuite struct { ...
package main import ( "flag" "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" ) // The fields we want to capture for writing out to the // config file type configData struct { keyName string h...
// Copyright 2020 Google Inc. 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
package ticket import ( "encoding/json" "github.com/bitmaelum/bitmaelum-suite/internal/config" "github.com/bitmaelum/bitmaelum-suite/pkg/address" pow "github.com/bitmaelum/bitmaelum-suite/pkg/proofofwork" "github.com/google/uuid" ) // TicketHeader is the HTTP Header that contains our ticket ID const TicketHeader...
package main import ( "fmt" "ms/sun/servises/file_service/file_common" "ms/sun/shared/x" ) func main() { p:=x.PostMedia{ MediaId: 1525756746191010004, UserId: 0, PostId: 0, AlbumId: 0, MediaTypeEnum: 0, Width: 400, Height: 0, Size: 0, ...
package service import ( "fmt" "kz.nitec.digidocs.pcr/internal/config" "kz.nitec.digidocs.pcr/internal/models" "kz.nitec.digidocs.pcr/internal/repository" "kz.nitec.digidocs.pcr/pkg/logger" "time" ) type BuildService struct { repo repository.BuildServiceRepo conf *config.Services } func newBuildService(repo ...
package osbuild2 import ( "testing" "github.com/stretchr/testify/assert" ) func TestNewScriptStageOptions(t *testing.T) { expectedOptions := &ScriptStageOptions{ Script: "/root/test.sh", } actualOptions := NewScriptStageOptions("/root/test.sh") assert.Equal(t, expectedOptions, actualOptions) } func TestNewS...
package main import ( "bytes" "errors" "log" "net/http" "time" "github.com/gorilla/websocket" "github.com/nicklasos/golimit" "github.com/tomasen/realip" ) var ( ipLimit = golimit.NewGroupLimiter( golimit.NewLimiter(1*time.Second, 4), golimit.NewLimiter(1*time.Minute, 60), ) idLimit = golimit.NewGroup...
package main func main() { // var x int // var y = false // print(x, y ) // var x, y int // println(x, y) // var a, s = 100, "abc" // println(a, s) var ( x, y int a, s = 100, "abc" ) println(x, y, a, s) }
package terraform import ( "fmt" "io/ioutil" ) type ExecutorError struct { tfStateFilename string err error debug bool } func NewExecutorError(tfStateFilename string, err error, debug bool) ExecutorError { return ExecutorError{ tfStateFilename: tfStateFilename, err: err, ...
package atomix import ( "testing" "time" ) func TestTime(t *testing.T) { now := time.Now() a := NewTime(now) mustEqual(t, a.Load(), now) now2 := now.Add(time.Hour) a.Store(now2) mustEqual(t, a.Load(), now2) }
// DO NOT EDIT!!! package options type Option func(options *BaseDecls) func OptionUnexportedEmptyVal(option struct{}) Option { return func(options *BaseDecls) { options.unexportedEmptyVal = option } } func OptionChanVal(option chan struct{}) Option { return func(options *BaseDecls) { options.ChanVal = option ...
package main import ( "encoding/json" "errors" "fmt" "io/ioutil" "net/http" ) // All retrieves all persons from the database func All() ([]Person, error) { persons := []Person{} for key, element := range PersonMap { persons = append(persons, element) fmt.Println("Key:", key, "=>", "Element:", element) } ...
package main import ( "design-patterns-go/decoratorPattern" "fmt" ) func main() { fmt.Println("Implementing Decorator Pattern in Go") fmt.Println(".") fmt.Println("..") fmt.Println("...") fmt.Println("....") fmt.Println("") decorator := decoratorPattern.NewDecorator() decorator.Run() }
package controller import ( "net/http" "strconv" "varconf-server/core/dao" "varconf-server/core/moudle/router" "varconf-server/core/service" "varconf-server/core/web/common" ) type AppController struct { common.Controller appService *service.AppService configService *service.ConfigService } func InitAp...
/* Copyright 2021 The CD Events SDK 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" "gingin/config" "gingin/model" "gingin/types" "github.com/gin-gonic/gin" _ "go.etcd.io/etcd/client/v3" "strconv" "sync" ) func main() { model.InitDB() user := model.NewUserModel() fmt.Println(";;;;") u, err := user.GetUser(1) fmt.Println(u) fmt.Println(err) w := new(sync...
package log import ( "bytes" "strings" "testing" "github.com/rs/zerolog" "github.com/stretchr/testify/assert" ) func TestHTTPHeaders(t *testing.T) { t.Parallel() type A = []string type M = map[string]string t.Run("all", func(t *testing.T) { t.Parallel() var buf bytes.Buffer log := zerolog.New(&buf)...
package cryptotrader import ( "context" "flag" "fmt" "math" "os" "os/signal" "strings" "syscall" "github.com/mhereman/cryptotrader/logger" ) func ReadFlags() (assetCfg AssetConfig, exchangeCfg ExchangeConfig, algoConfig AlgorithmConfig, tradeConfig TradeConfig, notifierConfig NotifierConfig, err error) { v...
// test-receiver project main.go package main import ( "fmt" ) type Bag struct { items []int } func Insert(b *Bag, itemid int) { b.items = append(b.items, itemid) } func (b *Bag) Insert2(itemid int) { b.items = append(b.items, itemid) } type Point struct { X int Y int } type MyInt int func (m MyInt) IsZero...
package bytedata import ( "testing" "time" "github.com/direktiv/direktiv/pkg/refactor/logengine" ) func TestConvertLogMsgForOutput(t *testing.T) { input := make([]*logengine.LogEntry, 0) field := make(map[string]interface{}) field["level"] = "info" input = append(input, &logengine.LogEntry{ T: time.Now...
package main import ( "okd-pulumi-vsphere-upi/pkg/rhcos" _ "okd-pulumi-vsphere-upi/pkg/vm" "github.com/davecgh/go-spew/spew" "github.com/pulumi/pulumi/sdk/v2/go/pulumi" ) func main() { /* Order of execution (existing terraform) ******************************** * 1. IPAM * 2. Create vSphere objects RP, F...
package filemail type Initialize struct { Transferid string `json:"transferid"` Transferkey string `json:"transferkey"` Transferurl string `json:"transferurl"` Transferip string `json:"transferip"` Udpport int `json:"udpport"` Udpthreshold int `json:"udpthreshold"` Response...
package main import ( "fmt" ) func main() { var arrs = [5]int{1, 2, 3, 4, 5} for idx, value := range arrs { arrs[idx] = value * 2 fmt.Printf("Array idx[%d] is %d!\n", idx, arrs[idx]) } var arr1 = new([5]int) var arr2 [5]int var inta int = 3 arr1[0] = inta arr2[0] = inta fmt.Printf("value: %d\n", arr1[0...
// Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 package chainimpl import ( "time" "github.com/iotaledger/wasp/packages/chain" "github.com/iotaledger/wasp/packages/hashing" "github.com/iotaledger/wasp/packages/util" "github.com/prometheus/common/log" ) func (c *chainObj) testTrace(msg *ch...
package hookexecutor import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" kubescheme "k8s.io/client-go/kubernetes/scheme" ) /** * decoder is a tool to convert a yaml/json manifest to a k8s object. */ type Decode func(data []byte, defaults *schema.GroupVersionKind, into runtime.Obj...
package compute import "testing" // List anti-affinity rules (successful). func TestClient_ListAntityAffinityRules_Success(test *testing.T) { expect := expect(test) testClientRequest(test, &ClientTestConfig{ Request: func(test *testing.T, client *Client) { page := DefaultPaging() rules, err := client.ListS...
package components import ( go_redis_orm "github.com/fananchong/go-redis-orm.v2" "github.com/fananchong/go-xserver/common" ) // Redis : Redis 组件 type Redis struct { ctx *common.Context } // NewRedis : 实例化 func NewRedis(ctx *common.Context) *Redis { return &Redis{ctx: ctx} } // Start : 实例化组件 func (redis *Redis) ...
package aoc2020 import ( "strconv" "strings" aoc "github.com/janreggie/aoc/internal" "github.com/pkg/errors" ) // conwayCube represents a Conway cube type conwayCube [][][]bool func (cube conwayCube) String() string { var sb strings.Builder for zz := range cube { for yy := range cube[zz] { for xx := ran...
// Copyright 2023 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 link import ( "fmt" "strconv" "time" "golang.org/x/net/context" "github.com/almighty/almighty-core/app" "github.com/almighty/almighty-core/errors" "github.com/almighty/almighty-core/gormsupport" "github.com/almighty/almighty-core/log" "github.com/almighty/almighty-core/workitem" "github.com/goadesi...
package gui import ( "fmt" "github.com/fatih/color" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazydocker/pkg/commands" "github.com/jesseduffield/lazydocker/pkg/config" "github.com/jesseduffield/lazydocker/pkg/gui/panels" "github.com/jesseduffield/lazydocker/pkg/gui/presentation" "github.com/j...
package main import ( "flag" "fmt" "log" "os/exec" "path/filepath" "sort" "strconv" "time" "github.com/atotto/clipboard" "github.com/cheggaaa/pb/v3" "github.com/linus4/csgoverview/common" "github.com/linus4/csgoverview/match" demoinfo "github.com/markus-wa/demoinfocs-golang/v2/pkg/demoinfocs/common" "gi...