text
stringlengths
11
4.05M
package awspreset import ( "crypto/hmac" "crypto/sha1" "encoding/base32" "encoding/binary" "fmt" "math" "time" "github.com/pkg/errors" ) var now = time.Now const ( digits = 6 timestep = 30 values = 2 ) const ( errFailedToParseSecret = "failed to parse base32 encoded secret" errFailedToWriteHMAC ...
package quiz import ( "github.com/evleria/quiz-cli/pkg/config" "math/rand" ) type Runner struct { questions []config.Question history []answer current int } type Result struct { Correct int Total int WrongQuestions []answeredQuestion } type answer struct { Indices []int Correct bool } ...
package pgsql import ( "database/sql" "database/sql/driver" "strconv" ) // LsegFromFloat64Array2Array2 returns a driver.Valuer that produces a PostgreSQL lseg from the given Go [2][2]float64. func LsegFromFloat64Array2Array2(val [2][2]float64) driver.Valuer { return lsegFromFloat64Array2Array2{val: val} } // Lse...
package main import ( "coolpy7_benchmark/src/client" "coolpy7_benchmark/src/packet" "flag" "fmt" "log" "os" "os/signal" "strconv" "strings" "syscall" "time" ) var urlString = flag.String("url", "tcp://127.0.0.1:1883", "broker url") var topic = flag.String("topic", "cp7sub%i", "the used topic") var workers ...
package find // Find return the first index that b in a, realized the RK string search algo func Find(a, b string) int { n, m := len(a), len(b) if n == 0 || m == 0 || m > n { return -1 } var ah, bh int for j := 0; j < m; j++ { bh = bh + int(b[j]) } for i := 0; i < n-m+1; i++ { if i == 0 { for j := 0...
package api import ( ) //Init 不晓得思昊要干什么无害先保留 func Init() { //InitRfs() InitReset() }
// Copyright 2019 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 ( "fmt" . "leetcode" ) func main() { fmt.Println(deleteDuplicates(&ListNode{ Val: 1, Next: &ListNode{ Val: 2, Next: &ListNode{ Val: 3, Next: &ListNode{ Val: 3, Next: &ListNode{Val: 5}, }, }, }, })) } //leetcode submit region begin(Prohibit modification a...
package main import ( "flag" "net" "os" "os/signal" "pancakebasspanda/grpc-message-service/protos" "pancakebasspanda/grpc-message-service/server" "github.com/sirupsen/logrus" "google.golang.org/grpc" ) const appName = "message-service" var ( level string address string ) func init() { flag.StringVar(&...
package events import ( "context" "fmt" "mysql-metadata/constant" "cloud.google.com/go/pubsub" ) type pubSubEvent struct { ctx context.Context client *pubsub.Client topic *pubsub.Topic } var event *pubSubEvent // Initialize block to setup pubsub clients. // Create subscription with hostname func init() ...
package main import ( "fmt" "math" "time" ) func scanEpoch(value string, epoch time.Time) time.Time { parsed_time, parse_error := time.Parse("1/2/2006", value) if parse_error != nil { return epoch } return parsed_time } func scanOffset(value string, file_pos int) int { var err error expression := "" scan...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/11/26 9:31 上午 # @File : lt_217_存在重复的元素.go # @Description : # @Attention : */ package v2 // 关键: // 可以用hashSet来做,也可以排序然后比较前后来做 func containsDuplicate(nums []int) bool { containsDuplicateQSort(nums, 0, len(nums)-1) for i := 0; i < len(nums); i++ { if i+1 < l...
// Written in 2014 by Petar Maymounkov. // // It helps future understanding of past knowledge to save // this notice, so peers of other times and backgrounds can // see history clearly. package be import ( cir "github.com/hoijui/escher/pkg/circuit" ) // create all links before materializing gates func createLinks(d...
package filemonitor import ( "context" "github.com/fsnotify/fsnotify" "github.com/sirupsen/logrus" ) type watcher struct { notify *fsnotify.Watcher pathsToWatch []string logger logrus.FieldLogger onUpdateFn func(logrus.FieldLogger, fsnotify.Event) } // NewWatch sets up monitoring on a slice of ...
package conn import ( "fmt" "github.com/gomodule/redigo/redis" ) func NewRedisClient(host string, port int) (redis.Conn, error) { conn, err := redis.Dial("tcp", fmt.Sprintf("%s:%d", host, port)) if err != nil { return nil, err } return conn, err }
package controllers import ( "services" "log" "encoding/binary" "errors" ) func StartUDPController(myPeer *services.Peer) { log.Println("StartUDPController: Started UDP Controller") go func() { for msg := range services.CommunicationChannelUDPMessages { handleUDPMessage(msg, myPeer) } }() } func handl...
package scanner import ( "fmt" "go/token" "path/filepath" "unicode/utf8" "h12.io/gombi/experiment/gre/scan" ) const ( firstOp = int(token.ADD) lastOp = int(token.COLON) ) const ( ScanComments Mode = 1 << iota // return comments as COMMENT tokens dontInsertSemis // do not automatically ...
package config import ( "github.com/lfmexi/tcpgateway/events" "github.com/lfmexi/tcpgateway/kafkasource" "github.com/confluentinc/confluent-kafka-go/kafka" ) func createConsumerFactory() kafkasource.CreateKafkaConsumer { return func(groupID string) (kafkasource.KafkaConsumer, error) { responsesConfig := configu...
package testing import ( "context" "net/http" "reflect" "testing" "github.com/selectel/go-selvpcclient/selvpcclient/resell/v2/quotas" "github.com/selectel/go-selvpcclient/selvpcclient/testutils" ) func TestGetAllQuotas(t *testing.T) { endpointCalled := false testEnv := testutils.SetupTestEnv() defer testEn...
package middlewares import ( "context" "github.com/go-chi/chi" _model "github.com/shipu/tracker/app/models" _repo "github.com/shipu/tracker/app/repositories" "github.com/shipu/tracker/app/response" "net/http" ) func ActivityMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.Respon...
package protocol import ( "bytes" "fmt" "github.com/sbunce/bson" ) type OpCode int32 const ( HeaderLength = 16 OpCodeReply OpCode = 1 OpCodeMsg OpCode = 1000 OpCodeUpdate OpCode = 2001 OpCodeInsert OpCode = 2002 OpReserved OpCode = 2003 OpCodeQuery OpCode = 2004 OpCodeGetM...
package exporter import ( "fmt" "github.com/blockassets/cgminer_client" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "io/ioutil" "net/http/httptest" "testing" "time" ) func TestNewExporter(t *testing.T) { cgClient := cgminer_client.New("10.10.0.11...
// Copyright ©2014 The Gonum 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 mat32 import ( "github.com/pa-m/mat32/internal/asm/f32" "gonum.org/v1/gonum/blas/blas32" ) // Inner computes the generalized inner product // ...
package main import "fmt" type processFun func(int) bool // 声明一个函数类型 func main() { fmt.Println("hello func 40 03") nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} fmt.Println("nums=", nums) even := filter(nums, isEven) fmt.Println(even) fmt.Println(filter(nums, isOdd)) } func isEven(num int) bool { /* 判断是否为偶数...
package main import ( "time" ) type GenericError struct { Description string `json:"description"` } type MutedError struct { GenericError MuteTimeLeft int64 `json:"muteTimeLeft"` } func NewMutedError(duration time.Duration) MutedError { return MutedError{ GenericError{"muted"}, int64(duration / time.Second...
package reverse import ( "unicode/utf8" ) // String returns the input as reversed string func String(str string) (result string) { for len(str) > 0 { r, size := utf8.DecodeLastRuneInString(str) str = str[:len(str)-size] result = result + string(r) } return result }
package main import ( "crypto/aes" "crypto/cipher" "crypto/rand" f "fmt" "io" ) func main() { key := "Hello Key 123456" s := `동해 물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라 만세. 무궁화 삼천리 화려강산 대한 사람, 대한으로 길이 보전하세.` block, err := aes.NewCipher([]byte(key)) if err != nil { f.Println(err) return } cipherText := encry...
// Copyright 2019 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 git /* #include <git2.h> extern int _go_git_treewalk(git_tree *tree, git_treewalk_mode mode, void *ptr); */ import "C" import ( "runtime" "unsafe" ) // MessageEncoding is the encoding of commit messages. type MessageEncoding string const ( // MessageEncodingUTF8 is the default message encoding. Message...
/* Copyright 2020 The SuperEdge 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, s...
package main import ( "C" ) import "math" func Round(f float64, n int) float64 { pow10_n := math.Pow10(n) return math.Trunc((f+0.5/pow10_n)*pow10_n) / pow10_n } //export GoAdd func GoAdd(a, b float64) int { var abc []float64 var c float64 // hinge_y := 0.0 c = Round((a + b), 1) abc = append(abc, a, b, c) re...
package progressbar import ( "strings" "github.com/fatih/color" ) type StandardProgressTheme struct { filledColor *color.Color surroundColor *color.Color } func NewStandardTheme() *StandardProgressTheme { return &StandardProgressTheme{filledColor: color.New(color.FgHiCyan), surroundColor: color.New(color.Bol...
package controller import ( "config" "constant" "fmt" "model" "net/http" "time" "util" "util/context" "github.com/labstack/echo" "github.com/sirupsen/logrus" ) /** * @apiDefine CreateFeedback CreateFeedback * @apiDescription 添加反馈 * * @apiParam {String} contact_way 联系方式 * @apiParam {String} content 内...
package main import ( "fmt" ) func main() { m := map[string][]string{ `bond_james`: []string{`Shaken, not stirred`, `Martinis`, `Women`}, `moneypenny_miss`: []string{`James Bond`, `Literature`, `Computer Science`}, `no_dr`: []string{`Being evil`, `Ice cream`, `Sunsets`}, } fmt.Println(m) m...
package main import ( "bufio" "bytes" "fmt" "io" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) type ProtocolTestSuite struct { suite.Suite msg *Message buf *bytes.Buffer r *bufio.Reader } func (s *ProtocolTestSuite) SetupTest() { s.msg = &Message{} s.buf = bytes...
// Copyright 2020 MongoDB 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...
package main import ( "context" "log" "net" "os" gpay "app/payment-service/proto" payjp "github.com/payjp/payjp-go/v1" "google.golang.org/grpc" "google.golang.org/grpc/reflection" ) const ( port = ":50051" ) type server struct{} func (s *server) Charge(ctx context.Context, req *gpay.ChargeRequest) (*gpay...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //795. Number of Subarrays with Bounded Maximum //We are given an array A of positive integers, and two positive integers L and R (L <= R). //Return th...
package tablewriter import ( "encoding/csv" "io" ) type CSVTableWriter struct { io.Writer header []string footer []string rows [][]string } func NewCSVTableWriter(w io.Writer) *CSVTableWriter { return &CSVTableWriter{ Writer: w, } } func (c *CSVTableWriter) SetHeader(keys []string) { c.header = keys }...
package main import "fmt" func main() { mySlice := []int{42, 43, 44, 45, 46, 47, 48, 49, 50, 51} mySlice = append(mySlice, 52) fmt.Println(mySlice) mySlice = append(mySlice, 53, 54, 55) fmt.Println(mySlice) y := []int{56, 57, 58, 59, 60} mySlice = append(mySlice, y...) fmt.Println(mySlice) }
// Copyright 2016 Matthew Endsley // All rights reserved // // Redistribution and use in source and binary forms, with or without // modification, are permitted providing that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions ...
package clevels import ( "os" "strconv" "strings" "testing" "time" "github.com/stretchr/testify/assert" ) func TestParseAusterityLevel(t *testing.T) { type ParseAusterityTestCase struct { Contents string Expected AusterityLevel ExpectedError error } cases := []ParseAusterityTestCase{ { ...
package paperswithcode_go import ( "fmt" "github.com/codingpot/paperswithcode-go/v2/models" "net/url" ) // PaperTaskList returns tasks (an area of research) for the given paper. func (c *Client) PaperTaskList(paperID string) (*models.TaskList, error) { pURL := fmt.Sprintf("%s/papers/%s/tasks/", c.baseURL, url.Que...
package main import ( "bufio" "errors" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "strings" "sync" "time" ) const ( filesDir = "arquivos" dictionaryFile = "dictionary.txt" resultFilePath = "result.txt" ) var resultFile *os.File func main() { createResultFile() defer resultFile.Close() ...
/** * Author: Admiral Helmut * Created: 12.06.2019 * * (C) **/ package routes import ( "github.com/efi4st/efi4st/dbprovider" "github.com/efi4st/efi4st/analysis" "encoding/json" "fmt" _ "github.com/go-sql-driver/mysql" "github.com/kataras/iris/v12" "io/ioutil" "strconv" "strings" "time" ) func Tes...
package mxdisk import ( "fmt" "os" "os/exec" "path/filepath" "regexp" "strings" ) // UdevadmInfo for mapping from: // /sbin/udevadm info -q all -n /dev/sda1 (old and new Linux OS supports these format) // newer Linux OS must works with: /sbin/udevadm info -p /sys/class/block/devXX type UdevadmInfo struct { //...
package log import ( "runtime" "strconv" ) // funcName get func name. func funcName(skip int) (name string) { if _, file, lineNo, ok := runtime.Caller(skip); ok { return file + ":" + strconv.Itoa(lineNo) } return "unknown:0" }
package main import ( "context" "errors" "fmt" "io/ioutil" "net/http" "regexp" "sync" "time" ) func main() { ctx, ctxCancel := context.WithTimeout(context.Background(), 3000*time.Millisecond) defer ctxCancel() urls := []string{ "https://www.amazon.com", "https://www.google.com", "https://www.youtube...
package load import ( "context" "github.com/mszostok/codeowners-validator/internal/check" "github.com/mszostok/codeowners-validator/internal/envconfig" "github.com/mszostok/codeowners-validator/internal/github" "github.com/pkg/errors" ) // For now, it is a good enough solution to init checks. Important thing i...
// Unless explicitly stated otherwise all files in this repository are licensed // under the Apache License Version 2.0. // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2016-2019 Datadog, Inc. package debug import ( "net/http/pprof" "github.com/datadog/extendeddaem...
package main import ( "log" "github.com/pulumi/pulumi/sdk/v2/go/pulumi" ) func main() { pulumi.Run(func(ctx *pulumi.Context) error { bucket, err := PulumiDeployS3ForStatic(ctx) if err != nil { log.Fatal(err) } err = PulumiDeployStatic(ctx, bucket) if err != nil { log.Fatal(err) } ctx.Export(...
package _9_Palindrome_Number func isPalindrome(x int) bool { var n int if x < 0 || (x%10 == 0 && x != 0) { return false } for { if n >= x { break } n = n*10 + x%10 x = x / 10 } return n == x || n/10 == x }
package helpers import ( "io/ioutil" "strings" ) func GetFile(path string) []string { file, err := ioutil.ReadFile(path) if err != nil { panic(err) } values := strings.Split(string(file), "\n") return values }
package databaseConfig import mgo "gopkg.in/mgo.v2" func DbDetails() *mgo.Session { session, err := mgo.Dial("mongodb://localhost:27017") if err != nil { panic(err) } session.SetMode(mgo.Monotonic, true) return session } func CrudCollection(session *mgo.Session) *mgo.Collection { return session.DB("crud_db")...
package main import "fmt" import "expvar" import "net/http" var visits = expvar.NewInt("visitss") func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8000", nil) } func handler(w http.ResponseWriter, r *http.Request) { visits.Add(1) fmt.Fprintf(w, "Hi there, i love %s", r.URL.Path[1:]) } // 查看htt...
package c30_break_md4_length_extension import ( "crypto/rand" "testing" ) func TestMD4System(t *testing.T) { key := make([]byte, 16) rand.Read(key) s := NewMD4System(key) message := []byte("Some text") mac := s.MAC(message) if !s.Verify(mac, message) { t.Errorf("Incorrect verification. Expected true") } ...
package sql import ( "context" "github.com/gremlinsapps/avocado_server/api/model" "github.com/gremlinsapps/avocado_server/dal/model" "github.com/jinzhu/gorm" ) type MeasurementRepository struct { conn *DBConnection } func CreateMeasurementRepo(container DBConnectionContainer) (*MeasurementRepository, error) { ...
// http codecs plugin package http_codecs
package goSolution func maxAreaOfIsland(grid [][]int) int { n, m := len(grid), len(grid[0]) t := 1 ret := 0 for i := 0; i < n; i++ { for j := 0; j < m; j++ { if grid[i][j] == 1 { q := [][]int{{i, j}} t += 1 grid[i][j] = t for h := 0; h < len(q); h++ { x, y := q[h][0], q[h][1] for d ...
package models // StatusResponse is the server status response payload, // gets sent back on GET / type StatusResponse struct { Status string `json:"status"` ServerID string `json:"serverId"` } // NewStatusResponse creates a new response to send out with the // given server ID func NewStatusResponse(serverID stri...
package auth import ( "crypto/rsa" "os" "reflect" "testing" "github.com/satori/go.uuid" "github.com/stretchr/testify/mock" "github.com/tppgit/we_service/config" "github.com/tppgit/we_service/entity/user" ) type mockUserRepo struct { mock.Mock user.UserRepository } func (m *mockUserRepo) GetUserByEmail(ema...
package main import ( "bytes" "errors" "fmt" "go/format" "html/template" "io/ioutil" "path" "strings" "sync" "time" "github.com/andersfylling/disgord/internal/constant" "github.com/gocolly/colly" ) func main() { fmt.Println(1) genPermissions() } func newScraper() *colly.Collector { c := colly.NewCol...
package game import ( flatbuffers "github.com/google/flatbuffers/go" m "github.com/yanpozka/checkers/game/messages" ) // const ( StatusWaitingOpponent int8 = iota + 1 StatusPlaying StatusEnded ) // const ( PlayerA int8 = 1 PlayerB = 2 ) var gameBuilder = flatbuffers.NewBuilder(0) // InitGame creates an...
package main import ( "encoding/json" "io/ioutil" "log" ) type Config struct { Adminaddress string Frontendaddress string DBPath string FilesPath string AssetPath string Mailserver string MailSendername string } func loadconfig(configfilepath string) Config { file, err := io...
package main import ( "flag" "fmt" "io/ioutil" "log" "net" "net/http" "strings" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/route53" ) var urls = []string{ "http://whatismyip.akamai.com/", "http://checkip.amazonaws.com", "https://che...
package main import ( "encoding/json" "fmt" ) type Stu struct { Name string `json:"name_param"` Age int `json:"age"` Score float32 `json:"score"` } func main() { //初始化 var stu Stu stu.Name = "heylink" stu.Age = 25 stu.Score = 99.9 //打包 通过反射拿到tag data, err := json.Marshal(stu) if err != nil { retur...
package golang import ( "sort" ) func findBestValue(arr []int, target int) int { sort.Ints(arr) length := len(arr) idx, prevSum := getIdxPrevSum(target, length, arr) if idx == length { return arr[length-1] } else if idx == 0 { mod := target % length quotient := target / length if mod <= (length / 2) ...
package main func yonghu(stunum int,username string)(Choose,error){ var choose Choose err := db.Where(Choose{Stunum: stunum}).Attrs(Choose{Username: username}).FirstOrCreate(&choose).Error//如果没有该记录就自动增加 return choose,err } func queryclass(dacourse_num string)(Class,error){ var class Class err := db.Model(&Class{...
package kinetic import awsKinesis "github.com/aws/aws-sdk-go/service/kinesis" // Message represents an item on the Kinesis stream type Message struct { awsKinesis.Record } // Init initializes a Message. // Currently we are ignoring sequenceNumber. func (k *Message) Init(msg []byte, key string) *Message { return &M...
// Package registry implements a service registry server. package registry import ( "io" registrypb "github.com/pomerium/pomerium/pkg/grpc/registry" ) // Interface is a registry implementation. type Interface interface { registrypb.RegistryServer io.Closer }
package moduleMemberServices import ( "web/ant/kernel" "web/ant/kernel/databases" "web/ant/models" ) /** * 会员服务结构体, 提供会员服务相关业务方法. */ type MemberService struct{} /** * 获取所有会员信息 * * param map[string]string condition * return string */ func (this MemberService) FetchAllMembers(condition map[string]string) str...
package main import ( "context" "fmt" "github.com/caarlos0/env" "github.com/jackc/pgx/v4" es "github.com/pkg/errors" tgbotapi "gopkg.in/telegram-bot-api.v4" "strconv" ) type UserMessage struct { bot *tgbotapi.BotAPI connection *pgx.Conn update *tgbotapi.Update } func NewUserMessage(bot *tgbotapi...
// Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net> // released under the MIT license package ircbnc import ( "fmt" "net" "runtime/debug" "strings" "sync" "time" "code.cloudfoundry.org/bytefmt" "log" "github.com/goshuirc/bnc/lib/ircclient" "github.com/goshuirc/irc-go/ircmsg" ) // Registration...
package test import ( "testing" "github.com/a-h/generate/test/abandoned_gen" ) func TestAbandoned(t *testing.T) { // this just tests the name generation works correctly r := abandoned.Root{ Name: "jonson", Abandoned: &abandoned.PackageList{}, } // the test is the presence of the Abandoned field if r.A...
package service import ( "context" entity "github.com/aleale2121/Golang-TODO-Hex-DDD/internal/constant/model" protos "github.com/aleale2121/Golang-TODO-Hex-DDD/internal/grpc/note" noteServ "github.com/aleale2121/Golang-TODO-Hex-DDD/internal/module/user" ) type noteServiceServer struct { service noteServ.UseCase ...
package suites // This scenario is used to test sign in using the user email address. import ( "context" "fmt" "log" "testing" "time" "github.com/stretchr/testify/suite" ) type SigninEmailScenario struct { *RodSuite } func NewSigninEmailScenario() *SigninEmailScenario { return &SigninEmailScenario{ RodSu...
package main import "fmt" // GeoPoint maps against Postgis geographical point type GeoPoint struct { Lat float64 `json:"lat"` Lng float64 `json:"lng"` } func (p *GeoPoint) String() string { return fmt.Sprintf("POINT(%v %v)", p.Lat, p.Lng) } // Scan implements the Scanner interface and will scan the Postgis POINT...
package sqlc import ( "database/sql" "github.com/DemoHn/obsidian-panel/pkg/dbmigrate" // init migrations _ "github.com/DemoHn/obsidian-panel/app/sqlc/migrations" ) // MigrateUp - func MigrateUp(db *sql.DB) error { return dbmigrate.Up(db) } // MigrateDown - func MigrateDown(db *sql.DB, step int) error { return...
package main import ( "github.com/fberrez/forum/controller" "github.com/fberrez/forum/middleware" "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" ) func getRouter() *gin.Engine { router := gin.New() router.Use(middleware.CORSMiddleware()) router.Use(gin.Logger()) router.Use(gin.Recovery()) store...
package main type query func(string) string func exec(name string,vs ...query) string { ch :=make(chan string) fn := func(i int) { ch <- vs[i](name) } for i, _ := range vs { go fn(i) } return <-ch } //func main() { // // querys :=[]query{} // querys1 := func(n string) string { // return n+"func1" // } ...
// 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 main import ( "fmt" "github.com/glenbolake/aoc2018" "math" ) const ( depth = 4845 targetX = 6 targetY = 770 ) const ( rocky = 0 wet = 1 narrow = 2 ) var erosionMemo = map[aoc2018.Coord]int{} func calcErosion(x, y int) int { input := aoc2018.Coord{X: x, Y: y} value, seen := erosionMemo[inpu...
package main import ( "os" command "./internal/commands" "github.com/urfave/cli" ) func main() { app := cli.NewApp() app.Name = "lavar" app.Usage = "This app is management gitlab variables." app.Version = "0.0.1" app.Commands = []cli.Command{ command.ExportCommand(), command.ImportComma...
package powerdns import ( "context" "fmt" "net/url" ) // ServersService handles communication with the servers related methods of the Client API type ServersService service // Server structure with JSON API metadata type Server struct { Type *string `json:"type,omitempty"` ID *string `json:"id,omi...
package fetch import ( "time" "github.com/sirupsen/logrus" "github.com/slotix/dataflowkit/splash" ) // LoggingMiddleware logs Service endpoints func LoggingMiddleware(logger *logrus.Logger) ServiceMiddleware { return func(next Service) Service { return loggingMiddleware{next, logger} } } // Make a new type a...
// This file was generated for SObject DatacloudDandBCompany, API Version v43.0 at 2018-07-30 03:47:46.195324381 -0400 EDT m=+32.539151774 package sobjects import ( "fmt" "strings" ) type DatacloudDandBCompany struct { BaseSObject City string `force:",omitempty"` CompanyCurrencyIsoCode ...
package main import ( "bufio" "errors" "fmt" "log" "os" "strconv" "strings" "github.com/howeyc/gopass" "github.com/resin-os/resin-provisioner/provisioner" "github.com/resin-os/resin-provisioner/resin" "github.com/spf13/cobra" ) func init() { // show date/time in log output. log.SetFlags(log.LstdFlags) }...
package pie // Reduce continually applies the provided function // over the slice. Reducing the elements to a single value. // // Returns a zero value of T if there are no elements in the slice. It will // panic if the reducer is nil and the slice has more than one element (required // to invoke reduce). Otherwise ret...
package remark import ( "github.com/go-jar/goerror" "github.com/go-jar/gohttp/query" "github.com/go-jar/mysql" "blog/entity" "blog/errno" "blog/svc/remark" ) func (rc *RemarkController) DescribeAction(context *RemarkContext) { qp, err := rc.parseDescribeActionParams(context) if err != nil { context.ApiData...
package main import ( "log" "api-gaming/internal/config" "context" routes "api-gaming/internal/handlers" ) func init() { config.InitRedis() config.InitMux() //config.InitGoogle() } func main() { connDB, err := config.InitDB() if err != nil { log.Fatal(err) return } defer connDB.Close(context.Ba...
// 18. Implement CTR, the stream cipher mode package main import ( "crypto/aes" "crypto/cipher" "encoding/base64" "encoding/binary" "flag" "fmt" "io" "io/ioutil" "os" ) const secret = "YELLOW SUBMARINE" func main() { c, err := aes.NewCipher([]byte(secret)) if err != nil { panic(err) } iv := make([]by...
package main import ( "net/http" _ "github.com/jinzhu/gorm/dialects/mssql" "github.com/rprajapati0067/echo-web-framework/src/controllers" "github.com/labstack/echo" ) func main() { e := echo.New() // db, err := gorm.Open("mssql", "sqlserver://ravi:System123@LT212-RAVISP:1433?database=employee_db") // if err...
package bus import ( "io" "os" "runtime" "unsafe" "github.com/zyxar/berry/sys" ) const ( spiIoctlMAGIC = 'k' spiDev0 = "/dev/spidev0.0" spiDev1 = "/dev/spidev0.1" ) type spiIoctlTransfer struct { TxBuf, RxBuf uint64 Length, SpeedHz uint32 DelayUsecs uint16 BitsPerWo...
/* _ _ *__ _____ __ ___ ___ __ _| |_ ___ *\ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \ * \ V V / __/ (_| |\ V /| | (_| | || __/ * \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___| * * Copyright © 2016 - 2019 Weaviate. All rights reserved. * LICENSE: https://github.com/semi-techno...
package main // 9x9 数独校验 func isValidSudoku(board [][]byte) bool { return true }
// Copyright 2021 Clivern. All rights reserved. // Use of this source code is governed by the MIT // license that can be found in the LICENSE file. package definition import ( "fmt" ) const ( // MySQLService const MySQLService = "mysql" // MySQLPort const MySQLPort = "3306" // MySQLDockerImage const MySQLDo...
/* * @lc app=leetcode id=61 lang=golang * * [61] Rotate List * * https://leetcode.com/problems/rotate-list/description/ * * algorithms * Medium (27.44%) * Likes: 644 * Dislikes: 828 * Total Accepted: 200K * Total Submissions: 728.6K * Testcase Example: '[1,2,3,4,5]\n2' * * Given a linked list, rot...
package utils import ( "strconv" "strings" ) func StringConvUint(UuidS string) (UuidU uint) { UuidI, _ := strconv.ParseUint(UuidS, 0, 64) UuidU = uint(UuidI) return } func StringConvInt(str string) (int int) { int, _ = strconv.Atoi(str) return } func StringConvJoin(f, l string) (s string) { s = strings.Join...
package filters import ( "fmt" "github.com/loft-sh/vcluster/pkg/authorization/delegatingauthorizer" "github.com/loft-sh/vcluster/pkg/server/handler" requestpkg "github.com/loft-sh/vcluster/pkg/util/request" "github.com/loft-sh/vcluster/pkg/util/translate" corev1 "k8s.io/api/core/v1" kerrors "k8s.io/apimachinery...
package compute import ( "fmt" "net/http" "net/http/httptest" "testing" ) // Deploy network domain (successful). func TestClient_DeployNetworkDomain_Success(test *testing.T) { expect := expect(test) testServer := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { re...