text
stringlengths
11
4.05M
package main import ( "fmt" ) func calcdistance(c coord, all []coord, maxDistance int) int { distance := 0 for _, a := range all { distance += manhattandistance(c, a) if distance > maxDistance { return distance } } return distance } func main2(all []coord, lx, hx, ly, hy int) { maxDistance := 10000 c...
package database import ( "github.com/gorilla/mux" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" "youth2k/youthserver/src/render" "log" "net/http" ) type Control struct { DB *gorm.DB Render *render.Render } type ControlItem struct { ID ...
package gateway import ( "context" "net/http" "strconv" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "google.golang.org/protobuf/proto" ) // ReplaceHeaders of a grpc request with that of http's func ReplaceHeaders() func(ctx context.Context, w http.ResponseWriter, _ proto.Message) error { return func(ct...
package main import "fmt" func main() { fmt.Println(Sum(100, 2)) }
package astar import ( "math" "testing" ) const ( sqrt2 = 1.4142135623730951 ) type gridMap struct { grid []int width int height int } func abs(i int) int { if i < 0 { i = -i } return i } func (g *gridMap) Neighbors(node Node, edges []Edge) ([]Edge, error) { addNode := func(x, y int, cost float64) {...
/* * @lc app=leetcode.cn id=94 lang=golang * * [94] 二叉树的中序遍历 */ // @lc code=start /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ package main import "fmt" type TreeNode struct { Val int Left *TreeNode Right *TreeNode...
package ssh import ( "fmt" "os" "golang.org/x/crypto/ssh" ) func makeSignersFromAgent() []ssh.Signer { fmt.Fprintf(os.Stderr, "Unsupported connect to ssh-agent on this platform") os.Exit(1) return make([]ssh.Signer, 0) }
package fakes import ( "github.com/cloudfoundry-incubator/notifications/cf" "github.com/cloudfoundry-incubator/notifications/postal" ) type SpaceAndOrgLoader struct { LoadError error Space cf.CloudControllerSpace Organization cf.CloudControllerOrganization } func NewSpaceAndOrgLoader() ...
package crypto import ( "crypto/rsa" "crypto/rand" "crypto/x509" "encoding/pem" "os" ) func RsaKeyGen(bits int) error { privateKey, err := rsa.GenerateKey(rand.Reader, bits) if err != nil { return err } privateKeyBytes := x509.MarshalPKCS1PrivateKey(privateKey) block := pem.Block{ Type: "RSA PRIVATE KE...
package worker import ( "github.com/labstack/echo/v4" "net/http" ) type ( Status struct { Healthy bool `json:"healthy"` Master Master `json:"master"` Routes []*echo.Route `json:"routes"` } ) func (w Worker) Status() *Status { return &Status{ Healthy: true, Master: *w.Master, Routes: w.Server.Rou...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //632. Smallest Range //You have k lists of sorted integers in ascending order. Find the smallest range that includes at least one number from each of ...
package goldie var Templates map[string]string = map[string]string{}
package Template //协议内容 func Agreement() string { return ` 本软件使用GPLv3开源许可协议 使用本软件证明您已经知晓GPLv3开源许可协议内容。 简要摘如下 1. 使用本软件,以及其他衍生品不允许闭源。必须开放源代码。 2. 新增代码必须也遵循GPLv3许可协议。 本开源项目仅作为服务器部署使用,请遵守当地法律法规。 任何使用问题可以通过项目地址进行提交bug,或者项目社区提交问题。 本项目不对系统安全和稳定性做任何承诺,也不允许因为此原因承担任何责任。 开源项目引用: 1. php 2. mysql 3. ubuntu 4. debian 5. openrasp ...
package tree func findTarget(root *TreeNode, k int) bool { h := map[int]*TreeNode{} stack := []*TreeNode{root} for len(stack) != 0 { p := stack[len(stack)-1] stack = stack[:len(stack)-1] if v, ok := h[k-p.Val]; ok && p != v { return true } h[p.Val] = p if p.Right != nil { stack = append(stack, p.R...
package sdl // #include <SDL2/SDL.h> import "C" import "unsafe" type PixelFormat struct { Format uint32 Palette *Palette BitsPerPixels uint8 BytesPerPixel uint8 padding [2]uint8 Rmask uint32 Gmask uint32 Bmask uint32 Amask uint32 Rloss uint8 Gloss ...
package adapters_test import ( "fmt" "os" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/vmware-tanzu-labs/git-story/adapters" ) var _ = Describe("Git", func() { path := os.Getenv("PATH") BeforeEach(func() { os.Setenv("PATH", fmt.Sprintf("./fixtures:%s", path)) }) AfterEach(func() { ...
/* * chain: chain all problems * * input: * nelts: the number of elements * randmat_seed: random number generator seed * thresh_percent: percentage of cells to retain * winnow_nelts: the number of points to select * * output: * result: a real vector, whose values are the result of the final product ...
// Copyright 2019 The Dice Authors. 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by app...
// Copyright 2019-2023 The sakuracloud_exporter 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 appl...
package models_test import ( "gopher-translator/pkg/mock" "testing" ) func TestTranslationHistoryList(t *testing.T) { englishWord := "test" mockInstance := mock.CreateNewMock() gopherWord := mockInstance.TranslateEnglishWordToGopher(englishWord) historyList := mockInstance.CreateNewTranslationHistoryStructInsta...
package one import ( "testing" ) func TestMaxCalories(t *testing.T) { cases := []struct { name string actual string expected int }{ { name: "example", actual: input, expected: 24000, }, { name: "actual input", actual: input2, expected: 67016, }, } for _, c := ran...
package vote import ( "github.com/consensys/gnark-crypto/ecc" twistededwards_bn254 "github.com/consensys/gnark-crypto/ecc/bn254/twistededwards" "github.com/consensys/gnark-crypto/signature" "github.com/consensys/gnark/backend" "github.com/consensys/gnark/backend/groth16" "github.com/consensys/gnark/frontend" "g...
package seeders import ( "github.com/agusbasari29/Skilltest-RSP-Akselerasi-2-Backend-Agus-Basari/database" "github.com/agusbasari29/Skilltest-RSP-Akselerasi-2-Backend-Agus-Basari/repository" "gorm.io/gorm" ) var ( db *gorm.DB = database.SetupDatabaseConnection() eventRepo = repository.NewEventRep...
package util import ( "net" ) const ( RouteFlagUp = 1 << iota RouteFlagGateway RouteFlagHost ) type DefaultRouteInfo struct { Address net.IP Interface string Mask net.IPMask } type RouteEntry struct { BaseAddr net.IP BroadcastAddr net.IP Flags uint32 GatewayAddr net.IP InterfaceNam...
package ionic import ( "bytes" "encoding/json" "fmt" "net/url" "github.com/ion-channel/ionic/aliases" ) // AddAliasOptions struct that allows for adding an alias to a // project type AddAliasOptions struct { Name string `json:"name"` ProjectID string `json:"project_id"` TeamID string `json:"team_id"`...
package main import ( "testing" "github.com/jackytck/projecteuler/tools" ) func TestP87(t *testing.T) { cases := []tools.TestCase{ {In: 50, Out: 4}, {In: 50000000, Out: 1097343}, } tools.TestIntInt(t, cases, solve, "P87") }
package club import ( "bytes" "encoding/json" "net/http" "net/http/httptest" "testing" "github.com/ubclaunchpad/pinpoint/gateway/schema" "github.com/ubclaunchpad/pinpoint/protobuf/fakes" "github.com/ubclaunchpad/pinpoint/protobuf/request" "go.uber.org/zap/zaptest" ) func TestClubRouter_createClub(t *testing...
package apis import ( "log" "strconv" "github.com/umeat/go-gnss/cmd/database/daos" "github.com/gin-gonic/gin" "net/http" ) func GetObservation(c *gin.Context) { id, _ := strconv.ParseUint(c.Param("id"), 10, 32) if obs, err := daos.GetObservation(uint(id)); err != nil { c.AbortWithStatus(http.StatusNotFound) ...
package main import ( "fmt" ) func main() { numbers := [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} sum := 0 for index, val := range numbers { sum += val fmt.Print("[", index, ",", val, "]") } fmt.Println("\nSum is::", sum) kvs := map[int]string{1: "apple", 2: "banana"} for k, v := range kvs { fmt.Println(k...
package server import ( "context" "encoding/json" "fmt" "log" "net/http" "os" "cloud.google.com/go/datastore" "github.com/nervelife/learning-golang/src/app/data" "google.golang.org/api/iterator" ) var ctx context.Context var projectID string var client datastore.Client func init() { fmt.Println("Initiali...
package notify_saver_service import ( "log" "ms/sun/servises/event_service" "ms/sun/shared/config" "ms/sun/shared/helper" "ms/sun/shared/x" "ms/sun_old/base" ) var newNotify = make(chan x.Notify, 1000) func saveNewNotifyes() { for act := range newNotify { if act.Murmur64Hash == 0 || act.NotifyId == 0 || act...
package pie // Top will return n elements from head of the slice // if the slice has less elements then n that'll return all elements // if n < 0 it'll return empty slice. func Top[T any](ss []T, n int) (top []T) { for i := 0; i < len(ss) && n > 0; i++ { top = append(top, ss[i]) n-- } return }
package model import ( "appengine" "appengine/datastore" ) type Category struct { Name string Ratio float32 // Not stored in the datastore Key *datastore.Key `datastore:"-"` } func (cat *Category) ToPercent() int { return int(cat.Ratio * 100) } func QueryCategories(c appengine.Context, b *Budget) ([]*Catego...
package cmd import ( "fmt" "github.com/spf13/cobra" "github.com/yugabyte/yugabyte-db/managed/yba-installer/common" ) var versionCmd = &cobra.Command{ Use: "version", Short: "The version of YBA Installer.", Args: cobra.NoArgs, Long: ` The version will be the same as the version of YugabyteDB Anywhere th...
package main import ( "fmt" "os" "path/filepath" "github.com/garyburd/redigo/redis" sync "./lib" ) func main() { if len(os.Args) < 3 { fmt.Printf("usage: %s <src> <dst>\n", filepath.Base(os.Args[0])) os.Exit(1) } src, err := redis.Dial("tcp", os.Args[1]) if err != nil { fmt.Println(err) return } ...
package main import ( "encoding/json" "fmt" "math/rand" "net/http" "os" "strconv" "strings" "time" ) type responseObject struct { Events []event `json:"viktigaDatum,omitempty"` } type event struct { Type string `json:"type,omitempty"` Category string `json:"category,omitempty"` WebSkvPath str...
package memphis import ( "context" "fmt" "github.com/memphisdev/memphis.go" "github.com/pkg/errors" "github.com/batchcorp/plumber-schemas/build/go/protos/opts" "github.com/batchcorp/plumber-schemas/build/go/protos/records" "github.com/batchcorp/plumber/tunnel" "github.com/batchcorp/plumber/util" "github.co...
package c49_cbc_mac_forgery import ( "bytes" "testing" ) func TestValidation(t *testing.T) { key := bytes.Repeat([]byte("K"), 16) msg := bytes.Repeat([]byte("M"), 24) cbc := NewCBCMAC(key) iv, mac := cbc.Sign(msg) if !cbc.Validation(msg, iv, mac) { t.Errorf("Incorrect result. Expected true, got false\n") } ...
package service type GetEndpointParams struct{ Endpoint string `json:"endpoint" validate:"required,uri"` } type GetResponse struct { StatusCode int `json:"statusCode"` Content string `json:"content"` Err error `json:"err,omitempty"` } type AddEndpointParams struct { Username strin...
package main import ( "fmt" "github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter7/grpc/greeter" "golang.org/x/net/context" ) // Greeter implements the interface // generated by protoc type Greeter struct { Exclaim bool } // Greet implements grpc Greet func (g *Greeter) Greet(ctx context.Co...
package main import ( "fmt" "os" "strings" "github.com/NHAS/reverse_ssh/internal/server" ) func printHelp() { fmt.Println("Reverse SSH server") fmt.Println(os.Args[0], "listen addr") } func main() { arg := "" if len(os.Args) > 1 { arg = strings.TrimSpace(os.Args[1]) } if len(os.Args) != 2 { fmt.Prin...
// Gábor Nagy and Niklas Ingemar Bergdahl 2016-05-25 package crawler import ( "bytes" "io" "log" "net/http" "strings" "golang.org/x/net/html" ) // Crawl calls and parses the assigned webpage, looking for URLs and collecting // them in a list. func Crawl(url string) map[string]bool { body := getPage(url) def...
package web import ( "context" "github.com/angelospillos/rankingservice" pb "github.com/angelospillos/rankingservice/proto" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) type Server struct { pb.UnimplementedRankingServiceServer Service ranking.Service } func (s Server) GetRankings(ctx cont...
package medkit import ( "github.com/spf13/cobra" ) // installCmd represents the install command. var installCmd = &cobra.Command{ Use: "install", Short: "install various resources", Long: ` The install command will install various resources based on the sub-command.`, Run: func(cmd *cobra.Command, args []strin...
package main import ( "encoding/base64" "fmt" "golang.org/x/crypto/scrypt" ) func main() { dk, err := scrypt.Key([]byte("123456"), []byte("qwer"), 1 << 15, 8, 1,32) if err != nil { return } fmt.Println(base64.StdEncoding.EncodeToString(dk)) }
package ipcam import "testing" func TestIpcam_Map(t *testing.T) { f := Ipcam{} f.Id = "myid" f.Url = "myurl" f.Rec = true f.Off = true f.Online = false m := f.Map() _, ok1 := m["id"] _, ok2 := m["url"] _, ok3 := m["rec"] _, ok4 := m["off"] _, ok5 := m["online"] if !ok1 || !ok2 || !ok3 || !ok4 || ok5 { ...
package users import ( "context" "database/sql" "strings" "cinemo.com/shoping-cart/framework/loglib" "cinemo.com/shoping-cart/internal/errorcode" "cinemo.com/shoping-cart/internal/orm" "github.com/friendsofgo/errors" "github.com/volatiletech/null/v8" "github.com/volatiletech/sqlboiler/v4/boil" "github.com/v...
package leetcode import "strings" func LongestCommonPrefix(strs []string) string { if len(strs) == 0 { return "" } s := strs[0] res := "" for i := 1; i < len(s)+1; i++ { check := s[:i] for j := 1; j < len(strs); j++ { if !strings.HasPrefix(strs[j], check) { return res } } res = check } retu...
package main import "fmt" func hello(){ }
// This file was generated for SObject Idea, API Version v43.0 at 2018-07-30 03:47:20.482032335 -0400 EDT m=+6.824894863 package sobjects import ( "fmt" "strings" ) type Idea struct { BaseSObject Body string `force:",omitempty"` Categories string `force:",omitempty"` CommunityId ...
// Basic building blocks of the app. package main import ( "fmt" "log" "go.jlucktay.dev/golang-workbench/go_rest_api/pkg/mongo" "go.jlucktay.dev/golang-workbench/go_rest_api/pkg/server" ) // App has a server and a Mongo session. type App struct { server *server.Server session *mongo.Session } // Initialize s...
package main import "fmt" func main() { // 声明数组,方式1 var arr [10]int // 赋值操作 arr[0] = 11 arr[1] = 12 // 声明数组,方式2 arr2 := [3]int{1, 2, 3} arr3 := [10]int{111, 222, 333} arr4 := [...]int{444, 555, 666} for key, value := range arr2 { fmt.Println("arr2 key", key) fmt.Println("arr2 value", value) } for ke...
package pathfileops import ( "os" "strings" "testing" ) func TestFileAccessControl_CopyIn_01(t *testing.T) { textCode := "-rwxrwxrwx" fPermCfg, err := FilePermissionConfig{}.New(textCode) if err != nil { t.Errorf("Error returned by FilePermissionConfig{}.New(textCode).\n"+ "textCode='%v'\nErr...
package dushengchen /** Submission: https://leetcode.com/submissions/detail/372743143/ Runtime: 0 ms, faster than 100.00% of Go online submissions for Permutations. Memory Usage: 2.7 MB, less than 51.11% of Go online submissions for Permutations. Next challenges: Permutations II Permutation Sequence Combina...
package main import ( "fmt" "io" "github.com/pkg/errors" ) var ( version = "v0.0.0+unknown" // populated by goreleaser ) // VersionOps describes printing version string. type VersionOp struct{} func (op VersionOp) Run(stdout, _ io.Writer) error { _, err := fmt.Fprintf(stdout, "%s\n", version) return errors.W...
// Package source models a single audio source package source import ( "testing" "github.com/stretchr/testify/assert" "github.com/go-mix/mix/bind/debug" "github.com/go-mix/mix/bind/sample" "github.com/go-mix/mix/bind/spec" ) // TODO: test multi-channel source audio files func TestBase(t *testing.T) { // TODO...
// 要生成godoc,注释必须在被注解的对象上面,中间不能有空行。 // 每个package对应一个godoc页面。 // // 这里是一个新的段落,用空的注释行分段。 // // 代码格式前面加3个空格, // 这里是代码格式。 //package上面的注释生成为Overview模块。 package godoc import ( "fmt" ) // 这里是对const的注释。 const ( C1 = "asdf" // 大写的exported常量,可以生成为godoc。 c2 = 12 // 小写的unexported变量,不能生成为godoc。 ) // 这里是对struct ObjectA的...
package main import ( "bufio" "fmt" "io" "os" ) func main() { //打开文件 //概念说明:file的叫法 //1.file叫file对象 //2.file叫file指针 //3.file叫file文件句柄 file, err := os.Open("D:/test.txt") //以读的模式打开文件 if err != nil { fmt.Println("打开文件错误", err) //如果没有这个文件The system cannot find the file specified. } fmt.Println("打开的文件", fi...
package gorm_client import ( "github.com/jinzhu/gorm" ) type GormClient struct { master *gorm.DB slave *gorm.DB } func NewClient() *GormClient { return &GormClient{} } var Client *GormClient func Dial(dialect string, args ...interface{}) (*GormClient, error) { Client = NewClient() return Client.Dial(dialect...
package syncer import ( "context" "github.com/pkg/errors" "github.com/sourcegraph/sourcegraph/internal/api" "github.com/sourcegraph/sourcegraph/internal/db" "github.com/sourcegraph/sourcegraph/internal/errcode" "github.com/sourcegraph/sourcegraph/internal/types" "github.com/sourcegraph/sourcegraph/schema" ) ...
package main import ( "fmt" "log" "math" "os" "path/filepath" "the-go-programming-language/ch2/exs_2.2/unitconv" ) type conversion int const ( c2F conversion = iota + 1 m2Ft kg2Lbs ) func (c conversion) String() string { return []string{"Celsius/Fahrenheit", "Meter/Feet", "Kilogram/Pound"}[c-1] } func m...
package medium import "testing" type ListNode struct { Val int Next *ListNode } func Test02(t *testing.T) { var l1 *ListNode var l2 *ListNode addNode(l1,l2,0) } func addNode(l1 *ListNode, l2 *ListNode, pre int) (*ListNode){ if l1==nil && l2==nil { if pre !=0 { return &ListNode{Val:pre} } else { retu...
package scanner import ( "h12.io/dfa" "h12.io/gombi/scan" ) var tokMatcherCache = &scan.Matcher{ EOF: 1, Illegal: 0, M: &dfa.M{ States: dfa.States{ { Table: dfa.TransTable{ {0x09, 0x09, 1}, {0x0a, 0x0a, 2}, {0x0d, 0x0d, 3}, {0x20, 0x20, 4}, {0x21, 0x21, 5}, {0x22, 0x22, 6}, {0x25, 0x25, 7}, {0x26, 0x26, 8}, {0x27, ...
package boom import ( "testing" "go.mercari.io/datastore/v2/internal/testutils" "google.golang.org/api/iterator" ) func TestBoom_IteratorNext(t *testing.T) { ctx, client, cleanUp := testutils.SetupCloudDatastore(t) defer cleanUp() type Data struct { ID int64 `datastore:"-" boom:"id"` } bm := FromClient(c...
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os" "sort" "strings" "time" "github.com/prometheus/common/model" ) type ErrorType string type ApiResponse struct { Status string `json:"status"` Data json.RawMessage `json:"data"` ErrorType ErrorType `json:...
package responses import ( "encoding/json" "testing" "github.com/stretchr/testify/assert" ) func TestWalletInfoResponse(t *testing.T) { response := WalletInfoResponse{ Balance: "1", Pending: "2", Receivable: "2", AccountsCount: 5, AdhocCount: 1, Deterministi...
package types type CompanyIn struct { Name string `json:"name"` NameAbbr string `json:"name_abbr"` Code int64 `json:"code"` }
package dbfixtures import ( "context" "database/sql" "fmt" "os" "path" fixtures "github.com/go-testfixtures/testfixtures/v3" "github.com/mitchellh/mapstructure" "github.com/pkg/errors" migrate "github.com/rubenv/sql-migrate" // SQL drivers. _ "github.com/go-sql-driver/mysql" _ "github.com/lib/pq" _ "git...
/* * @lc app=leetcode.cn id=1104 lang=golang * * [1104] 二叉树寻路 */ // @lc code=start func pathInZigZagTree(label int) []int { } // @lc code=end
package rap type AuthToken struct { Token string } type AuthBasic struct { Username string Password string } type Authentication interface { AuthorizationHeader() string // "basic <base64-encoded string>" }
package xlattice_go const ( VERSION = "0.4.19" VERSION_DATE = "2017-11-10" )
package sql import ( "fmt" ) // Iterator represents a forward-only iterator over a set of points. // These are used by the MapFunctions in this file type Iterator interface { Next() (conversationsKey string, time int64, value interface{}) } // MapFunc represents a function used for mapping over a sequential series...
/* * Copyright (c) 2019 VMware, Inc. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package api_test import ( "context" "testing" "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" "github.com/kubenext/lissio/internal/api" "github.com/kubenext/lissio/internal/api/fake" "g...
package drivers import ( "fmt" "sync" "time" "github.com/complyue/ddgo/pkg/isoevt" "github.com/complyue/ddgo/pkg/livecoll" "github.com/complyue/ddgo/pkg/svcs" "github.com/complyue/hbigo" "github.com/complyue/hbigo/pkg/errors" "github.com/golang/glog" ) func NewMonoAPI(tid string) *ConsumerAPI { return &Con...
package tsmt import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document02100103 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:tsmt.021.001.03 Document"` Message *MisMatchAcceptanceNotificationV03 `xml:"MisMtchAccptncNtfctn"` } func ...
package test import ( "fmt" "testing" ) type AAA struct { ID int Name string Age int } func Test_v(t *testing.T) { a := AAA{ ID: 1, Name: "aaaa", Age: 3333, } fmt.Println("------ +v -----------") fmt.Println(fmt.Sprintf("%+v", a)) fmt.Println("----- #v ------------") fmt.Println(fmt.Sprintf("...
package sqly import "testing" func TestParseArray(t *testing.T) { //str := []byte("{10001, 10002, 10003, 10004}") str := []byte("{{\"meeting\",\"lunch\",\"lunch2\"},{\"training\",\"presentation\",\"fff\"}}") dims, elems, err := parseArray(str, []byte{','}) if err != nil { t.Log(err) } t.Log(dims) t.Log(elems...
package echov4 import ( "github.com/kaz/pprotein/integration" "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" "github.com/labstack/gommon/log" ) func Integrate(e *echo.Echo) { EnableDebugHandler(e) EnableDebugMode(e) } func EnableDebugHandler(e *echo.Echo) { e.Any("/debug/*", echo.WrapH...
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func pathSum(root *TreeNode, sum int) int { if root == nil { return 0 } sumMap := make(map[int]int) sumMap[0] = 1 num := 0 doPathSum(&num, root, 0, s...
package utils import "testing" func TestToJSON(t *testing.T) { m := map[string]int{ "first": 1, "second": 2, } jsonRep := ToJSON(m) expect := `{"first":1,"second":2}` if jsonRep != expect { t.Error("got bad json result: ", jsonRep) } } func TestToJSONStruct(t *testing.T) { js := &struct { Name ...
package messaging import ( "encoding/json" "log" ) // SerialiseString - uses json.marshal to serialise strings func SerialiseString(s string) (b []byte, isOK bool) { msg, err := json.Marshal(s) if err != nil { log.Println(err) return nil, false } return msg, true } // DeserialiseString - uses json.Unmars...
package Postgres import ( "MailService/internal/Model" "github.com/go-pg/pg/v9" "github.com/go-pg/pg/v9/orm" pgwrapper "gitlab.com/slax0rr/go-pg-wrapper" ) type DataBase struct { DB pgwrapper.DB User string Password string DataBaseName string } func (dbInfo *DataBase) Init(user string, ...
package main // Configuration is used to form context to perform search routine. type configuration struct { originBoard board // ... maxCost int // The max cost of a board can have //expectdepth int // The answer path is expect to be less then this number. It is used // // to avoid the A* method beh...
package terraform_test import ( "errors" "github.com/cloudfoundry/bosh-bootloader/fakes" "github.com/cloudfoundry/bosh-bootloader/terraform" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("OutputGenerator", func() { var ( executor *fakes.TerraformExecutor outputGenerator ...
package main import ( "fmt" "github.com/codesoap/ytools" "os" "path/filepath" ) func main() { url, err := ytools.GetDesiredVideoUrl() if err != nil { os.Exit(1) } save_as_last_picked(url) fmt.Println(url) } func save_as_last_picked(url string) (err error) { data_dir, err := ytools.GetDataDir() if err !=...
package antlr type BaseATNSimulator struct { atn *ATN sharedContextCache *PredictionContextCache } func NewBaseATNSimulator(atn *ATN, sharedContextCache *PredictionContextCache) *BaseATNSimulator { b := new(BaseATNSimulator) b.atn = atn b.sharedContextCache = sharedContextCache return b } var...
package handlers import ( "net/http" "rest-api-test-users/pkg/user" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-sdk-go/aws" ) const errorMethodNotAllowed = "method Not allowed" // ErrorBody struct object type ErrorBody struct { ErrorMsg *string `json:"error,omitempty"` } // GetUsersHandler gets ...
package serverconfigs import ( "encoding/json" "errors" "github.com/TeaOSLab/EdgeCommon/pkg/configutils" "github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs" "github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/sslconfigs" ) type ServerConfig struct { Id int64 `yaml:"id" j...
package service import ( "Seaman/config" "Seaman/model" "github.com/go-xorm/xorm" "github.com/kataras/iris/v12" "time" ) /** * 角色模块功能服务接口 */ type AppRoleService interface { //新增角色 AddAppRole(model *model.TplAppRoleT) bool //删除角色 DeleteAppRole(id int) bool //通过id查询角色 GetAppRole(id int) (model.TplAppRol...
package iutils import "github.com/golang/protobuf/proto" type IByte interface { ProtoBuf(value proto.Message) error String() string Json(value interface{}) error Bytes() []byte SetData(data []byte) }
package main import "fmt" func main() { foo() bar("James") s := woo("Moneypenny") fmt.Println(s) x, y := mouse("Ian", "Felmming") fmt.Println(x) fmt.Println(y) } // func (r receiver) identifier(parameters) (returns(s)) { ... } func foo() { fmt.Println("hello Im foo") } // know the difference with parameter...
package db import ( "fmt" "log" "github.com/google/uuid" ) func AddFile(name string, folderName string) { Open() defer Close() if !IsInitialized() { Initialize() } tx := BeginTransaction() rows, err := db.Query("select id from folders where name=?", folderName) if err != nil { log.Fatal(err) } if ...
// Copyright 2017 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 main import ( "time" ) type ( Auth interface { } Base struct { ID uint `gorm:"primary_key"` CreatedAt time.Time UpdatedAt time.Time } Person struct { Base Career string `form:"Career"` Class string `form:"Class"` Country string `form:"Country"` Develop string `form:"Help"` Em...
package mysql import ( "fmt" _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" "tcc_transaction/constant" "tcc_transaction/log" "tcc_transaction/store/data" "time" ) const ( maxOpenConns = 10 maxIdleConns = 10 maxLifeTime = 300 ) type MysqlClient struct { c *sqlx.DB } // tcc:tcc_123@tcp(local...
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func isValidBST(root *TreeNode) bool { if root == nil { return true } result := true dfs(root.Left, nil, &root.Val, &result) dfs(root.Right, &root.Val...
package sudoku import "os" import "sync" import "github.com/mandolyte/simplelogger" import "sync/atomic" // misc var mutex = &sync.Mutex{} var solutions map[string]string var sl *simplelogger.SimpleLogger var Counter uint64 func init() { solutions = make(map[string]string) sl = &simplelogger.SimpleLogger { ...
package parquet_test import ( "testing" "github.com/segmentio/parquet-go" ) func TestTransformRowReader(t *testing.T) { rows := []parquet.Row{ {parquet.Int64Value(0)}, {parquet.Int64Value(1)}, {parquet.Int64Value(2)}, {parquet.Int64Value(3)}, {parquet.Int64Value(4)}, } want := []parquet.Row{ {parqu...
package models type Item struct { Name string `bson:"name"` Quantity int `bson:"qtd"` Price float64 `bson:"price"` }
package order import ( "context" "tpay_backend/merchantapi/internal/common" "tpay_backend/model" "tpay_backend/merchantapi/internal/svc" "tpay_backend/merchantapi/internal/types" "github.com/tal-tech/go-zero/core/logx" ) type ModifyTransferTestOrderStatusLogic struct { logx.Logger ctx context.Context sv...