text
stringlengths
11
4.05M
// Copyright 2012 The golibpcap 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 pkt /* #include <net/ethernet.h> #include <netinet/ether.h> #include <netinet/in.h> // http...
// https://en.wikipedia.org/wiki/Koch_snowflake package main import ( "fmt" "math" "runtime" "time" "github.com/go-gl/gl/v4.1-core/gl" "github.com/go-gl/glfw/v3.1/glfw" mgl "github.com/go-gl/mathgl/mgl32" "github.com/nicholasblaskey/go-learn-opengl/includes/shader" "github.com/nicholasblaskey/animations/f...
package xattr import "errors" import "os" var XAttrErrorAttributeNotFound = errors.New("attribute not found") var XAttrErrorNoDataAvailable = errors.New("no data available") var XAttrErrorResultTooLarge = errors.New("result too large") func syscallErrorToXAttrError(err error) error { if err == nil { retu...
package casbin import ( "backend/models" "backend/utils/logging" "backend/utils/response" "github.com/gin-gonic/gin" "net/http" ) func Casbin() gin.HandlerFunc { return func(c *gin.Context) { // 获取请求的URI obj := c.Request.URL.RequestURI() // 获取请求方法 act := c.Request.Method // 获取用户的角色 username, _ := c....
package safepassword import ( "bytes" "crypto" "crypto/aes" "crypto/cipher" "crypto/rsa" "crypto/x509" "encoding/pem" "errors" "io/ioutil" "crypto/rand" ) //RSAKeyGen Generate an RSA key pair with given bits(recommend:2048), then write both the public and private keys to the current folder //PKCS1&PEM func ...
// Exercise 07_makerorder guides you through using replay to place and update a marker order on the Lino exchange. // // A maker order is either a limit buy order below the market price or a limit sell order above the market price. // The order waits in the order book and is therefore said to ‘make’ the market. The Lun...
package webserver import ( "encoding/json" "fmt" "net/http" "strconv" "github.com/ghetzel/canibus/api" "github.com/ghetzel/canibus/candevice" "github.com/ghetzel/canibus/core" "github.com/ghetzel/canibus/hacksession" "github.com/ghetzel/canibus/logger" "github.com/gorilla/mux" ) type CanDeviceJSON struct {...
package main import ( "fmt" "os" "sort" "strings" "github.com/bitrise-io/go-steputils/jsdependency" "github.com/bitrise-io/go-steputils/stepconf" "github.com/bitrise-io/go-utils/colorstring" "github.com/bitrise-io/go-utils/errorutil" "github.com/bitrise-io/go-utils/log" "github.com/bitrise-io/go-utils/pathu...
package httperrors import "net/http" type Error interface { error WriteTo(http.ResponseWriter) } type httpError struct { status int message string } func (h httpError) WriteTo(rw http.ResponseWriter) { http.Error(rw, h.message, h.status) } func (h httpError) Error() string { return h.message } func NewHttp...
package v1 import ( "fmt" "gin-vue-admin/global/response" "gin-vue-admin/model/request" resp "gin-vue-admin/model/response" "gin-vue-admin/service" "github.com/gin-gonic/gin" ) func GetCertHolderList(c *gin.Context) { var paQuery request.PaginatedQuery _ = c.ShouldBindJSON(&paQuery) err, list, total := servi...
package common import ( "errors" "git.dustess.com/mk-base/gin-ext/api" "git.dustess.com/mk-training/mk-blog-svc/pkg/user/model" "github.com/gin-gonic/gin" "net/http" "strconv" "strings" ) const ( SessionHeaderKey = "session" ) type SuccessRes api.SuccessRes type FailedRes api.FailedRes // SendOK 成功 func Se...
package glosh_test import ( "log" "math" "math/rand" "testing" "github.com/brentp/glosh" ) func dist(v1, v2 []float64) float64 { var s float64 for i, v := range v1 { s += math.Abs(v - v2[i]) } return s } func randomVector(n int) []float64 { v := make([]float64, n) for i := range v { v[i] = rand.NormF...
package budgets import ( "fmt" "log" "go.bmvs.io/ynab" "go.bmvs.io/ynab/api/budget" ) //GetBudgets returns the list of budgets associated with user token func GetBudgets(c ynab.ClientServicer) []*budget.Budget { log.Print("Getting Budgets...") budgetSummaries, err := c.Budget().GetBudgets() if err != nil { ...
package main import ( "fmt" ) // Struct 结构体 // 结构体是将零个或多个任意类型的变量,组合在一起的聚合数据类型,也可以看做是数据的集合 type Person struct { Name string Age int } func main() { var p1 Person p1.Name = "Tom" p1.Age = 30 // p1 = {Tom 30} fmt.Println("p1 =", p1) var p2 = Person{Name: "Burke", Age: 31} // p2 = {Burke 31} fmt.Println("p2...
package analyze import ( "fmt" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // StatefulSets checks stateful sets for problems func (a *analyzer) statefulSets(namespace string) ([]string, error) { problems := []string{} // Get all pods statefulSets, err := a.client.KubeClient().AppsV1().StatefulSets(namespac...
package clock import ( "fmt" "os" "sync" "sync/atomic" "testing" "time" ) // counter is an atomic uint32 that can be incremented easily. It's // useful for asserting things have happened in tests. type counter struct { count uint32 } func (c *counter) incr() { atomic.AddUint32(&c.count, 1) } func (c *count...
package jsontime import ( "fmt" "time" ) const TimeFormat = "2006-01-02 15:04:05" const DateFormat = "2006-01-02" type JsonDate time.Time type JsonTime time.Time func (this JsonDate) MarshalJSON() ([]byte, error) { var stamp = fmt.Sprintf("\"%s\"", time.Time(this).Format(DateFormat)) return []byte(stamp), nil...
package onlinestore import ( "context" "path/filepath" "reflect" "testing" "github.com/feast-dev/feast/go/internal/feast/registry" "github.com/stretchr/testify/assert" "github.com/feast-dev/feast/go/internal/test" "github.com/feast-dev/feast/go/protos/feast/types" ) func TestSqliteAndFeatureRepoSetup(t *te...
package m3 // M3 provides operatios, try a simple one first, later come back for more params. type M3 interface { Upload(bucket string, key string) (string, error) // return byte first } type m3 struct{} func (m m3) Upload(bucket, key string) (string, error) { return "ok", nil }
package actions type Actions interface { Reboot() error Shutdown() error }
package sshmgr import ( "errors" "sync" "sync/atomic" "time" "github.com/brunotm/sshmgr/locker" "github.com/pkg/sftp" ) var ( errManagerClosed = errors.New("manager closed") ) // Manager for shared ssh and sftp clients type Manager struct { mtx sync.RWMutex gcInterval time.Duration clientTTL int64...
package main import "os" func main() { fetchFiles(os.Args[1:]) }
package main import ( "fmt" "time" ) // // 申明一个数组,元素为chan // var chs [10]chan int // // 申明一个切片, 值为Chan // var chs2 []chan int // // 申明一个字典, 值为chan // var chs3 map[string]chan int func test(ch chan<- int) { // 往通道中写入数据 for i := 0; i < 100; i++ { ch <- i } close(ch) } func main() { start := time.Now() ch...
package missingnumbers import ( "sort" ) // Missing func func Missing(numbers []int) []int { res := make([]int, 2) // sort in ascending order to enable checking by successor calculated from index sort.Ints(numbers) offset := 0 // array is sorted in natural order, should be starting with '1' so the value of ev...
package user import ( "database/sql" "fmt" _ "github.com/lib/pq" "github.com/stretchr/testify/require" "go-friend-mgmt/cmd/internal/services/models" "testing" ) const ( hostTest="localhost" portTest=5432 userTest="postgres" passwordTest="123456789" dbnameTest="FriendManagement" ) func ConnectionDBForTest(...
package main import ( "fmt" "sync" ) func main() { n := 0 var mu sync.Mutex var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done() for i := 0; i < 1000; i++ { mu.Lock() n++ mu.Unlock() } }() go func() { defer wg.Done() for i := 0; i < 1000; i++ { mu.Lock() n++ mu.Unlock()...
package main_test import ( . "github.com/douglassquirrel/microservices-hackathon-november-2014/match-maker-service/main" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Match Maker", func() { Describe(".AddToQueue", func() { var matchMaker MatchMaker BeforeEach(func() { matchMa...
package pain import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document01700101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:pain.017.001.01 Document"` Message *MandateCopyRequestV01 `xml:"MndtCpyReq"` } func (d *Document01700101) AddMessage()...
package main import ( "os" "path/filepath" "reflect" "testing" "github.com/stretchr/testify/assert" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" v1 "github.com/jenkins-x/jx-api/v3/pkg/apis/jenkins.io/v1" "github.com/jenkins-x/jx-api/v3/pkg/client/clientset/versioned/fake" ) func TestOptions_findErrors(t *...
// Package service defines the "business" logic, backed by // a Store from the store package to manage the data. // There only current implmentation is the FibService. // // The service package API's are invoked from the api package, // which are the HTTP handler functions. package service import ( "context" "fmt" ...
package main import ( "strings" "github.com/gdamore/tcell" ) type CmdPrompt struct { cursor uint str string } func (self *CmdPrompt) Draw(s tcell.Screen, active bool) { _, h := s.Size() l := EmitStrDef(s, 0, h-1, self.str) if active { s.ShowCursor(l, h-1) } } func (self *CmdPrompt) Update(ev *tcell.Ev...
package fileio import ( "encoding/json" "errors" "main/utils" ) const ( uploadUrl = "https://file.io/" referer = "https://www.file.io/" ) func upload(path string, size, byteLimit int64, headers map[string]string) (string, error) { respBody, err := utils.MultipartUpload(uploadUrl, path, "file", ...
package main import "fmt" func main() { var ch byte var str string //字符 //1.单引号 //2.字符,往往都是只有一个字符 除了 \n \t 转义字符 ch = 'a' fmt.Println(ch) //字符串 //1.双引号 //2.字符串可以有一个或多个字符组成 //3.字符串都是隐藏了一个结束符 '\0' str = "a" fmt.Println(str) str = "hello go" fmt.Println(str[0],str[1]) fmt.Printf("%c,%c\n",str[0],str...
package main import "fmt" func main() { // array primes := [6]int{2, 3, 5, 7, 11, 13} // sはslice. primesの要素を1~3まで取得して作成 var s []int = primes[1:4] fmt.Println(s) fmt.Printf("%T\n", primes) fmt.Printf("%T\n", s) }
/* * @lc app=leetcode.cn id=114 lang=golang * * [114] 二叉树展开为链表 */ // @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 lnglat import "math" const ( // L ... 表示可能上限 L = 85.05112878 ) // Tile2Lnglat ... タイル座標=>緯度経度変換 func Tile2Lnglat(x, y int, z uint) (lon, lat float64) { lon = (math.Pow(float64(x)/2.0, (float64(z+7))) - 1) * 180 lat = 180 / math.Pi * (math.Asin(math.Tanh(math.Pow(-math.Pi/2, float64(z+7)*float64(y)+math.A...
package genpcap import ( "fmt" "github.com/google/gopacket" "github.com/google/gopacket/layers" "io" "net" "time" ) /* Endpoint impelemnts the sender and receiver */ type Endpoint struct { IP net.IP Mac net.HardwareAddr Port uint32 Seq uint32 ethLayer *layers.Ethernet ipLayer *layers.IPv4 tcpLayer ...
// 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 common import ( "errors" "sync/atomic" "time" "github.com/cpusoft/goutil/belogs" "github.com/cpusoft/goutil/iputil" "github.com/cpusoft/goutil/jsonutil" "github.com/cpusoft/goutil/xormdb" model "rpstir2-model" "xorm.io/xorm" ) func GetSerialNumberCountDb() (myCount uint64, err error) { start := tim...
package main import ( "container/heap" "fmt" ) // A PriorityQueue implements heap.Interface and holds Items. type PriorityQueue struct { items []Vertex // value to index m map[Vertex]int // value to priority pr map[Vertex]int } func (pq *PriorityQueue) Len() int { return len(pq.items) } fu...
package log import ( "io" "sync" ) // Handler is used to handle log events, outputting them to stdio or sending // them to remote services. type Handler interface { Handle(*Entry) error } func New(h ...Handler) *Context { return &Context{handler: handlers(h)} } type handlers []Handler func (h handlers) Handle(...
package sharesession import ( "database/sql" "log" "time" "github.com/rakoo/rakoshare/pkg/id" _ "github.com/mattn/go-sqlite3" ) var ( Q_SELECT_TORRENT = `SELECT torrent FROM meta` Q_SELECT_INFOHASH = `SELECT infohash FROM meta` Q_SELECT_LASTMODTIME = `SELECT lastmodtime FROM meta` Q_SELECT_IHMESSAGE...
package main import "testing" /** 二叉树的最近公共祖先 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。” 例如,给定如下二叉树:  root = [3,5,1,6,2,0,8,null,null,7,4] ![-1.png](./source/-1.png) 示例 1: ``` 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 输出:...
package dushengchen /* Submission: https://leetcode.com/submissions/detail/356998480/ */ var digitMaps = map[rune][]rune { '2' : []rune{'a', 'b', 'c'}, '3' : []rune{'d', 'e', 'f'}, '4' : []rune{'g', 'h', 'i'}, '5' : []rune{'j', 'k', 'l'}, '6' : []rune{'m', 'n', 'o'}, '7' : []rune{'p', 'q', ...
/* Copyright 2020 The Qmgo 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, sof...
package employee import "gitlab.com/username/online-service-and-customer-care/entity" // EmployeeService specifies application employee related services type EmployeeService interface { Employees() ([]entity.Employee, []error) Employee(id uint) (*entity.Employee, []error) UpdateEmployee(employee *entity.Employee) ...
package controllers import ( "github.com/gin-gonic/gin" "github.com/go-playground/validator" "github.com/jinzhu/gorm" "healthy-api/models" "healthy-api/validation" "healthy-api/validation/blood_validation" "math" "net/http" "strconv" ) type bloodController struct { } func NewBloodController() *bloodControl...
package usecase import ( "github.com/Arkadiyche/bd_techpark/internal/pkg/forum" "github.com/Arkadiyche/bd_techpark/internal/pkg/models" "github.com/Arkadiyche/bd_techpark/internal/pkg/user" "github.com/Arkadiyche/bd_techpark/internal/pkg/utils" "net/url" ) type ForumUseCase struct { ForumRepository forum.Reposi...
package main import "testing" //文件名字要为 文件名+ _test //方法名要用Test开头 func TestAdd(t *testing.T) { r := Add(2, 4) if r != 6 { t.Fatalf("add(2,4) error, expect:%d, actual:%d", 6, r) } t.Log("test add succ") }
package main import ( "net/http" "net/http/httptest" "testing" "strings" "github.com/gorilla/mux" ) func TestAllGames(t *testing.T) { games = append(games, Games{ID: "0", Name: "test", Date: "data"}) req, err := http.NewRequest("GET", "/games", nil) if err != nil { t.Errorf("An error occ...
// 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...
package http import ( "bytes" "fmt" "io" "mime/multipart" "net/http" "os" "path/filepath" ) //FormUploader represents HTTP multipart form submission. type FormUploader interface { AddField(name, value string) FormUploader AddFields(fields map[string]string) FormUploader Fields(name string) [...
// Code generated from an extremely hacky wsdl tool. // source: http://flightxml.flightaware.com/soap/FlightXML2/wsdl // DO NOT EDIT! package flightaware import ( "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "net/url" "strings" "github.com/golang/protobuf/jsonpb" "github.com/golang/protobuf/proto" ...
package controllers import ( "context" "fmt" "github.com/go-logr/logr" "github.com/pkg/errors" kube_core "k8s.io/api/core/v1" kube_runtime "k8s.io/apimachinery/pkg/runtime" kube_types "k8s.io/apimachinery/pkg/types" kube_record "k8s.io/client-go/tools/record" kube_ctrl "sigs.k8s.io/controller-runtime" kube_...
/* Copyright 2021 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 writi...
package main import ( "fmt" "github.com/Cloud-Foundations/Dominator/imageunpacker/client" "github.com/Cloud-Foundations/Dominator/lib/log" "github.com/Cloud-Foundations/Dominator/lib/srpc" ) func prepareForUnpackSubcommand(args []string, logger log.DebugLogger) error { if err := prepareForUnpack(getClient(), ar...
package main import ( "encoding/json" "fmt" "net/http" "os" "os/exec" "text/template" "github.com/gorilla/mux" "github.com/zhaizhonghao/explorerTool/services/connection" ) type Success struct { Payload string `json:"Payload"` Message string `json:"Message"` } var tpl *template.Template func main() { rou...
package main import ( "log" "github.com/JeanCntrs/airbnb-catalog-server/db" "github.com/JeanCntrs/airbnb-catalog-server/handlers" ) func main() { if db.CheckConnection() == 0 { log.Fatal("Without connection to database") return } handlers.RouteHandlers() }
/* Create a program to track cpu per pid over time, but you also want it to do the following: - output in .csv format - load into sqlite3 database - provide custom scripts to execute By automatically putting the data in a database you find processes that use a lot of cpu during 2.5min, 5min or 10min intervals ...
package gonet import ( "fmt" "net" "syscall" "github.com/vishvananda/netlink" "github.com/vishvananda/netns" ) // LinuxLink is the main interface towards the outside // It describes the API of the link type LinuxLink interface { Up() error Down() error SetName(name string) error Ifconfig(ip net.IP, netmask ...
package main import ( "github.com/btoll/rest-go/app" "github.com/btoll/rest-go/models" "github.com/dgaedcke/nmg_shared/constants" "github.com/goadesign/goa" ) // GameController implements the Game resource. type GameController struct { *goa.Controller } // NewGameController creates a Game controller. func NewGa...
// generate: stringer -type VendorID package sysex type VendorID uint func (v VendorID) Bytes() []byte { if v&0xFF0000 != 0 { return []byte{byte((v >> 16) & 0xFF)} } return []byte{ 0x00, byte((v >> 8) & 0xFF), byte(v & 0xFF), } } func vendorFrom3Bytes(b []byte) VendorID { ui0 := uint(b[0]) ui1 := uint(...
package main import ( "fmt" "github.com/gin-gonic/gin" "github.com/joho/godotenv" "html/template" ) // Clarifai client singleton // To keep it simple, make them global so that we don't need to pass them around var CLFclient = NewClarifaiClient() func main() { router := gin.Default() // TODO: Set up environmen...
package main import ( "fmt" "io/ioutil" "log" "path/filepath" "github.com/aws/aws-xray-daemon/daemon/conn" ) // version-gen is a simple program that generates the daemon version number and writes to VERSION file. func main() { fmt.Printf("AWS X-Ray daemon version: %v\n", conn.GetVersionNumber()) // Write X-R...
package commands import ( "code.cloudfoundry.org/garden" gclient "code.cloudfoundry.org/garden/client" gconn "code.cloudfoundry.org/garden/client/connection" ) func globalClient() garden.Client { network := Globals.Target.Network address := Globals.Target.Address return gclient.New(gconn.New(network, address))...
package rediscache import ( "time" "github.com/go-redis/redis" ) var client *redis.Client func createRedisClient() { client = redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password set DB: 0, // use default DB }) _, err := client.Ping().Result() if err != nil { ...
package nut import ( "time" "github.com/gin-gonic/gin" "github.com/go-pg/pg" "github.com/kapmahc/axe/web" ) func (p *AdminPlugin) checkCardToken(user *User, tid uint) bool { return p.Dao.Is(user.ID, RoleAdmin) } func (p *AdminPlugin) editCardH(tid uint, token string) (string, string, error) { var it Card if ...
package primitives_test import ( "encoding/xml" "fmt" "github.com/plandem/xlsx/format" "github.com/plandem/xlsx/internal/ml/primitives" "github.com/stretchr/testify/require" "testing" ) func TestFontCharset(t *testing.T) { type Element struct { Property primitives.FontCharsetType `xml:"property,omitempty"` ...
// Copyright 2016-2019 Authors of Cilium // // 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 ag...
package golang import ( "reflect" "testing" ) var tests = []struct { L int R int output int }{ {L: 6, R: 10, output: 4}, {L: 10, R: 15, output: 5}, {L: 842, R: 888, output: 23}, {L: 100, R: 999, output: 466}, {L: 4, R: 85, output: 55}, } func TestCountPrimeSetBits(t *testing.T) { for idx, test :...
package utils import ( "os" "path" "net/http" "io" "errors" "github.com/schollz/progressbar" ) /** * * Create BY YooDing * * Des: 文件操作 * * Time: 2019/7/6 2:14 PM. * * <a href="https://github.com/YooDing/gone">Github</a> */ func AppendStrToFile(fileName string, content string) error { // 以只写的模式,打开文件 ...
package model import "github.com/barrydev/api-3h-shop/src/constants" type Role struct { /** Response Field */ Id *int64 `json:"_id,omitempty"` Name *string `json:"name,omitempty"` /** Database Field */ RawId *int64 `json:"-"` RawName *string `json:"-"` } func (role *Role) FillResponse() { role.Id = role...
// // Copyright (C) 2019-2021 vdaas.org vald team <vald@vdaas.org> // // 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 requir...
/* ** description(""). ** copyright('tuoyun,www.tuoyun.net'). ** author("fg,Gordon@tuoyun.net"). ** time(2021/5/11 15:37). */ package logic import ( "Open_IM/pkg/common/config" "Open_IM/pkg/common/constant" "Open_IM/pkg/common/db/mysql_model/im_mysql_msg_model" kfk "Open_IM/pkg/common/kafka" "Open_IM/pkg/common/...
func missingNumber(nums []int) int { result:=(0+len(nums))*(len(nums)+1)/2 count:=0 for _,v:=range nums{ count+=v } return result-count }
package compress //bzip2 包提供解压bzip2的接口,未提供压缩方法
package test import ( "errors" "github.com/mkj-gram/go_email_service/internal/emailprovider" "github.com/mkj-gram/go_email_service/internal/server" "github.com/stretchr/testify/assert" "io" "net/http" "net/http/httptest" "strings" "testing" ) type TestStrategy struct { sendHandler func(m emailprovider.Email...
import ( "sort" "strings" ) func sortString(w string) string { s := strings.Split(w, "") sort.Strings(s) return strings.Join(s, "") } func isAnagram(s string, t string) bool { return sortString(s) == sortString(t) }
package main import ( "fmt" "html" "log" "net/http" ) func Calculate(x int) int { return x + 2 } func main() { fmt.Println("Go CI Pipeline Tutorial") http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) }) http.HandleFunc("/hi", fu...
package xhvalidate import ( "fmt" "testing" ) func TestValidateCNMobile(t *testing.T) { type Input struct { Mobile string `json:"mobile" validate:"required,is_CNMobile"` Password string `json:"password" validate:"required"` Nick string `json:"nick" validate:"required"` } fmt.Println(CheckCNMobile("1...
package mst import "github.com/nicksnyder/go-i18n/i18n" type RequestUserCTXSt struct { Language string T i18n.TranslateFunc ID string } type requestRetrieveUsrIdSRepSt struct { UsrId string `json:"usr_id"` }
package middleware import ( "fmt" "strconv" "net/http" "portal/util" "portal/model" "portal/config" "github.com/gin-gonic/gin" "github.com/dgrijalva/jwt-go" ) // claims // type MyClaims struct { // UserId string `json:"userId,omitempty"` // RoleId string `json:"roleId,omitempty"` // jwt.Standard...
package rule import ( "database/sql" "encoding/json" "fmt" "ism.com/common/db" ) type Service struct { Id string `json:"id"` Name string `json:"name"` SvcBlock string `json:"svcBlock"` InDstrId string `json:"inDstrId"` OutDstrId string `json:"outDstrId"`...
package api import ( "errors" "fmt" "github.com/qlcchain/go-qlc/config" "github.com/qlcchain/go-qlc/common" "github.com/qlcchain/go-qlc/common/types" "github.com/qlcchain/go-qlc/ledger" "github.com/qlcchain/go-qlc/log" "github.com/qlcchain/go-qlc/vm/contract" cabi "github.com/qlcchain/go-qlc/vm/contract/abi...
package do import ( "testing" "github.com/stretchr/testify/assert" ) func TestTokenSource(t *testing.T) { ts := TokenSource{AccessToken: "token"} _, err := ts.Token() assert.NoError(t, err) } func TestGodoClientFactory(t *testing.T) { gc := GodoClientFactory("test-token") assert.NotNil(t, gc) }
package collector import ( "strings" "sync" "time" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/log" "github.com/totvslabs/elasticsearch-tasks-exporter/client" ) const ( namespace = "elasticsearch" subsystem = "pending_tasks" ) // NewCollector collector func NewCollector(cl...
/** * Copyright (C) 2019, Xiongfa Li. * All right reserved. * @author xiongfa.li * @version V1.0 * Description: */ package oauth2 import ( "encoding/base64" "github.com/xfali/oauth2/defines" "strings" ) func saveToken(dm defines.DataManager, access_data, access_token, refresh_data, refresh_token ...
// This file contains the utility functions to read and validate the user input // Add any utility functions as required. package utils import ( "bufio" "fmt" "os" "strconv" "time" ) func ReadCommand(expected []string) int32 { return readInput(expected, "command") } func readInput(expected []string, operation ...
package cmd import ( "fmt" "io/ioutil" "os" "strings" "testing" "github.com/praetorian-inc/gokart/util" "github.com/spf13/cobra" ) func TestScanCommand(t *testing.T) { // Tests the Scan command. cur_dir, err := os.Getwd() if err != nil { fmt.Println(err) os.Exit(1) } fmt.Printf("Current dir is: %s", ...
package main import ( "code.google.com/p/gcfg" ) const ( CONFIGFILE = "bot.cfg" ) type Config struct { Bot struct { Frequency string } Twitter struct { ConsumerKey string ConsumerSecret string AccessTokenKey string AccessTokenSecret string } } func getConfig() (cfg Config, err error) { ...
package helpers import ( tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" "github.com/s-matyukevich/capture-criminal-tg-bot/src/common" dbpkg "github.com/s-matyukevich/capture-criminal-tg-bot/src/db" "go.uber.org/zap" ) const botPromo = "Получено с помощью бота 'Дазор' @capture_criminal_bel_bot" func F...
package auth import ( "context" "github.com/go-kit/kit/endpoint" ) type Endpoints struct { GenerateEndpoint endpoint.Endpoint ValidateEndpoint endpoint.Endpoint } type GenerateRequest struct { UserId int32 `json:"userId"` Role string `json:"role"` } type GenerateResponse struct { Token string `json:"toke...
package client import ( "chapter15/series" "fmt" "testing" ) func init() { fmt.Println("hello first") } func init() { fmt.Println("hello second") } func TestPackage(t *testing.T) { t.Log(series.GetFibonacciSeries(5)) }
package main import ( "container/heap" "fmt" ) // 215. 数组中的第K个最大元素 // 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。 // 说明: // 你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。 // https://leetcode-cn.com/problems/kth-largest-element-in-an-array/ func main() { // fmt.Println((findKthLargest2([]int{3, 2, 1, 5, 6, 4}, 2...
package main import "fmt" var packageVal bool func main() { var functionVal int fmt.Println(packageVal,functionVal) }
// Copyright 2014 The Sporting Exchange Limited. All rights reserved. // Use of this source code is governed by a free license that can be // found in the LICENSE file. package main import ( "log" "os" "time" "opentsp.org/internal/tsdb" "opentsp.org/internal/tsdb/tsdbutil" ) func init() { go encode() } var t...
// Generated from AdlWi.g4 by ANTLR 4.7. package adlwi // AdlWi import "github.com/wxio/goantlr" // Struct of Handlers type AdlWiHandlers struct { EnterEveryRule func(ctx antlr.RuleNode) ExitEveryRule func(ctx antlr.RuleNode) Adl func(ctx IAdlContext, this *AdlWiHandlers, args ...interface{}) (res...
package main import ( "flag" "fmt" "os" "log" "github.com/qnib/metahub/pkg/tooling" ) var ( version = flag.Bool("version", false, "print version") username = flag.String("user", "metahub", "The username to login (default: metahub)") typename = flag.String("type", "", "Define the machine type, will...
package router import ( "github.com/gin-gonic/gin" ) func Init() *gin.Engine { r := gin.Default() // 游戏服务端路由注册 r = Router(r) return r }
/* n! means n (n 1) ... 3 2 1 For example, 10! = 10 9 ... 3 2 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! */ package main import ( "fmt" "math/big" "strconv" ) func main() { sum := 0 fact100 := factorial(1...