text
stringlengths
11
4.05M
package problem0142 import "testing" func TestSolve(t *testing.T) { t.Log(detectCycle(buildCicleList([]int{3, 2, 0, -4}, 1))) t.Log(detectCycleTwoPointer(buildCicleList([]int{3, 2, 0, -4}, 1))) } func buildCicleList(nums []int, pos int) *ListNode { if len(nums) == 0 { return nil } head := &ListNode{Val: nums[...
package main import ( "fmt" "os" ) //学生管理系统 1.数据-->结构体字段 2.功能--->方法 type student struct{ id int64 name string } //学生的管理者 type studentMgr struct{ allStudent map[int64]student } func showMenu(){ fmt.Println("welcome to sms") fmt.Println(` 1.查看学生 2.添加学生 3.修改学生 4.删除学生 5.退出 `) } //查看学生 func (s studentMgr) s...
package entity // APIResponse export type APIResponse struct { Success bool `json:"success"` Fail bool `json:"fail"` Data interface{} `json:"data"` } // NewAPIResponse export func NewAPIResponse(data interface{}, err error) *APIResponse { if err != nil { return &APIResponse{ Fail: true, ...
package calc import "testing" func TestDotProd(t *testing.T) { exp := 3.0 vecA := Vec([]float64{1.0, 3.0, -5.0}) vecB := Vec([]float64{4.0, -2.0, -1.0}) act := vecA.DotProd(vecB) if exp != act { t.Error("Expected", exp, "got", act) } }
/* Copyright 2019 Packet 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...
/* You are playing a Billiards-like game on an N×N table, which has its four corners at the points {(0,0),(0,N),(N,0), and (N,N)}. You start from a coordinate (x,y), (0<x<N,0<y<N) and shoot the ball at an angle 45∘ with the horizontal. On hitting the sides, the ball continues to move with the same velocity and ensurin...
// Copyright 2018 Andrew Bates // // 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 wri...
package files import ( "crypto/md5" "encoding/hex" "io/ioutil" "log" ) type File struct { Path string Name string Hash string Size int } func (file *File) computeHash(done chan *File) { bytes, readError := ioutil.ReadFile(file.Path) if readError != nil { log.Printf("Encountered an error reading the file...
// Copyright (c) 2020 Chair of Applied Cryptography, Technische Universität // Darmstadt, Germany. All rights reserved. This file is part of go-perun. Use // of this source code is governed by a MIT-style license that can be found in // the LICENSE file. // Package test contains generic tests for channel backend imple...
package main import ( "fmt" "github.com/Wan-Mi/RPCDemos/thriftDemo/hello" "git.apache.org/thrift.git/lib/go/thrift" ) type HelloServer struct { } func (e *HelloServer)SayHello(userName string, userAge int32) (r *hello.User, err error){ usr := hello.User{ Name:userName, Age:userAge, } fmt.Println(usr) re...
// ///////////////////////////////////////////////////////////////////////////// // gate 服务器 package main import ( "github.com/zpab123/world" // world 库 ) // 主入口 func main() { // 创建代理 ad := NewAppDelegate() // 创建 app app := world.CreateApp("gate", ad) // 运行 app app.Run() }
package main import "github.com/davecgh/go-spew/spew" // 105. 从前序与中序遍历序列构造二叉树 // 根据一棵树的前序遍历与中序遍历构造二叉树。 // 注意: // 你可以假设树中没有重复的元素。 // https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ func main() { spew.Dump(buildTree([]int{3, 9, 20, 15, 7}, []int{9, 3, 15, 20, 7})) } type Tr...
package goftp import ( "crypto/tls" "fmt" "os" "testing" ) //import "fmt" var goodServer string var uglyServer string var badServer string func init() { //ProFTPD 1.3.5 Server (Debian) goodServer = "bo.mirror.garr.it:21" //Symantec EMEA FTP Server badServer = "ftp.packardbell.com:21" //Unknown server ug...
/* Copyright 2019 The MayaData 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 https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, s...
package sarchivos import ( "FileSystem-LWH/disco/acciones" "fmt" "sort" "strconv" ) // Mount Estructura de las particiones montadas type Mount struct { Ruta string Nombre string ID string Numero int IDent string } var particionesMontadas []Mount var post int = 0 var abc = []string{"a", "b", "c", "d",...
/* Package ast defines the Abstract Syntax Tree for RiveScript. The tree looks like this (in JSON-style syntax): { "Begin": { "Global": {}, // Global vars "Var": {}, // Bot variables "Sub": {}, // Substitution map "Person": {}, // Person substitution map "Array": {}, // Arrays }, "Topics"...
package dushengchen func findKthLargest(nums []int, k int) int { return 0 }
package matchers import ( "archive/zip" "bytes" "path/filepath" ) func Xlsx(in []byte) bool { return checkMsOfficex(in, "xl") } func Docx(in []byte) bool { return checkMsOfficex(in, "word") } func Pptx(in []byte) bool { return checkMsOfficex(in, "ppt") } // TODO func Doc(in []byte) bool { return false } fu...
package simplemath import ( "testing" ) func TestGCD(t *testing.T) { if GCD(3, 9) != 3 { t.Fatalf("expected GCD to be 3\n") } if GCD(7, 19) != 1 { t.Fatalf("expected GCD to be 1\n") } if GCD(500, 5, 1000) != 5 { t.Fatalf("expected GCD to be 5\n") } if GCD(9, 27, 900, 27000) != 9 { t.Fatalf("expected G...
// +build e2e package e2e import ( "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" wfv1 "github.com/argoproj/argo/pkg/apis/workflow/v1alpha1" "github.com/argoproj/argo/test/e2e/fixtures" ) type SmokeSuite struct { fixtu...
package unique import ( "sort" ) // RemoveDuplicates . // Filter for unique values and remove duplicates func RemoveDuplicates(data []int) []int { var result = []int{} for _, v := range data { var ok = true for _, e := range result { if v == e { ok = false } } if ok { result = append(result, ...
package main import ( "archive/zip" "io" "os" "testing" ) func TestCompressing(t *testing.T) { w := createZipWriter(createZipFile("done.zip")) defer w.Close() fileName := "config.json" fileToZip, err := os.Open(fileName) defer fileToZip.Close() if err != nil { panic(err) } info, err := fileToZip.Sta...
package suite_init type SuiteData struct { *StubsData *SynchronizedSuiteCallbacksData *WerfBinaryData *ProjectNameData *K8sDockerRegistryData *TmpDirData *ContainerRegistryPerImplementationData } func (data *SuiteData) SetupStubs(setupData *StubsData) bool { data.StubsData = setupData return true } func (da...
package main import "net/http" func handler(w http.ResponseWriter, r *http.Request) { w.Header().Set("content-type", "application/json") w.Write([]byte(`{"message": "hello world"}`)) } func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8001", nil) }
//+build integration package queue_test import ( "context" "math/rand" "strconv" "sync" "testing" "time" "github.com/stretchr/testify/require" "github.com/rwool/saas-interview-challenge1/pkg/service/internal/redistest" "github.com/rwool/saas-interview-challenge1/pkg/service/queue" "github.com/stretchr/t...
package handler import ( "encoding/json" "fmt" "log" "net/http" "strconv" "github.com/RamVellanki/habittracker/app/services" "github.com/gin-gonic/gin" ) // func PostHabits(c *gin.Context) { // log.Print(c.Request.Body) // c.IndentedJSON(http.StatusOK, string("K")) // } // GetHabits godoc // @Summary Get a...
// Copyright (C) 2019 Kevin L. Mitchell <klmitch@mit.edu> // // 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 a...
package common type DataFormat struct { Status int `json:"status"` Message string `json:"message"` Data interface{} `json:"data"` } func Format(status int, message string, data interface{}) DataFormat { return DataFormat{ Status: status, Message: message, Data: data, } }
package common import ( "regexp" ) const ( Namespace = "TitanGRM" FilePre = "File:" NginxPre = "Nginx:" GisPre = "Gis:" RasterPre = "Raster:" OfficePre = "Office:" FileUpload = "file" Base64Upload = "base64" OmitArg = "omit" DataLoading = "loading" DataNormal = "normal" DataObsoleted = "...
// This file was generated for SObject DatacloudContact, API Version v43.0 at 2018-07-30 03:48:11.604019131 -0400 EDT m=+57.948799959 package sobjects import ( "fmt" "strings" ) type DatacloudContact struct { BaseSObject City string `force:",omitempty"` CompanyId string `force:",omitempty"` CompanyNam...
package cmd import ( "fmt" "github.com/spf13/cobra" "log" ) var versionName = 0.1 var rootCmd = &cobra.Command{ Use: "gorse", Short: "gorse: Go Recommender System Engine", Long: "gorse is an offline recommender system backend based on collaborative filtering written in Go.", Run: func(cmd *cobra.Command, a...
package main import ( "fmt" "github.com/nbgucer/advent-of-code-2018/utils" "log" "strconv" ) func main() { sum := 0 result := 0 found := false seenFrequencies := make(map[int]int) seenFrequencies[0] = 1 fileName := "days\\day-1\\input" stringSlice := utils.GetInputAsSlice(fileName) // Calculate sum for...
package main import ( "fmt" "strings" ) type Passwords interface { GetMasterPassword() string } type SimonsPasswords struct{} type PasswordsProxy struct { user string userPasswords SimonsPasswords } func NewPasswordsProxy(user string) PasswordsProxy { proxy := PasswordsProxy{ use...
package main import ( "bytes" "github.com/stretchr/testify/assert" "io/ioutil" "math" "net/http" "net/http/httptest" "net/url" "strconv" "testing" ) const ( URL_AUTHENTICATE = "/auth" URL_AUTHENTICATE_FAILING = "/auth_fail" URL_CREATE_NEW_APP = "/new_app" URL_CREATE_...
package parser import "testing" var omegaResults01 = []string{ " ETA1 ETA2", "", " ETA1", "+ 1.23E-01", "", " ETA2", "+ 0.00E+00 1.54E-01", } var omegaResults01Parsed = []string{ "1.23E-01", "0.00E+00", "1.54E-01", } func TestParseOmegaResultsBlock(t *testing.T) { parsedDa...
package server import ( "context" "log" "net/http" "time" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/rbonnat/blockchain-in-go/server/controller" "github.com/rbonnat/blockchain-in-go/service" ) // Run Initialize router and launch http server func Run(ctx context.Context, port stri...
package relay import ( "fmt" "github.com/karalabe/hid" "runtime" ) const ( OFF = iota ON ) type IoStatus int const ( C1 = iota + 1 C2 C3 C4 C5 C6 C7 C8 ALL ) type ChannelNumber int type ChannelStatus struct { Channel_1 IoStatus Channel_2 IoStatus Channel_3 IoStatus Channel_4 IoStatus Channel_5 ...
package main import ( "fmt" "html/template" "net/http" "github.com/julienschmidt/httprouter" "github.com/paulsumit5555/gowebdevlopment/mvc/controller" "gopkg.in/mgo.v2" ) var tpl *template.Template func init() { tpl = template.Must(template.ParseGlob("view/*")) } func main() { router := httprouter.New() u...
package main import ( "flag" "fmt" "io/ioutil" "os" "strconv" "strings" ) const ( PrintColor = "\033[38;5;%dm%s\033[39;49m" ) func main() { if len(os.Args) < 2 { fmt.Println("Expected argument(you can set it's color and colored indexes or letters)") os.Exit(1) } else { str := os.Args[1] var indexArr...
package main import ( "context" "flag" "fmt" "github.com/jackc/pgx/v4/pgxpool" "github.com/teploff/otus/calendar/config" "github.com/teploff/otus/calendar/infrastructure/logger" "github.com/teploff/otus/calendar/internal" "go.uber.org/zap" "os" "os/signal" "syscall" ) var ( configFile = flag.String("confi...
package main import ( "database/sql" "fmt" // this is needed because init() function needs to be called in pq package _ "github.com/lib/pq" ) const ( host = "localhost" port = 5432 user = "postgres" password = "testtest" dbName = "postgres" ) func main() { var dbConnection string dbConnectio...
package rancher import ( "errors" "fmt" "io" "strings" "sync" "golang.org/x/net/context" "github.com/sirupsen/logrus" "github.com/docker/docker/api/types/container" "github.com/docker/libcompose/config" "github.com/docker/libcompose/docker/service" "github.com/docker/libcompose/labels" "github.com/docker...
package main import ( "fmt" "log" "net/http" ) func helloHandler2(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, web 2") } func main() { mux := http.NewServeMux() // 输入地址为:http://localhost:8080/ mux.Handle("/", &myHandle2{}) // 输入地址为:http://localhost:8080/hello mux.HandleFunc("/hello", he...
package controller import ( "github.com/Masterminds/semver" "github.com/kyma-project/helm-broker/internal" "github.com/kyma-project/helm-broker/internal/addon" "github.com/kyma-project/helm-broker/internal/addon/provider" "k8s.io/helm/pkg/proto/hapi/chart" ) //go:generate mockery -name=addonStorage -output=autom...
/* Copyright 2022 The KubeVela Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,...
package vm func ParseDescriptor(desc string) (string, []string) { i := 0 if desc[i] != '(' { panic("Invalid descriptor: " + desc) } i++; args := make([]string, 0) for desc[i] != ')' { switch (desc[i]) { case 'I': args = append(args, "I") default: panic("Unimplemented arg descr...
package xl import "go.uber.org/zap" var Logger *zap.Logger const LogPath = "/var/log/8x8.log" func init() { var err error c := zap.NewProductionConfig() c.OutputPaths = []string{LogPath} c.ErrorOutputPaths = []string{LogPath} c.DisableStacktrace = true c.Level.SetLevel(zap.DebugLevel) Logger, err = c.Build( ...
//author xinbing //time 2018/8/28 14:21 package utilities import ( "testing" "fmt" "math" "math/rand" "time" "strconv" ) func TestRound(t *testing.T) { fmt.Println(Round(3.1334, 2)) fmt.Println(Floor(3.9456, 2)) fmt.Println(Ceil(3.123, 2)) fmt.Println(Round(3.9-0.00001, 6)) fmt.Println(Round(0.999 /1000000...
package checkers // Checkers/Draughts var Symbols = map[string]map[string]string{ "black": map[string]string{ "one": "⛀", "two": "⛁", }, "white": map[string]string{ "one": "⛂", "two": "⛃", }, }
package o3e import ( "sync/atomic" "errors" "fmt" ) type wrapperResult uint8 type EmptyType struct{} var Empty = EmptyType{} const ( wrapperSuccess wrapperResult = iota wrapperWait wrapperError ) type Task interface { DepFactors() map[int]EmptyType // memoization may improve performance....
package web import ( "time" "github.com/dgrijalva/jwt-go" "github.com/gofiber/fiber/v2" "github.com/google/uuid" ) func CreateToken(c *fiber.Ctx, userID uuid.UUID, secret []byte) (string, error) { token := jwt.New(jwt.SigningMethodHS256) claims := token.Claims.(jwt.MapClaims) claims["id"] = userID exp := tim...
/* * @lc app=leetcode.cn id=226 lang=golang * * [226] 翻转二叉树 */ package main import "fmt" type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // @lc code=start func invertTree(root *TreeNode) *TreeNode { if root == nil || (root.Left == nil && root.Right == nil) { return root } root.Left = i...
package skeleton import ( "crypto/ecdsa" "crypto/rand" "testing" "time" "github.com/ethereum/go-ethereum/crypto/secp256k1" "github.com/ethereum/go-ethereum/p2p" ) func TestSimulation(t *testing.T) { key, _ := ecdsa.GenerateKey(secp256k1.S256(), rand.Reader) key2, _ := ecdsa.GenerateKey(secp256k1.S256(), rand...
package mailer import ( "bytes" "embed" "html/template" "time" "github.com/go-mail/mail/v2" ) //go:embed "templates" var templateFS embed.FS type Mailer struct { dialer *mail.Dialer sender string } func New(host string, port int, username, password, sender string) Mailer { dialer := mail.NewDialer(host, po...
package track import "time" type Delayes interface { Delay() time.Duration }
package dao import ( "fmt" "gf-init/app/model" "github.com/gogf/gf/database/gdb" "github.com/gogf/gf/frame/g" _ "github.com/lib/pq" ) var DB gdb.DB func GetUsers() { var user model.Users DB = g.DB("default") DB.Table("users").Where("nickname = ?", "1").Scan(&user) fmt.Println(user) }
package atlas import ( "encoding/json" "net/http" "github.com/10gen/realm-cli/internal/utils/api" ) const ( groupsPath = publicAPI + "/groups" ) // Group is an Atlas group type Group struct { ID string `json:"id"` Name string `json:"name"` } type groupResponse struct { Results []Group `json:"results"` } ...
package tests import ( "context" "math/big" "testing" "github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/ethclient" ) var globalAccountForTesting accounts.Account func TestNewAccount(t *testing.T) { ks := keystore.NewKeyStore("../....
package gcp_test import ( "errors" "fmt" "github.com/cloudfoundry/bosh-bootloader/fakes" "github.com/cloudfoundry/bosh-bootloader/gcp" compute "google.golang.org/api/compute/v1" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Client", func() { var ( computeClient *fakes.GCPComput...
/* * @lc app=leetcode.cn id=14 lang=golang * * [14] 最长公共前缀 * * https://leetcode-cn.com/problems/longest-common-prefix/description/ * * algorithms * Easy (34.42%) * Likes: 651 * Dislikes: 0 * Total Accepted: 108.3K * Total Submissions: 314.8K * Testcase Example: '["flower","flow","flight"]' * * 编写一...
package main import ( "fmt" "math" ) func main() { fmt.Println("Máximo = ", math.Max(float64(5), float64(6))) fmt.Println("Mínimo = ", math.Min(float64(5), float64(6))) fmt.Println("Potência = ", math.Pow(3, 2)) }
// Programas executáveis iniciam pelo pacote main package main /* Os programas em GO são organizados em pacotes e pada utiliza-los é necessário declarar um ou vários imports */ import "fmt" // A porta de entrada de um programa Go é a função main func main() { fmt.Print("Primeiro") fmt.Print(" Programa") }
/* This! is an RGB colour grid... Basic RGB grid Basically it's a 2-dimensional matrix in which: The first row, and the first column, are red. The second row, and the second column, are green. The third row, and the third column, are blue. Here are the colours described graphically, using the letters R...
package types type Login struct { User string `json:"user"` Password string `json:"password"` } type Member struct { Name string Age int Active bool }
package handler import ( "encoding/json" "net/http" "github.com/krostar/httpw" "github.com/krostar/logger" "github.com/krostar/logger/logmid" ) // DeployFromGithub deploies a r10k environment from a github trigger. func DeployFromGithub(log logger.Logger, usecase DeployUsecases) httpw.HandlerFunc { return func...
package main import "net/http" func newApiServer() (a *apiServer) { a = &apiServer{ router: http.NewServeMux(), } a.routes() return }
// Copyright 2020 The Reed Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. package types import ( "bytes" "github.com/reed/common/byteutil/byteconv" "github.com/reed/crypto" "github.com/reed/errors" "github.com/...
// Package regexp is a basic regexp library. // // The library was implemented to explore regexp parsing and NFA representation. package regexp // Regexp is a compiled regular expression. type Regexp struct { start, term node pattern string } // Compile compiles a pattern into Regexp. func Compile(pattern strin...
package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "regexp" "strings" "sync" ) var ( linkReg = regexp.MustCompile(`href='(.+?)'[\s\S]*?>([\s\S]+?)<`) articleReg = regexp.MustCompile(`<P>[\s\S]+</P>`) ) //SideBar type type SideBar struct { Docs Docs `json:"docs"` } //Docs type type Docs ...
package controllers import ( "github.com/canghai908/zbxtable/models" ) //TriggersController funct type TriggersController struct { BaseController } //TriggersRes resp var TriggersRes models.TriggersRes //URLMapping beego func (c *TriggersController) URLMapping() { c.Mapping("Get", c.GetInfo) } // GetInfo 获取未恢复告...
package resource import ( "os" "github.com/chronojam/aws-pricing-api/types/schema" "github.com/olekukonko/tablewriter" ) func GetVPC() { vpc := &schema.AmazonVPC{} err := vpc.Refresh() if err != nil { panic(err) } table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Description", "USD", "U...
package repowatch import ( "encoding/json" "errors" "fmt" "sync" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/aws/ec2metadata" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/secretsmanager" ) var ( awsSecretsManagerLock ...
package logdata import "encoding/base64" // Payload is the struct describing the logged data packets' payload when supported type Payload struct { Content string `json:"content"` Base64 string `json:"base64"` Truncated bool `json:"truncated"` } // NewPayloadLogData is used to create a new Payload struct fu...
package main import ( "fmt" ) type Differ struct { ceiling int } func (d Differ) SquareOfSums() int { sum := 0 for i := 1; i <= d.ceiling; i++ { sum += i } return sum * sum } func (d Differ) SumOfSquares() int { sum := 0 for i := 1; i <= d.ceiling; i++ { sum += i * i } return sum } func main() { ...
// chan3 project main.go package main import ( "fmt" ) func main() { ch := make(chan int) fmt.Println("1") ch <- 3 fmt.Println("oo", <-ch) fmt.Println(2) fmt.Println("Hello World!") }
package main import "fmt" // Go has built-in support for multiple return values. This feature is // used often in idiomatic Go, for example to retunr both result and // error values from a function. // Vals - the (int, int) in this function signature shows that the // function returns 2 ints. func vals() (int, int) ...
/* Objective: The objective is to calculate e^N for some real or imaginary N (e.g. 2, -3i, 0.7, 2.5i, but not 3+2i). This is code golf, so, shortest code (in bytes) wins. So, for example: N = 3, e^N = 20.0855392 N = -2i, e^N = -0.416146837 - 0.9092974268i The letter i shouldn't be capitalized (since in mat...
package api import ( "as/pkg/app" "as/pkg/errcode" "github.com/gin-gonic/gin" ) type Admin struct{} // Login 用户登录 // @Summary 用户登录 func (Admin) Login(c *gin.Context) { var userName struct { UserName string `form:"username" binding:"max=20,min=6,required"` Password string `form:"password" binding:"max=20,min=...
package main import ( "os" "github.com/golang/protobuf/proto" "google.golang.org/protobuf/types/known/anypb" "github.com/batchcorp/plumber/test-assets/protobuf-any/sample" ) func main() { inner, err := anypb.New(&sample.Message{ Name: "Mark", Age: 39, }) if err != nil { panic(err) } m := &sample.En...
package docsonnet import ( "fmt" "log" "strings" ) // load docsonnet // // Data assumptions: // - only map[string]interface{} and fields // - fields (#...) coming first func fastLoad(d ds) Package { pkg := d.Package() pkg.API = make(Fields) pkg.Sub = make(map[string]Package) for k, v := range d { if k == "...
// Copyright 2016 Google Inc. All rights reserved. // Use of this source code is governed by the Apache 2.0 // license that can be found in the LICENSE file. // Sample buckets creates a bucket, lists buckets and deletes a bucket // using the Google Storage API. More documentation is available at // https://cloud.googl...
package leetcode import ( "testing" ) func TestPrintNumbers(t *testing.T) { n := 2 PrintNumbers2(n) }
package responses import ( "Pinjem/businesses/deposits" "time" ) type DepositResponse struct { ID uint `json:"id"` UserId uint `json:"user_id"` Amount uint `json:"amount"` UsedAmount uint `json:"used_amount"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `jso...
package types import ( "fmt" "strings" ) // Symbol represents a tradable asset pair type Symbol struct { base string quote string } // NewSymbol creates a Symbol instance func NewSymbol(baseAsset string, quoteAsset string) Symbol { return Symbol{ base: strings.ToUpper(baseAsset), quote: strings.ToUpper(qu...
package main import ( "aoc/day1" "aoc/day2" "flag" ) var day int func init() { flag.IntVar(&day, "day", 1, "Which day would you to run") flag.Parse() } func main() { switch day { case 1: day1.Run() case 2: day2.Run() } }
package printer import ( "fmt" "strings" "sync" "time" "github.com/fatih/color" "github.com/mszostok/codeowners-validator/internal/check" ) type TTYPrinter struct { m sync.RWMutex } func (tty *TTYPrinter) PrintCheckResult(checkName string, duration time.Duration, checkOut check.Output) { tty.m.Lock() defer...
// +k8s:deepcopy-gen=package,register // +groupName=simple.io.example // Package api is the internal version of the API. package simple
package main import ( "encoding/json" "fmt" "log" "net/http" "gopkg.in/mgo.v2/bson" "gopkg.in/mgo.v2" "github.com/gorilla/mux" ) /* var movies = Movies{ Movie{"Sin Limites", 2013, "Desconocido"}, Movie{"Batman Begins", 1999, "Scorsese"}, Movie{"A todo gas", 2005, "Pizzi"}, } */ // Crear variable global ...
package tstune import ( "bytes" "fmt" "strings" "testing" ) type testPrinter struct { statementCalls uint64 statements []string promptCalls uint64 prompts []string successCalls uint64 successes []string errorCalls uint64 errors []string } func (p *testPrinter) Statement(f...
package main import ( "database/sql" "flag" "fmt" _ "github.com/mattn/go-oci8" "log" "os" "strings" ) var conn string func main() { flag.Parse() if flag.NArg() >= 1 { conn = flag.Arg(0) } else { conn = "system/123456@XE" } db, err := sql.Open("oci8", conn) if err != nil { fmt.Println("can't conne...
package main import ( "bufio" "encoding/csv" "fmt" "os" "strconv" "strings" "time" ) func readQuestions(fpath string) (*[]string, *[]int) { csvfile, err := os.Open(fpath) if err != nil { fmt.Println("Couldn't open the csv file", err) } r := csv.NewReader(csvfile) records, err := r.ReadAll() if err != n...
//author xinbing //time 2018/9/4 17:55 package db import "github.com/pkg/errors" type DBConfig struct { DBAddr string AutoCreateTables []interface{} //自动创建的表 MaxIdleConns int MaxOpenConns int LogMode bool } func (p *DBConfig) check() error { if p.DBAddr == "" { return errors.New("empty sql addr") } if p....
// Package runner provides common interface for program runner together with // common types including Result, Limit, Size and Status. // // Status // // Status defines the program running result status including // Normal // Program Error // Resource Limit Exceeded (Time / Memory / Output) // Unauthorized ...
package xeninvoice import ( xinvoice "github.com/xendit/xendit-go/invoice" "github.com/imrenagi/go-payment/invoice" ) func NewBRIVA(inv *invoice.Invoice) (*xinvoice.CreateParams, error) { return newBuilder(inv). AddPaymentMethod("BRI"). Build() }
package main import ( "ms/sun/shared/x" "ms/sun/shared/helper" "ms/sun/shared/dbs" ) func main() { p := x.PostCdb{ PostId: helper.NextRowsSeqId(), UserId: 0, PostTypeEnum: 0, PostCategoryEnum: 0, MediaId: 0, PostKey: "", Text: helper.FactRandSt...
package str_test import ( "fmt" "testing" "github.com/piniondb/str" ) func intStr(val uint) string { return str.Delimit(fmt.Sprintf("%d", val), ",", 3) } func Example_quantity() { for _, val := range []uint{0, 5, 15, 121, 4320, 70123, 999321, 4032500, 50100438, 100000054} { fmt.Printf("[%14s : %s]\n", intS...
package divide_conquer import "strconv" func diffWaysToCompute(input string) []int { var res []int for i := 0; i < len(input); i++ { if input[i] == '+' || input[i] == '-' || input[i] == '*' { part1 := input[:i] part2 := input[i+1:] res1 := diffWaysToCompute(part1) res2 := diffWaysToCompute(part2) f...
package main import ( "database/sql" "fmt" "github.com/cayleygraph/cayley" "github.com/cayleygraph/cayley/graph" _ "github.com/aselus-hub/cayley/graph/sql" "github.com/cayleygraph/cayley/quad" "github.com/satori/go.uuid" "log" "math/rand" "sync" "time" ) const insecureCdbPath = "postgresql://root@127.0.0.1...
package conference import "time" //CallForPapers represents a call for papers/requests done by conference organisers in order to get talks type CallForPapers struct { ConferenceName string ConferenceID string URL string Deadline time.Time Description string Starts time.Time }
/* Copyright © 2019 Sven Wilhelm <refnode@gmail.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 by applicable law or agreed to i...