text
stringlengths
11
4.05M
package ocrsdk import ( "./src/parametrs" "./src/responses" "./src/utils" "bytes" "encoding/base64" "errors" "fmt" "strings" "time" ) type OCRSDK struct { authorizationKey string } func CreateOCRSDK(name string, pwd string) (ocrsdk *OCRSDK, err error) { if len(name) == 0 || len(pwd) == 0 { err = error...
package ir import "sort" // ===================== Functions implementing a sort interface ====================== // By is the type of a "less" function that defines a ordering for SearchResult. type By func(r1, r2 *SearchResult) bool // Sort function for ordering the search results. func (by By) Sort(results []Sear...
package main import ( "fmt" "github.com/sihendra/go-msgbuzz" "time" ) func main() { // Create msgbuzz instance msgBus := msgbuzz.NewRabbitMqClient("amqp://127.0.0.1:5672", 4) // Register consumer of some topic msgBus.On("profile.created", "reco_engine", func(confirm msgbuzz.MessageConfirm, bytes []byte) error...
package main import ( "fmt" "os" "os/signal" "github.com/siggy/bbox/beatboxer/render/web" log "github.com/sirupsen/logrus" ) func main() { sig := make(chan os.Signal, 1) signal.Notify(sig, os.Interrupt, os.Kill) w := web.InitWeb() for { select { case <-sig: fmt.Printf("Received OS signal, exiting")...
package main import ( "fmt" "math/rand" "sync" "time" ) var arraySize = 4 var array1 = []int{3, 6, 3, 2} var array2 = []int{2, 9, 4, 1} var array3 = []int{8, 3, 2, 0} type CyclicBarrier struct { phase int count int parties int trigger *sync.Cond } func (b *CyclicBarrier) nextGeneration() { b.trigger.Br...
package mira import ( "bytes" b64 "encoding/base64" "encoding/json" "net/http" "net/url" "strings" "time" ) type Credentials struct { ClientID string ClientSecret string Username string Password string UserAgent string } // Authenticate returns *Reddit object that has been authed func Auth...
package dao func NewDao(debug bool) *Dao { return new(Dao) } type Dao struct { Debug bool IgnoreSign bool SecretKey string }
package loadbalancer import ( "context" "reflect" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elb" "github.com/giantswarm/apiextensions/pkg/apis/provider/v1alpha1" "github.com/giantswarm/micrologger/microloggertest" awsclient "github.com/giantswarm/aws-operator/client/aws" "...
package main import ( "fmt" "io/ioutil" "net/http" "net/url" ) func main() { res, err := http.Get("http://127.0.0.1:9090/query?name=zansan&age=10") if err != nil { fmt.Println(err) return } // 从res中把服务端返回的数据读取出来 b, err := ioutil.ReadAll(res.Body) if err != nil { fmt.Println(err) return } fmt.Prin...
// 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 in wr...
// Package snapshot Amazon Seller Utilities API Responses package snapshot import ( "encoding/json" "log" "net/http" ) // DownloadSnapshotError An error response from the API func DownloadSnapshotError(w http.ResponseWriter, version int, code int, err error) error { apiResponse := DownloadSnapshotAPIResponse{ V...
package routers import ( "github.com/genshen/ssh-web-console/src/controllers" "github.com/genshen/ssh-web-console/src/controllers/files" "github.com/genshen/ssh-web-console/src/utils" _ "github.com/genshen/ssh-web-console/statik" "github.com/rakyll/statik/fs" "log" "net/http" "os" ) const ( RunModeDev = "de...
package redis import ( "encoding/json" "fmt" "log" "time" "github.com/hailongz/kk-lib/dynamic" "github.com/hailongz/kk-logic/logic" "gopkg.in/redis.v5" ) type Redis struct { client *redis.Client prefix string } type RedisOpenLogic struct { logic.Logic redis *Redis } func (L *RedisOpenLogic) Recycle() { ...
package main import "fmt" func main() { //十进制 var i1 = 101 fmt.Printf("%d\n", i1) fmt.Printf("%b\n", i1) //把十进制转换成二进制 fmt.Printf("%o\n", i1) //把十进制转换成八进制 fmt.Printf("%x\n", i1) // 把十进制转换成十六进制 //八进制 i2 := 077 fmt.Printf("%d\n", i2) //十六进制 i3 := 0x123 fmt.Printf("%d\n", i3) //查看变量的类型 fmt.Printf("i3 type i...
package channelserver import ( "fmt" "strings" "github.com/Andoryuuta/Erupe/network/binpacket" "github.com/Andoryuuta/Erupe/network/mhfpacket" "github.com/Andoryuuta/byteframe" ) // MSG_SYS_CAST[ED]_BINARY types enum const ( BinaryMessageTypeState = 0 BinaryMessageTypeChat = 1 BinaryMessageTypeEmote = 6 ) ...
// Implement the dining philosopher’s problem with the following constraints/modifications. // // 1. There should be 5 philosophers sharing chopsticks, with one chopstick between each adjacent pair of philosophers. // 2. Each philosopher should eat only 3 times (not in an infinite loop as we did in lecture) // 3. The p...
package main import ( "github.com/beego/beego/v2/client/orm/migration" ) // DO NOT MODIFY type User_20210628_221252 struct { migration.Migration } // DO NOT MODIFY func init() { m := &User_20210628_221252{} m.Created = "20210628_221252" migration.Register("User_20210628_221252", m) } // Run the migrations fun...
package spatial import ( "bytes" "encoding/binary" ) type MultiPolygonData []PolygonData func (mpd *MultiPolygonData) decodeFrom(data *bytes.Reader) error { var length uint32 if err := binary.Read(data, byteOrder, &length); nil != err { return err } *mpd = make([]PolygonData, length) var p Polygon for i :...
package handler import ( "net/http" "github.com/chonla/oddsvr-api/jwt" jwtgo "github.com/dgrijalva/jwt-go" "github.com/labstack/echo" ) func (h *Handler) Me(c echo.Context) error { user := c.Get("user").(*jwtgo.Token) claims := user.Claims.(*jwt.Claims) uid := claims.ID me, e := h.vr.Profile(uid) if e != n...
package ordersprices import ( "database/sql" "fmt" . "go-sugar/config" . "go-sugar/db" ) // OrderPrice main struct type OrderPrice struct { OrderID int UserID NullInt64 PriceID NullInt64 } // Repo entity var Repo = Repository{tableName: Config.DB.Schema + ".orders_prices"} func parseRows(rows *sql.Rows) []...
package main import ( "io" "os" "time" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) var sugarLogger *zap.SugaredLogger var file os.File func init() { encoder := getEncoder() defaultWriter := getLogWriter("E:\\Projects\\project-github\\little-go\\practices\\log\\logs") core := zapcore.NewCore( encoder, de...
/* Package clouddatastore provides Cloud Datastore implementation of datastore.Client. This package wrapping cloud.google.com/go/datastore package. */ package clouddatastore // import "go.mercari.io/datastore/clouddatastore"
package iteration import ( "fmt" "testing" ) func TestRepeat(t *testing.T) { repeated := Repeat("a", 3) expected := "aaa" if repeated != expected { t.Errorf("expected %q but got %q", expected, repeated) } } func BenchmarkRepeat(b *testing.B) { for i := 0; i < b.N; i++ { Repeat("a", 3) } } func ExampleR...
package config import ( "fmt" "github.com/spf13/viper" ) type Configurations struct { Multi bool Broker BrokerConfig Actor ActorConfig } type BrokerConfig struct { Hostname string Port int } type ActorConfig struct { Hostname string Port int Services []string `yaml:"services"` } func LoadConfig(configPa...
package order import ( "context" "errors" ) var ( ErrOrderNotFound = errors.New("order not found") ErrCmdRepository = errors.New("unable to command repository") ErrQueryRepository = errors.New("unable to query repository") ) // Service describes the Order service. type Service interface { Create(ctx contex...
package streak import ( "errors" "net/http" "regexp" "strconv" "time" "github.com/PuerkitoBio/goquery" ) // Streak with count and the dates of the streak type Streak struct { From time.Time `json:"from"` To time.Time `json:"to"` Count int `json:"count"` } // Client with http Client for dependency...
package cmds import ( "testing" ) func TestReqLog(t *testing.T) { l := &ReqLog{} req1, err := NewEmptyRequest() if err != nil { t.Fatal(err) } req2, err := NewEmptyRequest() if err != nil { t.Fatal(err) } req1.Values()["foo"] = 42 req2.Values()["bar"] = 23 rle1 := l.Add(req1) rle2 := l.Add(req2) ...
//Generated TestNew //Generated TestScanner_Next package lex import ( //"bufio" "io" //"os" "reflect" "testing" ) func TestNew(t *testing.T) { //file, _ := os.Open("../red/dwarf.red") //reader := bufio.NewReader(file) type args struct { name string r io.ByteReader } tests := []struct { name string ...
package gen import ( "io/ioutil" "os" "path/filepath" "regexp" "testing" ) func TestMerge(t *testing.T) { debug := true type tcase struct { name string infiles map[string]string // file structure to start with out map[string][]string // regexps to match in output files outNot map[string][]s...
package dao import "git.dustess.com/mk-training/mk-blog-svc/pkg/tags/model" // FindOne 查询一条数据 func (m *TagDao) FindOne(filter interface{}) (result model.Tag, err error) { err = m.dao.FindOne(m.ctx, filter).Decode(&result) return } // FindMany 批量查询 func (m *TagDao) FindMany(filter interface{})(result []model.Tag, e...
package executors import ( "context" "io" "github.com/pkg/errors" "github.com/projecteru2/phistage/common" "github.com/sirupsen/logrus" ) type PhistageExecutor interface { Execute(ctx context.Context) error } // JobExecutor is an executor to execute the job. // It is designed stateful, so job is not a paramet...
package main import "flag" import "fmt" import "os" func main() { wordPtr := flag.String("word", "foo", "a string") numPtr := flag.Int("numb", 11, "an int") var boo bool flag.BoolVar(&boo, "fork", false, "a bool") flag.Parse() fmt.Println("word : ", *wordPtr) fmt.Println("num : ", *numPtr) fmt.Println("bo...
package main import ( "crypto/sha1" "fmt" ) func main() { s := "my name is ankita" h := sha1.New() h.Write([]byte(s)) bs := h.Sum(nil) fmt.Print(s) fmt.Print("%x", bs) }
package chme import ( "net/http" ) // DefaultInputName is used as the key of the value to which request method is changed. const DefaultInputName = "_method" var defaultChme = NewChme(DefaultInputName) var changeableMethods = map[string]bool{ http.MethodPut: true, http.MethodPatch: true, http.MethodDelete: ...
package eventlog import ( "github.com/iotaledger/wasp/packages/coretypes" "github.com/iotaledger/wasp/packages/kv" "github.com/iotaledger/wasp/packages/kv/kvdecoder" "github.com/iotaledger/wasp/packages/kv/codec" "github.com/iotaledger/wasp/packages/kv/collections" "github.com/iotaledger/wasp/packages/kv/dict" ...
package signal_test import ( "os" "syscall" "github.com/flexi-cache/pkg/signal" ) func ExampleHandlers() { signals := signal.NewHandlers() stop := signals.StartListen() defer stop() var cleanup = func(os.Signal) error { // This will be called when termination signals received. e.g. SIGINT return nil } ...
package commonMiddleware import ( "net/http" "time" "github.com/MiteshSharma/gateway/common" "github.com/felixge/httpsnoop" "go.uber.org/zap" ) // LoggerMiddleware struct type LoggerMiddleware struct { } // NewLoggerMiddleware function returns instance of logger middleware func NewLoggerMiddleware() *LoggerMid...
package htlc import ( sdk "github.com/irisnet/irishub/types" ) // NewHandler handles all "htlc" messages func NewHandler(k Keeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { switch msg := msg.(type) { case MsgCreateHTLC: return handleMsgCreateHTLC(ctx, k, msg) case MsgClaimHTLC: ...
/* * List intra-datacenter firewall policies associated with a given account. * Optionally filter results to policies associated with a second "destination" account. */ package main import ( "flag" "fmt" "os" "path" "strings" "github.com/grrtrr/clcv2/clcv2cli" "github.com/grrtrr/exit" "github.com/kr/pretty...
/* * VMaaS Webapp * * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * API version: 1.3.2 * Generated by: OpenAPI Generator (https://openapi-generator.tech) */ package vmaas import ( _context "context" _ioutil "io/ioutil" _nethttp "net/http" _ne...
package main import ( "database/sql" "fmt" "github.com/exasol/exasol-driver-go" "log" ) func main() { fmt.Printf("Drivers=%#v\n", sql.Drivers()) database, err := sql.Open("exasol", exasol.NewConfig("sys", "exasol"). Host("localhost"). Port(8563). ValidateServerCertificate(false). String()) onError(err...
package bundler import ( "encoding/json" "fmt" "log" "strconv" ) // The file in an app directory where we expect to find the metadata const MetadataName string = "Siphonfile" type PlatformMetadata struct { Language string `json:"language"` StoreName string `json:"store_name"` } // Metadata represents the par...
package LeetCode func FairCandySwap(A []int, B []int) []int { SumA, SumB := 0,0 MapA := map[int]bool{} MapB := map[int]bool{} res := []int{} for _,v := range A { SumA += v MapA[v] = true } for _,v := range B { SumB += v MapB[v] = true } diff := (SumB - SumA)/2 for _,v := range A { if _,ok := Map...
package practice // Brute Force: Recursion // Runtime: 628 ms // Memory Usage: 2.1 MB func findTargetSumWays(nums []int, S int) int { if len(nums) == 0 { if S == 0 { return 1 } return 0 } f := findTargetSumWays return f(nums[1:], S+nums[0]) + f(nums[1:], S-nums[0]) } // Recursion with Memoization // Run...
package github import ( "errors" "fmt" "os" "github.com/FINTLabs/fint-consumer/common/utils" "gopkg.in/src-d/go-git.v4" "gopkg.in/src-d/go-git.v4/plumbing" ) func Clone(name string, cloneUrl string, reference string) error { ref := plumbing.ReferenceName(reference) r, err := git.PlainClone(utils.GetWorking...
package gorms import ( "gorm.io/driver/sqlite" ) func NewSqliteAdapter(settings GormSettings) *adapter { return &adapter{ dialector: sqlite.Open(settings.ConnectionString), settings: settings, } }
package main import ( "fmt" ) func printRankings(board map[int]int, leaders []int, scores []int, lowest int) { max := leaders[0] min := leaders[len(leaders) - 1] idx := len(leaders) - 1 for _, i := range scores { if val, ok := board[i]; ok { fmt.Println(val) } else if i > max { fmt.Println(1) } else i...
// Package multipart to handle MultipartForm package multipart import ( "fmt" "io" "mime" "mime/multipart" "net/http" ) type MultipartForm struct { r *http.Request } type FormFile struct { part *multipart.Part name string // form name filename string // file name // size int64 // readed size }...
package azure import ( "fmt" "github.com/pkg/errors" "github.com/spf13/cobra" azmigrate "github.com/openshift/installer/pkg/migrate/azure" "github.com/openshift/installer/pkg/types/azure" ) var ( azureMigrateOpts struct { cloudName string zone string resourceGroup string virtu...
package drivers import ( "crypto/tls" "fmt" "log" "net/smtp" "os" "github.com/mitchdennett/flameframework/contracts" ) type MailSmtpDriver struct { to string from string message string subject string } func (m MailSmtpDriver) To(email string) contracts.MailContract { m.to = email return m } fun...
package main import "fmt" type Stu struct { Name string Age int } func (stu *Stu) String() string { str := fmt.Sprintf("name=[%v] age=[%v]", stu.Name, stu.Age) return str } func main() { stu := Stu{ Name: "zcr", Age: 12, } fmt.Println(&stu) }
package hydrator import ( "context" "github.com/asecurityteam/nexpose-vuln-hydrator/pkg/domain" ) // HydratorConfig contains items to be configured for the HydratorComponent. type HydratorConfig struct { Nexpose *NexposeConfig } // Name is used by the settings library and will add a "HYDRATOR_" // prefix to all ...
// 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 cmd import ( "fmt" "os" "github.com/spf13/cobra" ) var rootCmd = &cobra.Command{ Use: "todoapp", Short: "Todo App is file base command line todo list", } func init() { rootCmd.AddCommand(listCmd) rootCmd.AddCommand(showCmd) rootCmd.AddCommand(newCmd) rootCmd.AddCommand(addCmd) rootCmd.AddCommand...
// Copyright 2019 Stefan Prisca // 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 models import ( "encoding/json" "fmt" "io/ioutil" "time" log "github.com/sirupsen/logrus" ) // Post 微博的具体信息 type Post struct { URL string `json:"url"` UID uint64 `json:"uid"` PostCreatedAt string `json:"created_at"` ID string `json:"id" gorm:"primaryKey"` MID ...
package model import ( "fmt" "log" "testing" "github.com/davecgh/go-spew/spew" "github.com/vhaoran/vchat/lib" "github.com/vhaoran/vchat/lib/ypg" ) type Abc struct { ypg.BaseModel ID int `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id"` CName string } func (r *Abc) TableName() string { return "abc" } func...
package errs import ( "errors" ) func fnWithError() error { return errors.New("some error") } func fnNoError() error { return nil }
package cacheutil func DistributeShards(newCluster *CacheCluster, cluster *CacheCluster, args *CacheClusterArgs) []*Shard { // cluster.Mux.Lock() // defer cluster.Mux.Unlock() // if cluster.ShardsAmount < args.ShardsAmount { // diff := args.ShardsAmount - cluster.ShardsAmount // for addingShardIdx := 0; ...
package base import "math/rand" // RandomGenerator is the random generator for gorse. type RandomGenerator struct { *rand.Rand } // NewRandomGenerator creates a RandomGenerator. func NewRandomGenerator(seed int64) RandomGenerator { return RandomGenerator{rand.New(rand.NewSource(int64(seed)))} } // NewUniformVecto...
package storage import ( "bytes" "context" "io" "github.com/klauspost/compress/gzip" "github.com/klauspost/compress/snappy" "github.com/klauspost/compress/zstd" "github.com/pingcap/errors" "github.com/pingcap/log" "go.uber.org/zap" ) // CompressType represents the type of compression. type CompressType uint...
package main import "fmt" func main() { fmt.Printf("My name is %s, I am %d years old\n", "Alan", 3) cupcakes := 3 calories := 320.5 fmt.Printf("One cupcake has %f calories. I ate %d, so in total I consumed %.2f calories", calories, cupcakes, float64(cupcakes)*calories) }
package main import ( "fmt" "github.com/graphql-go/graphql" "github.com/graphql-go/handler" "go_graphql/petstore/mutations" "go_graphql/petstore/queries" "log" "net/http" "os" ) func main() { f, err := os.OpenFile("development.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) if err != nil { fmt.Println("U...
package entity import "github.com/google/uuid" type Todo struct { Id uuid.UUID Description string Finished bool }
package gateway import ( "crypto/rand" "errors" "fmt" "github.com/adonese/noebs/utils" "github.com/dgrijalva/jwt-go" "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" "github.com/go-redis/redis" "github.com/jinzhu/gorm" log "github.com/sirupsen/logrus" "golang.org/x/crypto/bcrypt" "net/http" "...
package user import ( "encoding/json" "fmt" "github.com/gorilla/mux" "net/http" "strconv" ) const ( userURL = "/user/{id}" searchURL = "/user/search/" ) var _ Handler = &userHandler{} type userHandler struct { UserService Service } type AppError struct { Message string `json:"error"` } type Handler int...
// Copyright 2023 Google LLC. 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applica...
package main import "testing" func TestCheckResponseCode(t *testing.T) { c := CIDR{ Name: "Test", Mask: 24, } m1 := map[string]interface{}{"code": float64(201)} m2 := map[string]interface{}{"code": float64(500)} _, err := checkResponseCode(c, m1) if err != nil { t.Errorf("Expected nil, but received %v\n",...
package sync import ( "strings" "sync" ) type fileIndex struct { fileMap map[string]*FileInformation fileMapMutex sync.Mutex } func newFileIndex() *fileIndex { return &fileIndex{ fileMap: make(map[string]*FileInformation), } } func (f *fileIndex) Lock() { f.fileMapMutex.Lock() } func (f *fileIndex) U...
/* 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 client import ( "crypto/tls" "crypto/x509" "fmt" "io/ioutil" "net/http" "testing" "github.com/google/go-cmp/cmp" ) var certPool = x509.NewCertPool() func init() { data, err := ioutil.ReadFile("testdata/ca.crt") if err != nil { panic(err) } if !certPool.AppendCertsFromPEM(data) { panic("could ...
package main import ( "fmt" "github.com/jBugman/go-pocket/pocket" "os" "pocket/analysis" ) const CONSUMER_KEY = "<my-key>" const ACCESS_TOKEN = "<access-token>" func dump(model analysis.Model, filename string) { fmt.Println("Dumping model to " + filename) f, err := os.Create(filename) if err != nil { panic...
package main import ( "bufio" "fmt" "github.com/Knetic/govaluate" "os" "sort" "strconv" "strings" "unicode/utf8" ) //User_To_Server(UID, ORDER, ELEMENT) Examp: User_To_Server(30, 1, "6") //Server_To_User(UID, RESULT) Examp: Server_To_User(27, "= 8") var strNum = 1 func main() { userHashmap := ma...
package build import ( cref "github.com/pip-services3-go/pip-services3-commons-go/refer" cbuild "github.com/pip-services3-go/pip-services3-components-go/build" conn "github.com/pip-services3-go/pip-services3-mongodb-go/connect" ) //DefaultMongoDbFactory helps creates MongoDb components by their descriptors. //See ...
package main import "fmt" func main() { var ( m uint64 n uint64 a uint64 ) fmt.Scanf("%d %d %d",&m,&n,&a) x := m / a if m % a != 0{ x = x + 1 } y := n / a if n % a != 0 { y = y + 1 } result := x*y fmt.Printf("%d\n",result) }
package main import ( "crypto/tls" "crypto/x509" "io/ioutil" "net/http" ) // newClient creates an http.Client configured for certificate authorization and // verification against cert-api.access.redhat.com. func newClient(certFile, keyFile string) (*http.Client, error) { caCert, err := ioutil.ReadFile("/etc/insi...
package postgres import ( "database/sql" "fmt" "log" "path" "runtime" "github.com/BurntSushi/toml" _ "github.com/lib/pq" ) type DatabaseConfig struct { Username string Password string Database string Hostname string } func (d *DatabaseConfig) IsValid() bool { return (d.Username != "" && d.Password != ...
package command import ( "github.com/fatih/structs" "github.com/flosch/pongo2" "mix/plugins/micro" ) func (p *Handler) makeConfig() { renderConfig := micro.ReadRenderConfig(p.project) renderConfigData := pongo2.Context(structs.Map(renderConfig)) p.renderDynamic(ProjectConfigGlobalPath, renderConfigData) p.rend...
// Package user 业务 package user import ( "github.com/thoohv5/template/internal/service/user" "github.com/thoohv5/template/internal/service/user/entity" "github.com/thoohv5/template/pkg/http" "github.com/gin-gonic/gin" "github.com/thoohv5/template/internal/pkg/config" "github.com/thoohv5/template/pkg/log" ) ty...
// Copyright 2021 BoCloud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in wri...
package game import ( "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestShuffleDeck(t *testing.T) { deck := ShuffleDeck() t.Run("Contains 24 Cards", func(t *testing.T) { require.Len(t, deck, 24) }) t.Run("Contains No Duplicates", func(t *testing.T) { ...
package server import ( "net" ) type ServerOption struct { Addr net.TCPAddr }
package encoding import ( "encoding/binary" "testing" ) func BenchmarkBinaryBigEndianPutUint16(b *testing.B) { b.ReportAllocs() v := make([]byte, 2) for i := 0; i < b.N; i++ { binary.BigEndian.PutUint16(v, 12) } b.SetBytes(int64(len(v))) } func BenchmarkBinaryBigEndianPutUint64(b *testing.B) { b.ReportAllo...
package storage import ( "github.com/biezhi/gorm-paginator/pagination" md "github.com/ebikode/eLearning-core/model" ) type DBActivityLogStorage struct { *MDatabase } // Initialize ActivityLog Storage func NewDBActivityLogStorage(db *MDatabase) *DBActivityLogStorage { return &DBActivityLogStorage{db} } // Get al...
package controllers import "sharemusic/models" func (c *MusicController) LeftRoom() { id, _ := c.GetInt64("id") res, _ := models.GetOneById(id) var err error if res.UserNum == 1 { err = models.DelRoomInfo(id) } else { err = models.UpdateRoomInfoUserName(id, res.UserNum-1) } c.Ctx.Output.SetStatus(200) new...
package fingerprint import ( "fmt" "os" "os/exec" "path" "testing" "github.com/spf13/afero" "github.com/stretchr/testify/assert" ) const ( testDataDir = "/test/audio/" testFile1 = "sample1.mp3" testFile2 = "sample2.mp3" testFile3 = "textfile.txt" ) var ( mockExec = func(command string, args ...str...
package repository import ( "context" "time" "github.com/google/uuid" ) // Guest represents the repository guest object type Guest struct { ID uuid.UUID `json:"id" gorm:"primaryKey,not null"` Name string `json:"name" gorm:"index:idx_guest_phone,unique,not null"` T...
package utils import ( "io" "math/rand" "os" "strings" "time" ) var randchars [94]byte func init() { var i byte for i = 33; i <= 126; i++ { randchars[i-33] = i } rand.Seed(time.Now().UnixNano()) } //Randstr Randstr func Randstr(strlen int) string { data := make([]byte, strlen) for i := 0; i < strlen;...
package main import ( "net" "fmt" "bufio" "strings" ) func main() { l,err:=net.Listen("tcp",":8080") if err!=nil{ fmt.Println(err) } for{ c,err:=l.Accept() //here we accept the tcp connection in c and now we can read and write on this connection if err!=nil{ fmt.Println(err) continu...
package hacks import ( "net/http" "net/http/httputil" ) func WorkingKey(w http.ResponseWriter, r *http.Request) { rev := httputil.ReverseProxy{} rev.ServeHTTP(w, r) }
///////////////////////////////////////////////////////////////////// // arataca89@gmail.com // 20210423 // // Implementa uma fila de strings usando slice // package main import ( "fmt" "os" ) var queue = make([]string, 1) var start = true func push(item string) { if start { queue[0] = item ...
/* 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 writing, so...
/* Copyright 2018-2020, Arm Limited and affiliates. 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 writ...
// Copyright Fuzamei Corp. 2018 All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package executor import ( "github.com/33cn/chain33/types" pty "github.com/GM-Publicchain/gm/plugin/dapp/valnode/types" ) // Query_GetValNodeByHeight method fu...
package message import ( "context" "time" ) type Table map[string]interface{} // exchange 参数 type ExchangeOptions struct { Name string Kind string Durable bool AutoDelete bool Internal bool NoWait bool Args Table // Other options Context context.Context } type ExchangeOption fu...
package main import ( "io" "log" "net/http" ) func main() { http.HandleFunc("/", serveIndexHTML) http.HandleFunc("/tody.jpg", serveTodyPicture) err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatalln(err) } } func serveIndexHTML(res http.ResponseWriter, req *http.Request) { res.Header().Add(...
package 数学 func isBoomerang(points [][]int) bool { v1 := NewVector(points[0][0]-points[1][0],points[0][1]-points[1][1]) v2 := NewVector(points[0][0]-points[2][0],points[0][1]-points[2][1]) return !isParallel(v1,v2) } // ----------- Vector ---------- type Vector struct { X int Y int } func NewVector(x, y int) ...
package main import ( "encoding/json" "net/http" "strconv" auth "github.com/ahmedash95/authSDK" "github.com/gorilla/mux" ) func PostsCreateHandler(w http.ResponseWriter, r *http.Request) { decoder := json.NewDecoder(r.Body) var post Post err := decoder.Decode(&post) if err != nil { jsonResponse(w, err, 40...
/****************************************************************************** Blogo's main package /*****************************************************************************/ package main import ( "fmt" "github.com/eligiobz/blogo/handlers" "net/http" ) // Unpack assets built with go-resources // github.co...
// 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 circuit provides Escher gates // for building dynamic cloud applications // using the circuit runtime of http://gocircuit....