text
stringlengths
11
4.05M
package main import ( "os" "github.com/sirupsen/logrus" dockerclient "github.com/docker/docker/client" "github.com/square/p2/pkg/hooks" "github.com/square/p2/pkg/logging" "github.com/square/p2/pkg/manifest" "github.com/square/p2/pkg/pods" "github.com/square/p2/pkg/types" "github.com/square/p2/pkg/uri" "git...
package secretbox import ( "testing" "github.com/stretchr/testify/require" ) func TestSecretKey(t *testing.T) { secretKey := New() plaintext1 := []byte("hello world") ciphertext := secretKey.Seal(plaintext1) plaintext2, err := secretKey.Open(ciphertext) require.NoError(t, err) require.Equal(t, plaintext1, pl...
// Copyright 2019 CUE 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 ...
package iban import "testing" func TestValidate(t *testing.T) { cases := map[string]bool{ "DE44 # 5001 0517 5407 3249": false, "DE44 5001 0517 5407 3249 231": false, "de44 5001 0517 5407 3249 31": true, "DE44 5001 0517 5407 3249 31": true, "GR16 0110 1250 0000 0001 2300 695": true, ...
package wikipedia import "testing" func contains(s []string, e string) bool { for _, a := range s { if a == e { return true } } return false } func TestGetLanguages(t *testing.T) { t.Parallel() w := NewWikipedia() languages, err := w.GetLanguages() if err != nil { t.Error("Failed to get languages") ...
package sleepy import ( "github.com/stretchr/testify/require" "testing" ) func TestChannelFullBufferWorstCase(t *testing.T) { channel := NewChannel(nil) i := 0 for len(channel.queue) == 0 { i++ channel.Write(nil) require.NoError(t, channel.Update(0)) } require.EqualValues(t, channel.endpoint.config.Rec...
package sqlbuilder import ( . "github.com/smartystreets/goconvey/convey" "testing" ) func TestConstraints(t *testing.T) { Convey("Constraints SQL generation", t, func() { cache := &VarCache{} Convey("and combined", func() { c := new(constraint) c.gate = gate_and c.addChild(Equal{"foo", 10}) c.add...
package commands import ( "fmt" "github.com/qubitz/lawyer/constants" ) // A Command executes a predefined procedure established before its creation. type Command interface { Execute() error } type setup interface { Parse(args []string) Command } var helpSuggestion = "use \"lawyer help\" to show usage informati...
package types type ReqContent struct { Tag string Command string Params []string } type P2pRequest struct { ReqType string Content ReqContent } type BroadUnitEntity struct { HasPeers []string Message string } type LightNewUnitEntity struct { FromAddress string ToAddress string Amount int } t...
package master import ( "github.com/stretchr/testify/assert" "net/http" "net/http/httptest" "testing" ) func TestCheckStatusCode(t *testing.T) { testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) { })) responseStatusCode := checkStatusCode(testServer.URL) ass...
package pgsql import ( "database/sql" "database/sql/driver" "strconv" ) // Int8ArrayFromIntSlice returns a driver.Valuer that produces a PostgreSQL int8[] from the given Go []int. func Int8ArrayFromIntSlice(val []int) driver.Valuer { return int8ArrayFromIntSlice{val: val} } // Int8ArrayToIntSlice returns an sql....
package queue type Queue []interface{} func NewQueue() *Queue { return &Queue{} } func (q *Queue) Enqueue(v interface{}) { *q = append(*q, v) } func (q *Queue) Equeue() (v interface{}) { if len(*q) == 0 { return nil } v = (*q)[0] *q = (*q)[1:] return } func (q *Queue) len() int { return len(*q) } func ...
package csender import ( "bytes" "encoding/json" "net/http" "time" "net/url" "strings" "compress/gzip" "crypto/tls" "fmt" log "github.com/sirupsen/logrus" ) func (cs *Csender) initHubHttpClient() { if cs.hubHttpClient == nil { tr := *(http.DefaultTransport.(*http.Transport)) if cs.rootCAs != 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 auth defines an opinionated wrapper around OAuth2. It hides configurability of base oauth2 library and instead makes a predefined set of choic...
package controllers import ( "./../../pkg" pkg_model "./../../pkg/models" "./../../transfer/task" "cydex" "cydex/transfer" "errors" clog "github.com/cihub/seelog" "strconv" "strings" "time" ) func fillTransferState(state *cydex.TransferState, uid string, size uint64, jd *pkg_model.JobDetail) { state.Uid = ...
package main import ( "errors" "fmt" "os" "os/exec" "runtime" "strings" "time" "github.com/AlecAivazis/survey/v2" "github.com/AlecAivazis/survey/v2/core" "github.com/GoAdminGroup/go-admin/modules/db" "github.com/GoAdminGroup/go-admin/plugins/admin/modules" "github.com/GoAdminGroup/go-admin/plugins/admin/m...
package main import "github.com/gin-gonic/gin" func main() { server := gin.Default() server.GET("/test", func(ctx *gin.Context) { ctx.JSON(200, gin.H{ "message": "heloo kalam", }) }) server.Run(":8080") }
package main import ( "encoding/json" "io/ioutil" "os" "path/filepath" ) type Conf struct { ClientSecret string `json:"clientSecret"` CalendarId string `json:"calendarId"` DebugCalendarId string `json:"debugCalendarId"` } func (conf *Conf) Load() (err error) { row, err := ioutil.ReadFile(filepath.Joi...
// Copyright 2021 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 history import ( "github.com/stellar/go/xdr" "github.com/stretchr/testify/mock" ) // MockQHistoryClaimableBalances is a mock implementation of the QClaimableBalances interface type MockQHistoryClaimableBalances struct { mock.Mock } func (m *MockQHistoryClaimableBalances) CreateHistoryClaimableBalances(id...
package main import ( _ "gowechatsubscribe/routers" "fmt" "github.com/astaxie/beego" "github.com/astaxie/beego/context" "github.com/silenceper/wechat" "github.com/silenceper/wechat/message" "gowechatsubscribe/dblite" "github.com/going/toolkit/log" "gowechatsubscribe/controllers" "gowechatsubscribe/models" ) ...
package pgtest import ( "database/sql" "testing" _ "github.com/lib/pq" gc "gopkg.in/check.v1" ) func Test(t *testing.T) { gc.TestingT(t) } type S struct { PGSuite } var _ = gc.Suite(&S{}) func (s *S) TestRun(c *gc.C) { db, err := sql.Open("postgres", s.URL) c.Assert(err, gc.IsNil) var n int err = db.Quer...
package main import ( "KafkaLog/src/KafkaLag/GetCluster" "KafkaLog/src/KafkaLag/GetConsumers" getlag "KafkaLog/src/KafkaLag/GetLag" "fmt" ) const ( url string = "xxxxx:8000/v3/kafka/" ) func main() { c, err := kafkaclusters.GetCluster(url) if err != nil { fmt.Println("get kafka cluster faild:", err) } clu...
package main import ( "fmt" "time" ) func main() { go say("virat") go say("kohli") // time.Sleep(time.Second) } func say(greet string) { for i := 0; i < 3; i++ { fmt.Println(greet) } }
package tc /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "Lic...
package main import ( "database/sql" "fmt" ) type task struct { ID int `json:"id"` Completed bool `json:"completed"` Description string `json:"description"` } func (t *task) getTask(db *sql.DB) error { statement := fmt.Sprintf("SELECT description, completed FROM tasks WHERE id=%d", t.I...
// Copyright 2017 Martin Hebnes Pedersen (LA5NTA). All rights reserved. // Use of this source code is governed by the MIT-license that can be // found in the LICENSE file. package main import ( "log" "net" "sync" "time" ) type TransportListener interface { Init() (net.Listener, error) Name() string CurrentFre...
package main import ( "fmt" "strconv" "os" "bufio" ) //常规写法 func normalFor() { sum := 0 for i := 1; i <= 100; i++ { sum += i } fmt.Println(sum) } //省略初始条件,相当于while func convertToBin(n int) string { result := "" for ; n > 0; n /= 2 { lsb := n % 2 result = strconv.Itoa(lsb) + result } return result }...
package scrabble import ( "strings" ) var values = map[string]int{ "A": 1, "E": 1, "I": 1, "O": 1, "U": 1, "L": 1, "N": 1, "R": 1, "S": 1, "T": 1, "D": 2, "G": 2, "B": 3, "C": 3, "M": 3, "P": 3, "F": 4, "H": 4, "V": 4, "W": 4, "Y": 4, "K": 5, "J": 8, "X": 8, "Q": 10, "Z": 10, } //Score - Computes the scrabbl...
package template func init() { Default.Add("version.go", Version, "cmd/version.go") Default.Add("versions.go", LibVersion, "pkg/versions/versions.go") Default.Add("description.go", Description, "pkg/versions/description.go") } // Version cmd/version.go模板 const Version = ` package cmd import ( "{{.importPath}}/pk...
package rangeproof import ( "math/big" "math/rand" "testing" ristretto "github.com/bwesterb/go-ristretto" "github.com/stretchr/testify/assert" ) func TestProveBulletProof(t *testing.T) { // due to inner product proof, must be a multiple of two m := 4 amounts := []ristretto.Scalar{} for i := 0; i < m; i++...
package main import ( _ "server-monitor-admin/config" "server-monitor-admin/core" "server-monitor-admin/global" "server-monitor-admin/initialize" ) func main() { //初始化mysql initialize.Mysql() //注册所有表 initialize.DbTables() //程序结束关闭数据库连接 defer global.DB.Close() //启动服务 core.RunServer() }
package objs type IpasTrackingFilter struct { IpasFilter EquipIdWithOrg string `form:"equip_id_with_org"` }
package models // Models generated from: https://mholt.github.io/json-to-go/ type BlockRes struct { Hash string `json:"hash"` Size int `json:"size"` Version int `json:"version"` Previousblockhash string `json:"previousblockhash"` Merkleroot string `json:"merkleroo...
// Copyright 2022 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 gatekeeper import "log" func RetryAndPanic(retries uint, f func() error) { // retry a function n times before panicing and closing out the // program. This should only be for exceptional cases err := f() for i := uint(0); i <= retries; i++ { if err == nil { return } err = f() } log.Fatal(err)...
package data_test import ( "accountapi/data" "encoding/json" "strings" "testing" "github.com/biter777/countries" ) // TestCCode for testing unmarshalling JSON values. type TestCCode struct { TestCC data.CountryCode `json:"testCC"` } // TestCountryCode verifies proper country codes parsing and unmarshalling. f...
package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" "log" "time" ) var MysqlDb *sql.DB var MysqlDbErr error const ( UserName = "root" PassWord = "jsw135799" HOST = "115.29.243.4" PORT = "3306" DATABASE = "blog" CHARSET = "utf8" ) // 初始化链接 func init() { dbDSN := fmt.Sp...
package unionfind import ( "fmt" "math" "testing" ) func setupUnionCalls(uf UnionFind) { uf.Union(4, 3) uf.Union(3, 8) uf.Union(6, 5) uf.Union(9, 4) uf.Union(2, 1) uf.Union(8, 9) uf.Union(5, 0) uf.Union(7, 2) } var expectedConnectedResults = []struct { p, q int expected bool }{ {0, 1, false}, {0, ...
// consume the queue called 'encryptonator' and run a go routine to start // the encryption process package main import ( "fmt" "log" "strings" "github.com/streadway/amqp" ) type consumer struct { uri string exchange string exchangeType string queueName string bindingKey string consumerTa...
package models import ( "github.com/gophergala2016/source/core/foundation" ) type UserRepository struct { RootRepository } func NewUserRepository(ctx foundation.Context) *UserRepository { return &UserRepository{ RootRepository: NewRootRepository(ctx), } } func (r *UserRepository) GetByID(id uint64) (*User, er...
package api import ( "encoding/json" "fmt" "sync" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/CosmWasm/wasmvm/types" dbm "github.com/tendermint/tm-db" ) type queueData struct { checksum []byte store *Lookup api *GoAPI querier types.Querier } ...
package models import "fmt" const ( _keyID = "id" _keyFieldsets = "fieldsets" _keyFields = "fields" ) // From models the structure of an HTML Form type Form struct { ID string `json:"id"` Fieldsets map[string]Fieldset `json:"fieldsets"` Fields map[string]Field `json:"fields"...
package taskpool import ( "errors" "time" ) var ( errPoolSizeNotValid = errors.New("pool size not valid") errQueueSizeNotValid = errors.New("pool size not valid") errPoolFull = errors.New("pool is full") errPoolTimeout = errors.New("timeout") errPoolPanic = errors.New("panic") errPoolC...
package prototype // cloneable接口 type Cloneable interface { Clone() Cloneable } // 原型类,实现cloneable接口 type Handler struct { Name string } func NewHandler(name string) *Handler { return &Handler{Name: name} } func (s *Handler) GetName() string { return s.Name } func (s *Handler) SetName(name string) { s.Name = ...
package main //Request hold the content for performing cloning type Request struct { App App Bucket string Content []byte `json:"content"` Key string `json:"key"` }
package middleware import ( "net/http" "github.com/ismar/dsa/distrybuted_systems_api/utils" ) //Middleware ... type Middleware struct{} // CORS ... func (m Middleware) CORS(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) { // CORS support for Preflighted requests res.Header().Set("Access-Cont...
package lib type H map[string]interface{}
/* Copyright 2020 Kamal Nasser 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 applicable law or agreed to in wr...
package main import ( "fmt" "time" "github.com/eapache/go-resiliency/retrier" ) func main() { n := 0 r := retrier.New(retrier.ConstantBackoff(3, 1*time.Second), nil) err := r.Run(func() error { fmt.Println("Attempt: ", n) n++ return fmt.Errorf("Failed") }) if err != nil { fmt.Println(err) } }
package ionic import ( "bytes" "encoding/json" "fmt" "github.com/ion-channel/ionic/aliases" "github.com/ion-channel/ionic/pagination" "github.com/ion-channel/ionic/projects" "github.com/ion-channel/ionic/requests" "github.com/ion-channel/ionic/tags" "io" "mime/multipart" "net/http" "net/url" "os" "reflec...
package DCP import ( "encoding/csv" "encoding/json" "fmt" "github.com/google/uuid" "math/big" "math/rand" "os" "strconv" "testing" "time" ) func TestCalculationObjectPaillier_KeyGen(t *testing.T) { nodes := make([]CtNode, 10) for _, node := range nodes { node = CtNode{ Id: uuid.New(), ...
package octopus import ( "strconv" "testing" ) func Test_CachedWorkerPool(t *testing.T) { pool, _ := NewCachedWorkerPool() f, err := pool.SubmitCallable(func () interface{} { t.Log("Hi") return "Hi, result" }) if err != nil { t.Error(err) } v, _ := f.Get() t.Log(v) pool.SubmitRunnable(func () { ...
package main func main() { } func buildTree(preorder []int, inorder []int) *TreeNode { if len(preorder) == 0 { return nil } root := &TreeNode{preorder[0], nil, nil} var stack []*TreeNode stack = append(stack, root) var inorderIndex int for i := 1; i < len(preorder); i++ { preorderVal := preorder[i] node...
package jarviscore import ( "context" "io" "sync" "time" "google.golang.org/grpc/codes" "github.com/zhs007/jarviscore/coredb" coredbpb "github.com/zhs007/jarviscore/coredb/proto" "go.uber.org/zap" jarvisbase "github.com/zhs007/jarviscore/base" pb "github.com/zhs007/jarviscore/proto" "google.golang.org/...
package request import "quan/model" type SysDictionarySearch struct { model.SysDictionary PageInfo }
/* Copyright 2023 MediaExchange.io 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" "math/rand" ) func main() { fmt.Print(rand.Intn(100), ",") fmt.Print(rand.Intn(100)) fmt.Println() fmt.Println(rand.Float64()) fmt.Println(int(10 * rand.Float64())) }
package graphkb import "github.com/clems4ever/go-graphkb/internal/schema" type AssetType = schema.AssetType type RelationKeyType = schema.RelationKeyType type RelationType = schema.RelationType
package main import ( "fmt" //"strings" "crypto/md5" //"strconv" "io" "encoding/hex" "strconv" "strings" ) func in_array(a string, list [8]string) bool { for _, b := range list { if b == a { return true } } return false } func main() { door_id := "abc" found := fal...
package client import ( "github.com/json-iterator/go" "errors" ) var json = jsoniter.ConfigCompatibleWithStandardLibrary type Client struct { server_addr string acid string } var WxClient = &Client{ "", "", } func InitClient(addr string, acid string) { (*WxClient).server_addr = addr (*WxClient).acid...
package goSolution import "testing" func TestKInversePairs(t *testing.T) { AssertEqual(t, 2, kInversePairs(3, 1)) }
package sqls // InsResult is SQL. const InsResult = ` INSERT INTO results ( competition_id , user_id , user_name , url , ttl_ns_per_op , ttl_alloced_bytes_per_op , ttl_allocs_per_op , file_path , created_at , updated_at ) VALUES ( ? , ? , ? , ? , ? , ? , ? , ? , CURRENT_TIMESTAMP , CURRENT_TIMEST...
package point import ( "testing" "github.com/go-gl/mathgl/mgl32" ) type testShader struct { } func (t testShader) Use() { } func (t testShader) SetUniformMat4(s string, m mgl32.Mat4) { } func (t testShader) DrawPoints(i int32) { } func (t testShader) Close(i int) { } func (t testShader) VertexAttribPointer(i uint...
package main import "fmt" func ascOrder(num1 int, num2 int) []int { if num1 < num2 { return []int{num1, num2} } return []int{num2, num1} } func main() { fmt.Println(ascOrder(2, 7)) fmt.Println(ascOrder(7, 2)) }
package parser_test import ( "errors" "testing" parser "github.com/romshark/llparser" "github.com/romshark/llparser/misc" "github.com/stretchr/testify/require" ) type FragKind = parser.FragmentKind const ( _ FragKind = misc.FrSign + iota TestFrFoo TestFrBar ) func rncmp(a, b []rune) bool { for i, x := ran...
package http import ( "errors" "github.com/spiral/roadrunner" "github.com/spiral/roadrunner/service" "strings" "time" ) // Config configures RoadRunner HTTP server. type Config struct { // Enable enables http svc. Enable bool // Address and port to handle as http server. Address string // MaxRequest speci...
package service import "github.com/saravase/golang_echo_api/entity" type PlantService interface { Save(entity.Plant) entity.Plant FindAll() []entity.Plant } type service struct { plants []entity.Plant } func New() PlantService { return &service{ plants: []entity.Plant{}, } } func (service *service) Save(pla...
package rp import ( "bytes" "encoding/json" "net/http" ) type TestItemType string type ExecutionStatus string type LogLevel string type Mode string const ( // TimestampLayout can be used with time.Parse to create time.Time values from strings. TimestampLayout = "2006-01-02T15:04:05.000Z" // TestItemTypeSuite ...
/* The generalised harmonic number of order m of n is H(n,m)=sum[k, n] 1/k^m For example, the harmonic numbers are H(n, 1) and H(∞,2)=π^2/6. These are related to the Riemann zeta function as ζ(m)=lim n→∞ H(n,m) Given two positive integers n>0, m>0, output the exact rational number H(n,m). The fraction should be re...
package model type PlayerLicenseAnalytics struct { // Analytics License Key AnalyticsKey string `json:"analyticsKey,omitempty"` }
package Problem0275 // a 为升序排列 func hIndex(a []int) int { size := len(a) // 二分查找法 lo, hi := 0, size-1 // lo, miD, hi 都是降序切片 d 中的序列号 // 因为 a 是 d 的逆序,即 a 是升序切片 // d[miD] , a[miA] 是同一个数 // 所以,存在数量关系,miD + miA +1 == size var miD, miA int for lo <= hi { miD = (lo + hi) / 2 miA = size - miD - 1 if a[miA] > m...
package main import ( "log" "net/http" ) func handleCategoryOverview(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/categories/" { handleNotFound(w, r) return } session, _ := store.Get(r, "session") ctx, err := createContextFromSession(db, session) if !err.Empty() { err.AddTraceback("hand...
package tameshigiri import "testing" // func ExampleAssertion() { var t = &testing.T{} var assertion = Assertion{ T: t } var expected = 123 var actual = 123 assertion.IsTrue(expected == actual, "Ye") assertion.IsFalse(expected != actual, "Ne") assertion.Equals(expected, actual...
package apimodels type ApiResult struct { Success bool `json:"success"` Msgs []string `json:"msgs"` }
package starwars_test import ( "encoding/json" "net/http" "net/http/httptest" "testing" golangtraining "github.com/julianjca/julian-golang-training-beginner" "github.com/julianjca/julian-golang-training-beginner/internal/starwars" "github.com/stretchr/testify/require" ) func TestGetCharacters(t *testing.T) { ...
package log import ( "encoding/json" "reflect" "testing" ) func TestFixFieldsConflict(t *testing.T) { m := map[string]interface{}{ "request_id": "request_id", "time": "time", "field.time": "field.time", "level": "level", "field.level": "field.level", "field.level.2": "field.le...
package model import ( "fmt" ) type Employee struct { ID int32 FirstName string LastName string BadgeNumber int32 } // Demo2 print hello func Demo2() { fmt.Println("hello model") }
package tenant import ( "github.com/imsilence/gocmdb/server/cloud" "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common" "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile" cvm "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cvm/v20170312" ) type TenantCloud struct { ...
package sql import ( "bufio" "strconv" "strings" "unicode" ) var eof = rune(0) var bufSizeHint = 32 type Lexeme struct { Token Token Lit string } type Scanner struct { r *bufio.Reader } func NewScanner(r *strings.Reader) *Scanner { s := Scanner{r: bufio.NewReader(r)} return &s } func (s *Scanner) Scan(...
package main import ( "fmt" ) func main() { test([]int{}, 0, []int{}) test([]int{1}, 1, []int{1}) test([]int{1, 1, 2}, 3, []int{1, 1, 2}) test([]int{1, 1, 1, 2, 2}, 4, []int{1, 1, 2, 2}) test([]int{1, 1, 1, 2, 2, 2, 3}, 5, []int{1, 1, 2, 2, 3}) test([]int{1, 1, 1, 1, 3, 3}, 4, []int{1, 1, 3, 3}) } func test(n...
package main import ( "fmt" "log" "encoding/json" "github.com/go-resty/resty/v2" . "github.com/logrusorgru/aurora" ) // Refer to this. // https://github.com/steadylearner/Rust-Full-Stack/blob/master/bots/teloxide/src/community-bots/models/subreddit.rs type Post struct { Title string Url string } type Chi...
// Copyright 2017 Gruppe 12 IS-105. All rights reserved. package main import ( "fmt" "net" "./Crypt" ) func sendResponse(conn *net.UDPConn, addr *net.UDPAddr) { _,err := conn.WriteToUDP([]byte("From server: Hello I got your mesage "), addr) if err != nil { fmt.Printf("Couldn't send response %v", err) } } co...
/** * @Author: korei * @Description: * @File: VirtualCoinBox * @Version: 1.0.0 * @Date: 2020/11/18 下午7:08 */ package virtualHardWare import ( "fmt" "sync" ) type VirtualCoinBox struct { count float32 countMutex sync.Mutex } func (v *VirtualCoinBox) Cost(count float32) bool { v.countMutex.Lock() de...
package main import ( "github.com/DanielRenne/mangosNode/push" "log" "time" ) const url = "tcp://127.0.0.1:600" func main() { var node push.Node err := node.Connect(url) if err != nil { log.Printf("Error: %v", err.Error) } //Code a forever loop to stop main from exiting. for { time.Sleep(3 * time.Sec...
package main import ( "fmt" ) func main() { msg1 := make(chan int, 3) msg2 := make(chan int, 3) defer close(msg1) defer close(msg2) go func (){ // msg1 <- 2 }() var result int select { case result=<-msg1: fmt.Println("msg1") case result=<-msg2: fmt.Println("msg2") default: fmt.Println("defaul...
package repo import ( "fmt" "strings" "github.com/kyma-incubator/compass/components/director/pkg/apperrors" "github.com/jmoiron/sqlx" "github.com/pkg/errors" ) func getAllArgs(conditions Conditions) []interface{} { var allArgs []interface{} for _, cond := range conditions { if argVal, ok := cond.GetQuery...
package main import ( "flag" "github.com/garyburd/redigo/redis" "github.com/gorilla/websocket" "log" "os" ) type Live struct { connections []*connection `json:"-"` silentusers []string `json:"-"` chatrecord []byte `json:"-"` online int `json:"-"` } type connection struct { // Th...
package pet // todo 写入文件 const ( WEAPON_ATTR_CRIT = 1 // 暴击 WEAPON_ATTR_FLASH = 2 // 闪避 WEAPON_ATTR_REST = 3 // 休息 WEAPON_ATTR_LOCK = 4 // 必中 WEAPON_ATTR_CONT = 5 // 连续 WEAPON_ATTR_DODGE = 6 // 闪避 KIND_S = 0 KIND_M = 1 KIND_L = 2 KIND_T = 3 // 投掷类 ) var Skills = []Skill{ { Id: 0, Name: "胶水",...
package timeline import ( "encoding/json" "fmt" "github.com/xeipuuv/gojsonschema" "io/ioutil" "strings" "time" ) func ProcessFile(inputPath string, ch chan<- ShortResult) { start := time.Now() buffer, err := ioutil.ReadFile(inputPath) if err != nil { ch <- ShortResult{fmt.Sprintf("can't read input file: %...
/* NOTE : - there's MANUAL cleaning data in input ex: b4 : 128 x 128pixels a4 : 128 x 128 pixels b4 : pixels| a4 : pixel b4 : 6 lines| 101 x 67 pixels a4 : 101 x 67 pixels - 1 chars = 8 pixels */ package display_size import ( util "github.com/verlandz/clustering-phone/utility" "os" "strconv" "strin...
package mathutil_test import ( "fmt" "github.com/AdguardTeam/golibs/mathutil" ) func ExampleBoolToNumber() { fmt.Println(mathutil.BoolToNumber[int](true)) fmt.Println(mathutil.BoolToNumber[int](false)) type flag float64 fmt.Println(mathutil.BoolToNumber[flag](true)) fmt.Println(mathutil.BoolToNumber[flag](fa...
package main import ( "context" "database/sql" "flag" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/go-chi/cors" article2 "github.com/hardstylez72/bblog/internal/api/controller/article" objectstorage2 "github.com/hardstylez72/bblog/internal/api/controller/objectstorage" user2 "github....
package model import ( "fmt" "mvc-app/util" "net/http" ) var person = map[uint64]*User{ 123: &User{ FName: "Diwakar", LName: "Singh", Email: "diwakar@gmail.com", }, 124: &User{ FName: "Ravi", LName: "Kumar", Email: "ravi@gmail.com", }, } type userService struct{} var UserService userService fun...
// ------------------------------------------------------------------- // // salter: Tool for bootstrap salt clusters in EC2 // // Copyright (c) 2013-2014 Orchestrate, Inc. All Rights Reserved. // // This file is provided to you under the Apache License, // Version 2.0 (the "License"); you may not use this file // exce...
package main import ( "context" "fmt" "github.com/spf13/cobra" cmder "github.com/yaegashi/cobra-cmder" msgraph "github.com/yaegashi/msgraph.go/beta" V "github.com/yaegashi/msgraph.go/val" ) type AppSP struct { *App SpID string ServicePrincipalList []msgraph.ServicePrincipal ServicePrincipal...
package line_segment import ( "../basic" "../gfx" "github.com/go-gl/gl/v4.1-core/gl" "github.com/lucasb-eyer/go-colorful" ) type Bezier struct { p0, p1, p2, p3 *basic.Point q0, q1, q2, q3 *basic.Point b1, b2 *bead } func NewBezier(p0, p1, p2, p3 *basic.Point) *Bezier { vertShader, err := gfx.NewShaderFromFil...
package util import "bitbucket.org/inehealth/idonia-common/filter" //Ascendant sql string const Ascendant = "ASC" //Descendant sql string const Descendant = "DESC" //PageResult pagination struct type PageResult struct { CurrentPage int `json:"current_page"` TotalPages int ...
package handler import ( "context" "errors" "path/filepath" "testing" proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/user/v1" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) // UnsetSecureEmailTestSuite 通过密保问题重置密码测试 type UnsetSecureEmailTestSuite struct { suite.Su...
package environment import ( "context" "fmt" "os" "sync/atomic" "time" gomegaConfig "github.com/onsi/ginkgo/config" "github.com/onsi/gomega" "github.com/pkg/errors" "github.com/spf13/afero" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" _ "k8s.io/client-go/plugin/pkg/client/a...