text
stringlengths
11
4.05M
package gate import "github.com/gin-gonic/gin" // AddGroup : Add route group func (gate *Gate) AddGroup(relativePath string, handlers ...gin.HandlerFunc) { gate.groups[relativePath] = gate.engine.Group(relativePath, handlers...) } // GET add get handler func (gate *Gate) GET(relativePath string, handler interface{}...
// Package parse has functions that turn string-representations of geometry // package primitives into their respective primitives following the same // pattern set by each primitive's string-representation. package parse import ( "bufio" "errors" "io" "strconv" "strings" "github.com/jwowillo/viztransform/geome...
package storage import ( "strconv" "strings" "time" "grm-service/dbcentral/pg" "grm-service/log" "github.com/emicklei/go-restful" "grm-service/common" "grm-service/geoserver" . "grm-service/util" . "storage-manager/types" ) var ( volUnit = map[string]string{"K": "KB", "M": "MB", "G": "GB", "T": "TB"} ) ...
package main import ( "context" "fmt" "github.com/scjalliance/drivestream/driveapicollector" "github.com/scjalliance/drivestream/resource" drive "google.golang.org/api/drive/v3" ) func listPermissions(ctx context.Context, s *drive.Service, id string) (perms []resource.Permission, err error) { var token string ...
/* The Code tab has a code which attempts to add a clone of an array to itself. There is no error message, but the results are not as expected. Can you fix the code? Examples clone([1, 1]) ➞ [1, 1, [1, 1]] clone([1, 2, 3]) ➞ [1, 2, 3, [1, 2, 3]] clone(["x", "y"]) ➞ ["x", "y", ["x", "y"]] */ package main import ...
package file import ( "jmcs/core/library/socket" "jmcs/core/utils/file/transfer" "github.com/gin-gonic/gin/json" "jmcs/core/utils/file" "net" ) type FileTransController struct { socket.SocketController } func (f FileTransController) Receive() { serverTransfer := &transfer.ServerTransfer{} f.ResolveBody(serve...
package main import "net/http" func f1(w http.ResponseWriter, r *http.Request) { str := "hello dali" w.Write([]byte(str)) } func main() { http.HandleFunc("/hello", f1) http.ListenAndServe("127.0.0.1:9000", nil) }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package isolated import ( "encoding/json" "strconv" ) // Int is a JSON/Cloud Endpoints friendly int type that will correctly parse // string encoded i...
package hit import ( "math" "github.com/GuillaumeTech/3dgo/internal/geom" ) type Sphere struct { Center geom.Vec3d Radius float64 Mat Material } func (sphere Sphere) hit(ray geom.Ray, tMin float64, tMax float64, record *HitRecord) bool { oc := geom.SubstractTwoVec(ray.Origin, sphere.Center) a := geom.DotP...
package main import ( "fmt" . "leetcode" ) func main() { fmt.Println(reverseKGroup(NewListNode(1, 2, 3, 4), 2)) } func reverseKGroup(head *ListNode, k int) *ListNode { var reverse func(head, foot *ListNode) *ListNode reverse = func(head, foot *ListNode) *ListNode { if head == nil || head.Next == nil { re...
package main import ( "fmt" "google.golang.org/grpc" "grpc_calculator/calculator/calculatorpb" "io" "log" "net" "time" ) //Server with embedded UnimplementedGreetServiceServer type Server struct { calculatorpb.UnimplementedCalculatorServiceServer } func(s *Server) PrimeNumberDecomposition(req *calculatorpb.P...
package response import ( "github.com/pobo380/network-games/card-game/server/websocket/handler/event_filter" ) type GameEvent struct { Events event_filter.EventWithTypes }
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-08-14 10:18 # @File : of_Offer_04_二维数组中的查找.go # @Description : 在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序, 每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 # @Attention : */ package offer import "testing" func Test_findNumberIn2DArray2(t *testing.T) { findN...
package middleware import ( "forum_Anpw/common" "forum_Anpw/model" "forum_Anpw/reps" "github.com/gin-gonic/gin" "strings" ) func AuthMiddleware()gin.HandlerFunc { //获取authorization header return func(c *gin.Context) { tokenString :=c.GetHeader("Authorization") //验证token格式 if tokenString ==""||!string...
package main import "fmt" /* Hi man , this is a cool thing that you know */ //this is a comment func main(){ fmt.Println(fmt.Println("Hello,World")) return }
package hot100 import ( "fmt" "testing" ) func Test_generateTrees(t *testing.T) { fmt.Println(generateTrees(3)) }
package iteration import ( "testing" "lib" "fmt" ) func TestRepeat(t *testing.T) { t.Run("repeat a 5 times", func(t *testing.T) { lib.AssertEqual(t, Repeat("a", 5), "aaaaa") }) t.Run("repeat fit 10 times", func(t *testing.T) { lib.AssertEqual(t, Repeat("fit", 10), "fitfitfitfitfitfitfitfitfitfit") }) } fu...
package api import ( "fmt" "log" ) func catch(err error) { if err != nil { log.Panic(err) } } func (i *Image) filename() string { return fmt.Sprintf("%d.%s", i.Index, i.Type.extension()) } func (i *Image) zfilename() string { return fmt.Sprintf("%03d.%s", i.Index, i.Type.extension()) } func (i *Image) gene...
// +build !tempdll // +build !memorydll package cfrida func checkAndReleaseDLL() (bool, string) { return false, "" }
package main import ( "github.com/deepglint/util/image/heatmap" "math/rand" ) func main() { hm := heatmap.NewHeatmap("image.png") points := []heatmap.DataPoint{} for i := 0; i < 100; i++ { points = append(points, heatmap.P(float64(1000*rand.Float64()), float64(1000*rand.Float64()))) } hm.DrawHeatmap(point...
package main import ( "time" "github.com/spf13/viper" ) type imageScalerConfig struct { hostname string port int username string password string imageExchange string imageUpdateQueue string imageUpdateRoutingKey string timeout ...
package setr import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document01700102 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:setr.017.001.02 Document"` Message *OrderCancellationStatusReportV02 `xml:"setr.017.001.02"` } func (d *Doc...
package route import ( "github.com/kataras/iris" "github.com/kataras/iris/context" "gocherry-api-gateway/components/common_enum" "gocherry-api-gateway/proxy/filter" ) func RegisterRoutes(app *iris.Application, appConfig *common_enum.Config, servers *filter.ClientMon) { app.Any("/*", func(ctx context.Context) { ...
package models import ( "encoding/json" "time" ) type User struct { UUID string `json:"uuid,omitempty"` Email string `json:"email,omitempty"` Password string `json:"password,omitempty"` Name string `json:"name,omitempty"` CreatedAt time.Time `json:"created_at,omitempty"` Delete...
package intercom import ( "io/ioutil" "testing" ) func TestJobAPISaveUser(t *testing.T) { http := TestJobHTTPClient{t: t, expectedURI: "/bulk/users", fixtureFilename: "fixtures/job.json"} api := JobAPI{httpClient: &http} user := User{UserID: "1234"} job := JobRequest{Items: []*JobItem{NewUserJobItem(&user, JOB_...
package repowatch import ( "time" "github.com/Cloud-Foundations/Dominator/lib/log" ) type Config struct { AwsSecretId string `yaml:"aws_secret_id"` Branch string `yaml:"branch"` CheckInterval time.Duration `yaml:"check_interval"` LocalRepositoryDirectory ...
package sol // heap approach func left(i int) int { return i << 1 } func right(i int) int { return i<<1 | 0x1 } func maxHeapify(nums []int, i int) { l := left(i) r := right(i) largest := i if l < len(nums) && nums[l] > nums[i] { largest = l } if r < len(nums) && nums[r] > nums[largest] { largest = r ...
package goose import "github.com/evelritual/goose/audio" // NewAudioPlayer initiliazes a new audio player for use in allocating sounds // and dealing with playback. func NewAudioPlayer() (audio.Player, error) { return activeDriver.NewAudioPlayer() }
/* Copyright 2018 Intel Corporation. SPDX-License-Identifier: Apache-2.0 */ package testlog import ( "os" "os/exec" "regexp" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/intel/oim/pkg/log" ) func TestGlobal(t *testing.T) { old := log.L() restore := SetGlobal(t) defer restore() a...
package secrets import ( "errors" "github.com/10gen/realm-cli/internal/cli" "github.com/10gen/realm-cli/internal/cli/user" "github.com/10gen/realm-cli/internal/cloud/realm" "github.com/10gen/realm-cli/internal/terminal" "github.com/AlecAivazis/survey/v2" ) type deleteInputs struct { cli.ProjectInputs secret...
// Package storage - служба хранения данных package storage import ( "go.core/lesson6/pkg/crawler" ) type Storager interface { Create(docs []crawler.Document) Document(id int) (crawler.Document, bool) Add(d crawler.Document) } // New - конструктор службы хранения данных func New(s Storager) Storager { return s ...
package oidc_test import ( "context" "testing" "github.com/golang-jwt/jwt/v5" "github.com/ory/fosite" fjwt "github.com/ory/fosite/token/jwt" "github.com/stretchr/testify/assert" "github.com/authelia/authelia/v4/internal/oidc" ) func TestStatelessJWTValidator_IntrospectToken(t *testing.T) { signer := &fjwt.D...
// Copyright 2015 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...
/* Copyright 2019 The Kubernetes 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 lambdas provides helper generic functions. // // These functions are especially helpful in combination with other `genesis` packages. package lambdas
//go:generate protoc --go_out=. messages/proxy.proto package proxy
package getter import ( "testing" "github.com/stretchr/testify/assert" "github.com/quilt/quilt/api" "github.com/quilt/quilt/api/client" "github.com/quilt/quilt/api/client/mocks" "github.com/quilt/quilt/db" ) func TestGetLeaderClient(t *testing.T) { t.Parallel() passedClient := &mocks.Client{} mockGetter :...
package sdkc // ErrorResponseWriter writes a error response failure type ErrorResponseWriter struct { } // NewErrorResponseWriter creates a new error response writer. func NewErrorResponseWriter() *ErrorResponseWriter { return &ErrorResponseWriter{} } func (erw *ErrorResponseWriter) Write(p []byte) (n int, err erro...
package reader import ( "bufio" "bytes" "encoding/binary" "errors" "fmt" "io/ioutil" "os" "os/user" "reflect" "strings" "syscall" ) const ( inputs = "/sys/class/input/event%d/device/uevent" deviceFile = "/dev/input/event%d" maxFiles = 255 ) // event types const ( EvSYN = 0x00 EvKEY = ...
package main import ( "testing" "github.com/Jeffail/gabs/v2" ) func TestAddObjectSimple(t *testing.T) { input := []byte(`{}`) correctResult := `{"foo":"bar"}` j, err := gabs.ParseJSON(input) if err != nil { t.Error(err) } options := addObjectOptions{ json: j, path: "foo", delimiter: ".", ...
package main import "fmt" func main() { var studentsAge map[string]int studentsAge["john"] = 32 studentsAge["bob"] = 31 fmt.Println(studentsAge) }
package server import ( "errors" "net/http" ) func (h *handler) needAuth(w http.ResponseWriter, r *http.Request) { w.Header().Set("WWW-Authenticate", "Basic realm=\""+r.URL.Path+"\"") } func (h *handler) verifyAuth(r *http.Request) (username string, success bool, err error) { var password string var hasAuthReq ...
package get import ( "context" "fmt" "os" "strings" "github.com/devopstoday11/tarian/pkg/logger" "github.com/devopstoday11/tarian/pkg/tarianctl/client" "github.com/devopstoday11/tarian/pkg/tarianctl/util" "github.com/devopstoday11/tarian/pkg/tarianpb" "github.com/olekukonko/tablewriter" cli "github.com/urfa...
// Copyright (c) 2021 Zededa, Inc. // SPDX-License-Identifier: Apache-2.0 // Network Instance/underlay network IP Address Management, // App Number management Module // Allocate a small integer for each application UUID. // The number can not exceed 255 since we use the as IPv4 subnet numbers. // Persist the numbers ...
package main import ( "io/ioutil" "log" "github.com/gin-gonic/gin" "gopkg.in/yaml.v2" ) func check(e error) { if e != nil { panic(e) } } type Config struct { Log struct { Level string `yaml:"level" json:"level"` } `yaml:"log" json:"log"` Mongo struct { Endpoint string `yaml:"endpoint" json:"endpoint"...
/* Copyright (C) 2016 Red Hat, 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, softwa...
package main import ( "fmt" "github.com/jlb0906/micro-movie/aria2-srv/handler" aria2 "github.com/jlb0906/micro-movie/aria2-srv/proto/aria2" "github.com/jlb0906/micro-movie/aria2-srv/service" "github.com/jlb0906/micro-movie/basic" "github.com/jlb0906/micro-movie/basic/common" "github.com/jlb0906/micro-movie/basi...
package webrpc import ( "log" "net/http" "github.com/gorilla/websocket" ) // Server implements an RPC server. type Server struct { chans map[string]*channel onConnect func(c *Conn) upgrader websocket.Upgrader } // Config specifies a configuration for the server. type Config struct { ReadBufferSize, Writ...
// +build !partners package service_test import ( "fmt" "github.com/APTrust/exchange/service" "github.com/APTrust/exchange/util/logger" "github.com/APTrust/exchange/util/testutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "io/ioutil" "net/http" "net/url" "testing" "time" ) ...
package alipay import ( "crypto/rsa" "crypto/x509" "encoding/pem" "fmt" "log" ) type AlipayConfig struct { //↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ //合作身份者id,以2088开头的16位纯数字 Partner string //安全检验码,以数字和字母组成的32位字符 Key string //商户的私钥(后缀是.pen)文件相对路径 //如果签名方式设置为“0001”时,请设置该参数 Private_key_path []byte //支付宝公钥(后缀...
package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "strings" ) func region(ip ...string) string { method := "POST" ipStr, _ := json.Marshal(ip) //payload := strings.NewReader("[\"10.132.123.220\",\"10.134.41.91\"]") payload := strings.NewReader(string(ipStr)) client := &http.Client{} req...
package hooks import ( "fmt" "os" "github.com/cloudfoundry/libbuildpack" ) type hooks1 struct { libbuildpack.DefaultHook } type hooks2 struct { libbuildpack.DefaultHook } func init() { if os.Getenv("BP_DEBUG") != "" { libbuildpack.AddHook(hooks1{}) libbuildpack.AddHook(hooks2{}) } } func (h hooks1) Bef...
package devops import "testing" func TestBumpVersion(t *testing.T) { err := BumpVersion("dev") if err != nil { t.Errorf("E! %v", err) } err = BumpVersion("staging") if err != nil { t.Errorf("E! %v", err) } }
// Constantes package main import "fmt" import "math" const s string = "gopher" func main() { fmt.Println("s = ", s) const n = 500 const d = 3e20 / n fmt.Println("d = ", d) fmt.Println("int64(d) = ", int64(d)) fmt.Println("math.Sin(n) = ", math.Sin(n)) }
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under both the GPLv2 (found in the // COPYING file in the root directory) and Apache 2.0 License // (found in the LICENSE.Apache file in the root directory). // // Copyright (c) 2011 The LevelDB Authors. All rights r...
package media import ( "time" uuid "github.com/satori/go.uuid" ) type FileUpload struct { ID uuid.UUID `gorm:"type:char(36); primary_key"` Name string `gorm:"type:text; not null"` Size int64 `gorm:"type:int; not null"` Link string `gorm:"text; not null"` CreatedAt time.Time }
package systemed // 查看启动时的默认 Target func GetDefault(name string) ([]byte, error) { sys := NewSystemed("systemctl") sys.SetArgs("get-default").SetArgs(name) rs, err := sys.Exec() return rs, err } // 设置启动时的默认 Target func SetDefault(name string) ([]byte, error) { sys := NewSystemed("systemctl") sys.SetArgs("set-de...
package goWeb3 import ( "encoding/json" "errors" "fmt" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/radar-bear/goWeb3/helper" "github.com/sirupsen/logrus" "math/big" "os" "strings" ) // ============= Web3 ==...
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package router import ( "github.com/tailscale/wireguard-go/device" "github.com/tailscale/wireguard-go/tun" "tailscale.com/types/logger" ) // Ne...
/* The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,1...
package restAPI import ( "errors" "net/url" "reflect" ) func fetchStringParameter(f *url.Values, key string, required bool) (*string, error) { str := (*f)[key] if duplicated(str) { return nil, errors.New(key + " should be only one") } if invalidString(str) { if required { return nil, errors.New(key + " ...
package config // WorkerConfig holds all the different implementations for a persistence store service type WorkerConfig struct { Converter WorkerConverterConfig }
package goqueue import ( "context" "errors" "fmt" ) var ( ErrorQueueFull = errors.New("queue was full") ErrorQueueEmpty = errors.New("queue was empty") ) type Config struct { PushBlocking bool PopBlocking bool MaxBuffer int64 } type InMemoryQueue struct { Config receiver chan Task } func NewInMemory...
// Copyright 2021 Praetorian Security, 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 o...
package util import ( "math/rand" "time" ) var seededGenerator *rand.Rand = rand.New(rand.NewSource(time.Now().UnixNano())) var stringCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" func GenerateGameCode() string { b := make([]byte, 6) for i := range b { b[i] = stringCharset[seededGenerator.In...
package graphdb // Node represent graph's node type Node struct { Nodetype int16 ID []byte // must be 4byte Value []byte } // nodeKeyBytes return bytes array represent Node's key func nodeKeyBytes(node *Node) []byte { var retbyte [3]byte retbyte[0] = NODE retbyte[1] = byte((node.Nodetype >> 8) & 0xff) ...
package main import ( "fmt" "log" "net/http" "time" ) func hello(w http.ResponseWriter, r *http.Request) { token := r.Header.Get("Authorization") body := fmt.Sprintf("Hello World! (Authorization: %s, Time: %s)\n", token, time.Now().Format("2006-01-02 15:04:05 MST")) w.WriteHeader(http.StatusOK) w.Write([]byte...
package worker import ( "github.com/OHopiak/fractal-load-balancer/core" "github.com/jinzhu/gorm" "github.com/labstack/echo/v4" "github.com/pkg/errors" "net" "time" ) type ( Master struct { core.Host `json:"host"` Connected bool `json:"connected"` } Worker struct { core.Host ID *uint Master *Ma...
package models import ( "database/sql" "fmt" "github.com/hiraisin/go-postgre/config" ) func CheckLogin(username, password string) error { var obj User var pwd string con := config.CreateCon() sqlStatement := "SELECT id,username,password FROM users where username = ?" err := con.QueryRow(sqlStatement, user...
// Writing a basic HTTP server is easy using the // `net/http` package. package main import ( "encoding/json" "fmt" "net/http" cls "github.com/wgliang/tencentcloud-cls-sdk-go" ) // A fundamental concept in `net/http` servers is // *handlers*. A handler is an object implementing the // `http.Handler` interface. A...
package tcp import ( "time" ) const ( DEFAULT_PACK_HEAD_LEN = 8 DEFAULT_MAX_BODY_LEN = 16384 - 8 DEFAULT_RECV_BUF_LEN = 1024 * 4 DEFAULT_SEND_BUF_LEN = 1024 * 4 DEFAULT_MAX_PACK_LEN = 1024 * 1024 DEFAULT_KEEP_ALIVE_TIME = time.Second * 60 DEFAULT_RECV_BLOCK_TIME = time.Second * 20 DEFAULT_SEND_BLO...
/* Copyright IBM Corporation 2020 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 di...
package middleware import ( "github.com/gin-gonic/gin" ) func TraceHandelMiddleWare() gin.HandlerFunc { return func(c *gin.Context) { headers := []string{ "X-Request-Id", "X-B3-TraceId", "X-B3-SpanId", "X-B3-ParentSpanId", "X-B3-Sampled", "X-B3-Flags", "X-Ot-Span-Context", "appid", "X...
package profile import ( // "github.com/bwmarrin/discordgo" // "encoding/json" // "../errors" "encoding/json" "errors" "github.com/gorilla/Schema" // "html" "io/ioutil" "log" "net/http" "net/url" "strconv" "strings" ) const COOKIE_COST = 20 type UserData struct { Cookies int Id string Username...
package struct_flags import ( "context" "encoding/json" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gopkg.in/go-playground/validator.v9" "io/ioutil" "os" "testing" ) func TestFlagSet_UnmarshalFlags(t *testing.T) { type Object struct { String1 string `flag:"string1" usage:"n...
package main import ( "errors" ) type Cell int const ( Empty Cell = iota Circle Cross ) func (c *Cell) Reversed() Cell { switch *c { case Circle: return Cross case Cross: return Circle default: return Empty } } func (c *Cell) Appearance() rune { switch *c { case Circle: return 'o' case Cross: ...
package payments import ( "fmt" "reflect" "git.zhuzi.me/zzjz/zhuzi-payment/lib/log" "git.zhuzi.me/zzjz/zhuzi-payment/model/payment_order" ) type Wx struct { OrderID string // 订单号 TransactionID string // 支付交易号 TotalFee int // 订单金额(单位分) ReturnData []byte // 返回回调数据 AttachDa...
package main import ( "fmt" "strings" ) // 切割字符串 func Split(str string, seq string)[]string { var ret [] string index := strings.Index(str, seq) for index > 0 { ret = append(ret, str[:index]) str = str[index+1:] index = strings.Index(str, seq) } ret = append(ret, str) return ret } func main() { fmt.P...
package logger import ( "testing" ) func TestConsole(t *testing.T) { lg := NewLogger(10000) lg.SetFuncDepth(2) lg.SetPrefix("consoletest") lg.SetLogger(CONSOLE_PROTOCOL, "") lg.Panic("Panic") lg.Error("error") lg.Warn("warn") lg.Info("info") lg.Debug("debug") t.Log("console test success.") }
package main import "fmt" type contactInfo struct { email string } type person struct { firstName string lastName string contact contactInfo } func main() { mike := person { firstName: "Mike", lastName: "Sanford", contact: contactInfo { email : "mikethecodegeek@gmail.com", }, } mike.update...
/* * @lc app=leetcode.cn id=1185 lang=golang * * [1185] 一周中的第几天 */ package main import ( "time" ) // @lc code=start func dayOfTheWeek(day int, month int, year int) string { t := time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.Now().Location()) return t.Weekday().String() } // func main() { // fmt.Pri...
package common import "fmt" func Pslice(slice *[]int) { for _,v := range *slice { fmt.Printf("%v ", v) } fmt.Printf("\n") } func PsliceS(slice *[]string) { for _,v := range *slice { fmt.Printf("%v ", v) } fmt.Printf("\n") } func Pmap(m *map[string]string) { for k,v := range *m { fmt.Printf("k -> %v, v ...
package main type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // 递归 + 外部变量 实现后序遍历 var postorderSequence []int func postorderTraversal(root *TreeNode) []int { postorderSequence = make([]int, 0) postorderTraversalExec(root) return postorderSequence } func postorderTraversalExec(root *TreeNode) {...
package diffbot import ( "testing" "github.com/stretchr/testify/assert" ) func TestArticle(t *testing.T) { c := client() url := "http://www.dailymail.co.uk/sciencetech/article-2355833/Apples-iPhone-5-hated-handset--majority-people-love-Samsung-Galaxy-S4-study-finds.html" in := c.NewArticleInput(url) out, err :...
package main import ( "io" "io/ioutil" "os" "path/filepath" "sort" "strconv" ) const prefix = "───" const middle = "├" const middleParent = "│" const last = "└" func main() { out := os.Stdout if !(len(os.Args) == 2 || len(os.Args) == 3) { panic("usage go run main.go . [-f]") } path := os.Args[1] printFi...
package main /** 329. 矩阵中的最长递增路径 给定一个整数矩阵,找出最长递增路径的长度。 对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。 示例1: ``` 输入: nums = [ [9,9,4], [6,6,8], [2,1,1] ] 输出: 4 解释: 最长递增路径为 [1, 2, 6, 9]。 ``` 示例2: ``` 输入: nums = [ [3,4,5], [3,2,6], [2,2,1] ] 输出: 4 解释: 最长递增路径是 [3, 4, 5, 6]。注意不允许在对角线方向上移动。 ``` ``` */...
package pwh var defaultPWH = New("gox", 10) func Config(publicSalt string, cost int) { defaultPWH.Config(publicSalt, cost) } func Hash(word string, salt string) string { return defaultPWH.Hash(word, salt) } func Match(word string, salt string, hash string) bool { return defaultPWH.Match(word, salt, hash) }
package utils import ( "io" "net/http" "fmt" "io/ioutil" ) func Get(url string,body io.Reader,head,fdata map[string]string)([]byte,error) { return sendHttpRequest("GET",url,body,head,fdata) } func Post(url string,body io.Reader,head,fdata map[string]string)([]byte,error) { return sendHttpRequest("POST",url,body...
package discord import ( "fmt" ) // User defines a user of Disord type User struct { ID string `json:"id"` Name string `json:"username"` Email string `json:"email"` Verified bool `json:"verified"` Avatar string `json:"avatar"` // TODO: Sometimes int, sometimes string. // Discriminator string...
// ----------------------------------------------------------------------------- // Common package used for containing shared code. // ----------------------------------------------------------------------------- package common import ( "fmt" "log" "github.com/streadway/amqp" ) // Constants related to the RabbitM...
package main import "math" /* * @lc app=leetcode id=99 lang=golang * * [99] Recover Binary Search Tree */ /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ /* 我喜欢这道题 首先将问题简化,如果给的是一个有序数组,然后打乱某两个元素的次序, 如何找到...
package rpc_user import ( "context" "fmt" "github.com/bqxtt/book_online/rpc/clients/rpc_user/userpb" "testing" ) func TestUserService(t *testing.T) { Init() resp, err := UserServiceClient.Register(context.Background(), &userpb.RegisterRequest{ UserAuth: &userpb.UserAuth{ UserId: 321, PwdDigest: "333"...
package factories import ( "github.com/barrydev/api-3h-shop/src/common/connect" "github.com/barrydev/api-3h-shop/src/connections" "github.com/barrydev/api-3h-shop/src/model" ) func FindCustomer(query *connect.QueryMySQL) ([]*model.Customer, error) { connection := connections.Mysql.GetConnection() queryString :=...
package setr import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document01100104 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:setr.011.001.04 Document"` Message *SubscriptionOrderCancellationRequestV04 `xml:"SbcptOrdrCxlReq"` }...
// models/book.go package models import ( "context" "log" "net/http" "time" "github.com/gin-gonic/gin" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" ) // Book Data Structure type Book struct { // ID string `bson:"_id, omitempty"` Title string `bson:"title, omitempt...
package public const ( ValidatorKey = "ValidatorKey" TranslatorKey = "TranslatorKey" )
package config import ( "errors" "fmt" "os" "strings" ) type Environment struct { DB DB Mastodon Mastodon Queue Queue Port string UserID int64 } type DB struct { Host string Database string Username string Password string } type Mastodon struct { ServerURL string AccessToken string } type...
package resources import ( . "goa.design/goa/v3/dsl" ) var JWTSec = JWTSecurity("jwt", func() { Description("JWT Authentication Security") }) var APIKeyAuth = APIKeySecurity("api_key", func() { Description("API Key for users API") })
package utils import "time" func JustifyTime(source time.Time, adjustment time.Time) time.Time { return time.Date(adjustment.Year(), adjustment.Month(), adjustment.Day(), source.Hour(), source.Minute(), 0, 0, time.UTC) }
package workqueue import ( "context" "database/sql" "sync" "time" "github.com/Masterminds/squirrel" "github.com/jmoiron/sqlx" "github.com/pkg/errors" "gopkg.in/tomb.v2" "git.scc.kit.edu/sdm/lsdf-checksum/meda" ) type transactionState int8 const ( transactionStateUninitialised transactionState = iota tra...