text
stringlengths
11
4.05M
package main import ( "fmt" "os" "github.com/urfave/cli" "github.com/micnncim/git-emot/cmd" ) func init() { if !cmd.IsInitialized() { fmt.Println("Initialize") if err := cmd.InitMsgs(); err != nil { fmt.Println(err) } } } func main() { app := cli.NewApp() app.Name = "git-emot" app.Commands = []cl...
package main import "fmt" func main() { switch "Shikamaru" { case "Sasuke", "Naruto", "Sakura": fmt.Println("Team 7") case "Shikamaru", "Choji", "Ino": fmt.Println("Team 10") case "Kiba", "Hinata", "Shino": fmt.Println("Team 8") case "Neji", "Lee", "Tenten": fmt.Println("Team 11") default: fmt.Println...
package hermes import ( "encoding/json" "fmt" "runtime" "time" "github.com/gorilla/websocket" ) type WebSocket struct { ws *websocket.Conn quit chan bool Stream chan *Event Errors chan error } type Event struct { Event string `json:"event"` Data interface{} `json:"data"` } func (s *WebSocket...
package practice import ( "fmt" "testing" ) func Test_cloneGraph(t *testing.T) { type args struct { node *Node } tests := []struct { name string args args }{ { name: "example 1", args: args{ node: newGraph([][]int{ {2, 4}, {1, 3}, {2, 4}, {1, 3}, }), }, }, } for _, tt := range ...
package main import ( "flag" "fmt" "os" "sort" "strings" "github.com/aws/aws-sdk-go-v2/aws/endpoints" "github.com/aws/aws-sdk-go-v2/aws/external" "github.com/aws/aws-sdk-go-v2/service/ec2" ) // Version of the CLI const CLIVersion = "0.2.1" func main() { cfg, err := external.LoadDefaultAWSConfig() if err ...
package datastruct import ( "github.com/MintegralTech/juno/document" . "github.com/smartystreets/goconvey/convey" "testing" ) func TestSliceIterator(t *testing.T) { sl := NewSlice() sl.Add(1, nil) sl.Add(3, nil) Convey("New Slice Iterator", t, func() { iter := sl.Iterator() v := iter.Current() So(v, Sho...
package Modules import "flag" type config struct { Port string Path string SUrl string Logg string } var Config config func (a *config) Init() { flag.StringVar(&a.Port, "p", "233", "监听端口") flag.StringVar(&a.Path, "path", "/", "心跳路径") flag.StringVar(&a.SUrl, "url", "", "上报URL") flag.StringVar(&a.Logg, "log",...
package esSearch import ( . "github.com/smartystreets/goconvey/convey" "testing" ) func TestIsEsCluserOk(t *testing.T) { Convey("test is es cluster is ok", t, func() { Convey("case 1,succ", func() { isOK := IsEsCluserOk() So(isOK, ShouldBeTrue) }) }) } func TestNewEsClient(t *testing.T) { esCli := New...
package config import ( "encoding/json" "fmt" "strings" jT "github.com/kellerza/template" log "github.com/sirupsen/logrus" "github.com/srl-labs/containerlab/nodes" "github.com/srl-labs/containerlab/types" ) // templates to execute var TemplateNames []string // path to additional templates var TemplatePaths ...
package infrastructure import ( "encoding/json" "fmt" "net/http" "strconv" "time" "github.com/julienschmidt/httprouter" "github.com/michaldziurowski/tech-challenge-time/server/timetracking/usecases" ) const USERID string = "user@domain.com" func HttpHandler() http.Handler { inMemoryStorage := NewInMemorySto...
package main import ( "database/sql" "encoding/json" "fmt" _ "github.com/go-sql-driver/mysql" "io/ioutil" "log" "net/http" "strconv" "time" ) type withdrawalData struct { UserId int Alipay string Name string Amount int } type handlCash struct { UserId int...
package injector import ( corev1 "k8s.io/api/core/v1" ) const ( patchPathContainer = "/spec/containers/1" patchPathAnnotation = "/metadata/annotations" ) // PodPatch represents a RFC 6902 patch document for pods. type PodPatch struct { original *corev1.Pod patchOps []*patchOp } // NewPodPatch returns a new in...
package config import ( "log" "os" "github.com/joho/godotenv" ) type SpotifyConfig struct { ClientID string SecretKey string } type JwtConfig struct { SecretKey string } type Config struct { Spotify SpotifyConfig Jwt JwtConfig } func Init() *Config { err := godotenv.Load() if err != nil { log.Pri...
package sdk import ( "testing" rmTesting "github.com/brigadecore/brigade/sdk/v3/internal/restmachinery/testing" // nolint: lll "github.com/stretchr/testify/require" ) func TestNewCoreClient(t *testing.T) { client, ok := NewCoreClient( rmTesting.TestAPIAddress, rmTesting.TestAPIToken, nil, ).(*coreClient) ...
package main import ( "demo-api-go/api" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.GET("/", api.Root) router.Run(":9000") }
package main import ( "context" "encoding/json" "fmt" "golang.org/x/oauth2" "golang.org/x/oauth2/google" "google.golang.org/api/gmail/v1" "io/ioutil" "log" "net/http" "os" "path/filepath" ) const ( ClientSecretFileName = "client_secret.json" CachedTokentFileName = "gmail-access.json" ) // Based on https...
package model import "time" // UserDetail 用户详情 type UserDetail struct { Unionid string `json:"unionid"` // 员工在当前开发者企业账号范围内的唯一标识,系统生成,固定值,不会改变 Name string `json:"name"` // 员工名字 Tel string `json:"tel"` // 分机号(仅限企业内部开发调用) WorkPlace string ...
/** * @author liangbo * @email liangbogopher87@gmail.com * @date 2017/9/24 20:41 */ package utils import ( "fmt" "strings" "strconv" ) type ErrCode int const ( //需要返回http500的错误码 OKCode ErrCode = 0 InternalErrorCode ErrCode = 1 DbErrCode ErrCode = 2 Cach...
package i18n /* this file only define msgids ,i18n msg content is in ui : ui/src/core/library/locale */ const ServerInternalError = "error.serverInternal" const BadRequestData = "error.badRequestData" const NoPermission = "error.noPermission" const TeamNotExist = "error.teamNotExist" const UserNotExist = "error.userN...
// Package main - package main import ( "fmt" "github.com/shanehowearth/concurrency_in_go/pipeline" ) func main() { done := make(chan interface{}) defer close(done) intStream := pipeline.Generator(done, 1, 2, 3, 4) p := pipeline.Multiply(done, pipeline.Add(done, pipeline.Multiply(done, intStream, 2), 1), 2) ...
package main import ( "log" ) func hanoi(l []int,x,y,z string){ length := len(l) if length == 1{ log.Printf("move %d from %s to %s",l[0],x,z) }else{ hanoi(l[:length-1],x,z,y) log.Printf("move %d from %s to %s",l[length-1],x,z) hanoi(l[:length-1],y,x,z) } } func main(){ l := []int{1,2,3,4,5,6,7} han...
/* * Copyright (c) 2018 Juniper Networks, Inc. All rights reserved. * * file: run_test.go * details: Deals with the setup and teardown for Unit Tests for msghandler package * */ package msghandler import ( "log" "os" "testing" opts "github.com/Juniper/collector/flow-translator/options" ) func VerifyErr...
package processes import ( "os/exec" ) type Worker interface { Kill() GetStopChan() chan bool } type worker struct { killWorkersChan chan bool killWaitChan chan bool stopChan chan bool } func (w *worker) Kill() { w.killWorkersChan <- true <-w.killWaitChan } func (w *worker) GetStopChan() chan boo...
//+build linux,arm package main import ( "net" "os" ) var ( hostname string addr string ) func initService() { hostname, _ = os.Hostname() if hostname == "" { hostname = "RaspberryPi" } hostname += ":" if conn, err := net.Dial("udp", "google.com:80"); err != nil { addr = "127.0.0.1" } else { add...
package main import ( "flag" "fmt" "log" "net/http" "github.com/shvetsiya/distribkv/db" ) var ( dbLocation = flag.String("db-location", "", "The path to bold db") httpAddr = flag.String("http-addr", "127.0.0.1:8080", "http host and port") ) func parseFlags() { flag.Parse() if *dbLocation == "" { log.Fat...
package beacon import ( "bytes" "crypto/sha256" "encoding/binary" "encoding/json" "errors" "path" "sync" bolt "github.com/coreos/bbolt" "github.com/nikkolasg/slog" ) // store contains all the definitions and implementation of the logic that // stores and loads beacon signatures. At the moment of writing, it...
package main import ( "fmt" "os" "golang.org/x/sys/unix" ) func do_bind_mount(s, t string) error { err := unix.Mount(s, t, "", unix.MS_BIND, "") if err != nil { fmt.Printf("bind-mount error received: %v\n", err) return err } return nil } func do_remount_ro(s, t string) error { err := unix.Mount(s, t,...
// Copyright 2018, 2021 Tamás Gulácsi. All rights reserved. // // SPDX-License-Identifier: Apache-2.0 package plsqlparser import ( "fmt" "log" "strings" "unicode" plsql "github.com/UNO-SOFT/plsql-parser/plsql" "github.com/antlr/antlr4/runtime/Go/antlr" ) //go:generate mkdir -p plsql //go:generate sh -c "[ -e ...
package kfdef import ( "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" ) const ( // KubeflowLabel represents Label for kfctl deployed resource KubeflowLabel = "app.kubernetes.io/managed-by" ) var ( // watchedResources contains all resources we will watch and reconcile when changed watc...
package main import ( "time" "github.com/henrylee2cn/teleport" ) func main() { teleport.GraceSignal() teleport.SetShutdown(time.Second*20, nil, nil) var cfg = &teleport.PeerConfig{ ReadTimeout: time.Minute * 3, WriteTimeout: time.Minute * 3, TlsCertFile: "", TlsKeyFile: "", Slo...
package pbengine import ( "bytes" "log" "os" "strings" "text/template" "github.com/vanishs/gwsrpc/swg" ) const tempgwsrpclits = `'use strict'; /// <reference path="../../typings/index.d.ts"/> {{ range $key, $value := .FileDatas }}/// <reference path="./{{$value.PackageName}}/{{$value.PackageName}}.d.ts"/> {{ ...
package pagerduty_test import ( "fmt" . "github.com/danryan/go-pagerduty/pagerduty" "net/http" "reflect" "testing" ) func TestUser_marshal(t *testing.T) { testJSONMarshal(t, &User{}, "{}") u := &User{ ID: "ABCDEF", Name: "Bill Williams", Email: "bill.williams@example.com", UserURL: "/users/A...
package installer import ( "strings" "github.com/wx13/genesis" ) // Task is the most fundamental Doer. It consists of just a single module. // All other Doers contain tasks at their deepest levels (i.e. only a Task // can contain a module directly. type Task struct { genesis.Module } func (task Task) Files() []s...
package create /*import ( "bytes" "encoding/base64" "encoding/json" "fmt" "io/ioutil" "os" "path/filepath" "strings" "testing" "time" cloudpkg "github.com/devspace-cloud/devspace/pkg/devspace/cloud" cloudconfig "github.com/devspace-cloud/devspace/pkg/devspace/cloud/config" cloudlatest "github.com/devspac...
package singleton var instance ParamRepository = &RepositoryImpl{} func GetInstance() ParamRepository { return instance //return &RepositoryImpl{} } func (repository *RepositoryImpl) GetParam(id int) Param { return Param{Id: id} }
package g import ( "encoding/json" "time" "log" "github.com/Shopify/sarama" "github.com/open-falcon/falcon-plus/common/model" ) var ( SYS_TOPIC string = "SYS_MONITOR" ) func SendKafkaMetrics(metrics []*model.MetricValue) { var kafkaAddrs []string = Config().Kafka.Addrs SyncProducer(kafkaAddrs, metrics) } ...
package engine import ( "bishe/spider/config" "bishe/spider/fetcher" "bishe/spider/model" "errors" "fmt" "log" "regexp" "strconv" "time" ) func Run(tasklist []config.Task) { for len(tasklist) > 0 { t := time.Tick(30*time.Second) task := tasklist[0] tasklist = tasklist[1:] data, err := fetcher.Fetche...
package models import ( "fmt" "monitor/data" "monitor/responses" "sort" ) // GetAllActionNames return all action func (md *MonitorService) GetAllActionNames() ([]string, error) { res := []string{} // var res []string; fmt.Println("GetAllActionNames ") md.ActionDailyLog.Range(func(key, _ interface{}) bool { ...
package cos_test import ( "fmt" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" sut "github.com/rancher-sandbox/ele-testhelpers/vm" ) var _ = Describe("cOS Installer EFI tests", func() { var s *sut.SUT BeforeEach(func() { s = sut.NewSUT() s.EventuallyConnects() }) Context("Using efi", func() {...
package problem0671 //TreeNode Definition for a binary tree node. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func findSecondMinimumValue(root *TreeNode) int { if root == nil { return -1 } if root.Left == nil && root.Right == nil { return -1 } leftVal := root.Left.Val rightVal := r...
package main import ( "fmt" "os" "os/exec" "os/signal" "syscall" ) var cmd = exec.Command("ping") func init() { cmd.Args = []string{"ping", "baidu.com"} cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr } func main() { signalChan := make(chan os.Signal, 1) // 2 & 15 signal.Notify(signal...
package core import ( "bytes" "sort" "strings" "time" ) // TestResults describes a set of test results for a test target. type TestResults struct { NumTests int // Total number of test cases in the test target. Passed int // Number of tests that passed outright. Failed int // Number...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-08-14 10:39 # @File : of_剑指_Offer_05_替换空格.go # @Description : # @Attention : */ package offer func replaceSpace(s string) string { bytes := make([]byte, 0) for i, j := 0, 0; i < len(s); { if s[i] == ' ' { bytes = append(bytes, '%', '2', '0') j +=...
/* Copyright © 2020-2021 The k3d Author(s) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distri...
package Data import ( "github.com/team-zf/framework/dal" "github.com/wuxia-server/login/Control" "github.com/wuxia-server/login/DataTable" ) func GetServerList() (serverList []*DataTable.Server) { serverList = make([]*DataTable.Server, 0) sqlstr := dal.MarshalGetSql(DataTable.NewServer()) rows, err := Control.G...
// array. package main import ( "encoding/json" "fmt" ) type Node struct { Name string `json:"name"` Age int `json:"age"` } type Nodes []*Node func (p *Nodes) MarshalIndent() { b, err := json.MarshalIndent(p, "", " ") if err != nil { panic(err) } fmt.Printf("%s\n", b) } func main() { var v Nodes ...
package main import ( "fmt" ) func Sqrt(x float64) float64 { y := x- (((x * x) - x) / 2 * x ) return y } func main() { fmt.Println(Sqrt(Sqrt(Sqrt(3)))) }
package api_test import ( "blog/app/common/jwt" "blog/bootstrap" "blog/config" "github.com/kataras/iris/v12/httptest" "testing" ) func init() { config.InitConfig("../../blog.yaml") } func TestUserInfo(t *testing.T) { app := bootstrap.Register() e := httptest.New(t, app) token, err := jwt.MakeToken(1, "admin...
// 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...
// Copyright 2020 The Reed Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. package vmcommon func BuildP2PKHScript(publicKeyHash []byte) []byte { var script []byte script = append(script, byte(OpDup)) script = appe...
/* Description People are different. Some secretly read magazines full of interesting girls' pictures, others create an A-bomb in their cellar, others like using Windows, and some like difficult mathematical games. Latest marketing research shows, that this market segment was so far underestimated and that there is l...
/* Copyright 2021 CodeNotary, Inc. 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 i...
package server import ( "context" "fmt" "time" "github.com/danielkvist/botio/proto" "github.com/golang/protobuf/ptypes/empty" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) // AddCommand tries to add a received command to the Server's database. It returns a non-nil error // if something wen...
package settings import ( "flag" envcfg "github.com/wealthworks/envflagset" ) var ( EmailDomain string EmailCheck bool SMTP struct { Enabled bool Host string Port int SenderName string SenderEmail string SenderPassword string } LDAP struct { Hosts string ...
/* 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...
package deletespot import ( "net/http" "github.com/doniacld/outdoorsight/internal/endpointdef" "github.com/doniacld/outdoorsight/internal/endpoints" ) // DeleteSpotMeta holds the endpoint information var DeleteSpotMeta = endpointdef.New( "DeleteSpotDetails", "/spots/{"+endpoints.ParamSpotName+"}", http.MethodD...
package geo import ( "fmt" "log" "math" "math/rand" "sync" "test/broker" "test/proto" "time" ) type XY struct { X int Y int } type GeoService struct { name string locationMu sync.RWMutex location XY activeWorkers int stop chan chan struct{} broker broker.Broker producer ...
package states import ( "context" "encoding/json" "errors" "fmt" "time" derrors "github.com/direktiv/direktiv/pkg/flow/errors" "github.com/direktiv/direktiv/pkg/model" "github.com/direktiv/direktiv/pkg/util" "github.com/google/uuid" ) func init() { RegisterState(model.StateTypeGetter, Getter) } type gette...
package zecutil import ( "errors" "fmt" "github.com/btcsuite/btcd/txscript" "github.com/btcsuite/btcutil" ) func PayToAddrScript(addr btcutil.Address) ([]byte, error) { var script []byte var err error script, err = txscript.PayToAddrScript(addr) if err == nil { return script, nil } const nilAddrErrStr =...
/** * blog_service * @author liuzhen * @Description * @version 1.0.0 2021/1/29 17:46 */ package service import ( "backend/src/module" "backend/src/repository" "backend/src/utils" "reflect" ) // 保存博客 func AddBlog(param module.Blog) ResponseBody { if utils.IsBlank(param.Title) { return NewCustomErrorRespons...
package leetcode import ( "reflect" "testing" ) func TestSortArrayByParity(t *testing.T) { if !reflect.DeepEqual(sortArrayByParity([]int{3, 1, 2, 4}), []int{4, 2, 1, 3}) { t.Fatal() } }
package conv import ( "testing" "github.com/stretchr/testify/assert" ) func TestDecode(t *testing.T) { data := []struct { in string expect string }{ {expect: "あいうえお", in: "杮杮杮柿柿柿杮杮杮柿柿柿柿柿柿杮杮柿柿柿柿柿杮柿杮杮杮柿柿柿杮杮杮柿柿柿柿柿柿杮杮柿柿柿柿杮柿柿杮杮杮柿柿柿杮杮杮柿柿柿柿柿柿杮杮柿柿柿柿杮杮柿杮杮杮柿柿柿杮杮杮柿柿柿柿柿柿杮杮柿柿柿杮柿柿柿杮杮杮柿柿柿杮杮杮柿柿柿柿柿柿杮杮柿柿柿杮柿杮柿"}, {expe...
package impl import ( "fmt" "github.com/techone577/blogging-go/model" "xorm.io/xorm" ) type postStorage struct { db *xorm.Engine } func NewPostStorage(db *xorm.Engine) *postStorage { return &postStorage{db: db} } func (p *postStorage) QueryByPostID(id string) (*model.PostInfo, error) { var post model.PostInfo...
package rest import ( "github.com/jinmukeji/jiujiantang-services/pkg/rest" proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/device/v1" "github.com/kataras/iris/v12" ) // Device 设备 type Device struct { ClientID string `json:"client_id"` SN string `json:"sn"` Model string `json:"model"` M...
// output table with results from Github search package main import ( "fmt" "io/ioutil" "log" "os" "os/exec" "sort" "strconv" "time" "github.com/fatih/color" "github.com/vlad-belogrudov/gopl/pkg/github" ) func readText() (string, error) { f, err := ioutil.TempFile("", "issue") if err != nil { return ""...
package model // 角色,资源中间表 type RoleResource struct { Id int RoleId int ResourceId int } // Assign permission to role // Id: roleId // Enable: grant permission // Disable: revoke permission type RolePrivilege struct { Id int `json:"id" bind:"required,min=1"` Enable []int `json:"enable" binding:"...
package token type TokenType string type Token struct { Type TokenType Literal string } const ( ILLEGAL TokenType = "ILLEGAL" EOF TokenType = "EOF" // Identifiers and literals. IDENT TokenType = "IDENT" INT TokenType = "INT" // Operators. ASSIGN TokenType = "=" PLUS TokenType = "+" // Delimi...
package pxc import ( appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" api "github.com/Percona-Lab/percona-xtradb-cluster-operator/pkg/apis/pxc/v1alpha1" "github.com/Percona-Lab/percona-xtradb-cluster-operator/pkg/pxc/app/statefulset" ) func (h *PXC) StatefulS...
package utils import ( "fmt" "gin-vue-admin/global" "github.com/gwpp/alidayu-go" "github.com/gwpp/alidayu-go/request" ) func SendShotMessage(phone, code string) error { client := alidayu.NewTopClient(global.GVA_CONFIG.Dayu.Appkey, global.GVA_CONFIG.Dayu.SecretKey) req := request.NewAlibabaAliqinFcSmsNumSendRequ...
// Copyright (c) 2019 Leonardo Faoro. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package cloudKMS makes it easy to interact with GCP's CloudKMS service. package cloudKMS import ( "context" "crypto/ecdsa" "crypto/sha256" "crypto/x...
package main import "testing" func TestP104(t *testing.T) { ans := 329468 v := solve() if v != ans { t.Errorf("p104: %v\tExpected: %v", v, ans) } }
package cache import ( "container/list" "time" ) type EvictType string const ( LRU EvictType = "lru" ARC = "arc" ) const ( DefaultSize = 100 ) // Cache is the interface for LRU/ARC cache. type Cache interface { // Set key-value pair with an expiration. Set(key, value interface{}, expire time.Durat...
// Copyright 2018 Kuei-chun Chen. All rights reserved. package util import ( "math/rand" "strconv" "strings" "time" "go.mongodb.org/mongo-driver/bson" ) var ( locations = []string{"US-NY", "US-GA", "US-IL", "US-TX", "US-CA", "US-WA"} ) // FavoritesSchema - type FavoritesSchema struct { ID string ...
package nominetuk var NominetUkObjects = []string{ "urn:ietf:params:xml:ns:domain-1.0", "urn:ietf:params:xml:ns:contact-1.0", "urn:ietf:params:xml:ns:host-1.0"} var NominetUkExtensions = []string{ "http://www.nominet.org.uk/epp/xml/contact-nom-ext-1.0", "http://www.nominet.org.uk/epp/xml/domain-nom-ext-1.2", "h...
package main import ( "bytes" "fmt" "github.com/stretchr/testify/assert" "io" "net/http" "net/http/httptest" "strings" "testing" ) func TestInvalidJsonReturnsUnmarshalError(t *testing.T) { t.Parallel() assert := assert.New(t) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Re...
package process import "fmt" // 用户的管理操作 // 比如对在线用户的管理 type ClientMgr struct { onlineUsers map[int]*UserProcessor } var ( clientMgr *ClientMgr ) // 完成初始化, 切片不初始化,不能使用 func init() { clientMgr = &ClientMgr{ onlineUsers: make(map[int]*UserProcessor, 1024), } } // 一个 ClientProcessor 实例,就对应一个登录的用户 func (p *ClientM...
package grpc import ( "context" "crypto/tls" "crypto/x509" "github.com/allabout/cloud-run-sdk/util" "google.golang.org/grpc" "google.golang.org/grpc/credentials" ) // addr 127.0.0.1:443 func NewTLSConn(ctx context.Context, addr string, opts ...grpc.DialOption) (*grpc.ClientConn, error) { systemRoots, err := x...
/* Copyright (c) 2017 GigaSpaces Technologies Ltd. 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 ...
/* Package gosnowth contains an IRONdb client library written in Go. Examples can be found at github.com/circonus-labs/gosnowth/tree/master/examples */ package gosnowth
package model type ErrorDetails struct { // Specific error code Code *int32 `json:"code,omitempty"` // Error group name Category string `json:"category,omitempty"` // Detailed error message Text string `json:"text,omitempty"` // Information if the encoding could potentially succeed when retrying. RetryHint Ret...
package main import ( "fmt" ) func variadic1(sl1 ...int) int { total := 0 for _, val := range sl1 { total += val } return total } func multiVariadic2(slice ...[][]int) int { // pass twoDimensional slice into a variadic function var total int = 0 for _, row := range slice { for i := 0; i < len(row); i++ { ...
package main import ( "fmt" "github.com/hajimehoshi/ebiten/v2" "github.com/hajimehoshi/ebiten/v2/ebitenutil" "go1/utils" _ "image/png" "log" "math/rand" ) type EdgeBehaviour int type GameWorld struct { name string screenWidth int screenHeight int maxAngle int minSprites ...
package main // TODO : CRUD handlers/server/RPA could be a standalone package // we could have a structure that only link him what to do with every action // Or not // Could be really handy to make improvements on all the RPAs // TODO : RPA => move handlers.go, routes.go, router.go, error.go, logger.go in RPA package ...
package main import ( "fmt" "os" "syscall" "github.com/mortawe/go-containerized/src/nsexec" "github.com/mortawe/go-containerized/src/nsnet" "github.com/mortawe/go-containerized/src/nsopts" ) func main() { opts := nsopts.NewOpts() if !opts.Validate() { opts.Help() os.Exit(1) } // invoke self exec to iso...
package router import ( "github.com/gorilla/mux" "net/http" quoteHandler "quote_wall/handler" ) func HandleRequest() { handler := mux.NewRouter(); handler.HandleFunc("/store", quoteHandler.SaveQuote()).Methods("POST") handler.HandleFunc("/store", quoteHandler.GetQuote()).Methods("GET") handler.PathPrefix("/")...
package unit type ActiveState int const ( ActiveStateError ActiveState = iota - 1 ActiveStateInactive ActiveStateActive ActiveStateDeactivating ActiveStateActivating ActiveStateReloading ActiveStateFailed ) var MapActiveState = map[string]ActiveState{ "inactive": ActiveStateInactive, "active": Act...
package connrt import ( "github.com/gookit/event" "github.com/prometheus/client_golang/prometheus" ) // Metrics var metricConnectionsTotal = prometheus.NewCounter(prometheus.CounterOpts{ Name: "conndetect_connections_total", Help: "Total number of connections detected", }) type MetricsCounter struct { Node } f...
/* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License...
/* Copyright 2016 Padduck, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software...
package repository import "github.com/octokit/go-octokit/octokit" type Repository interface { Nwo() string Issues(string, string) ([]octokit.Issue, error) PullRequests(string, string) ([]octokit.PullRequest, error) }
package p2 import ( "bufio" "fmt" "os" "regexp" "strconv" ) func isPolicySatisfied(min int32, max int32, c int32, pwd string) bool { prop1 := int32(pwd[min]) == c prop2 := int32(pwd[max]) == c return prop1 != prop2 } func driver() int { filename := fmt.Sprintf("p2.input") fp, fpe := os.Open(filename) if ...
package main import ( "context" "time" "github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter10/channels" ) func main() { ch := make(chan string) done := make(chan bool) ctx := context.Background() ctx, cancel := context.WithCancel(ctx) defer cancel() go channels.Printer(ctx, ch) go c...
package main import ( "encoding/json" "io/ioutil" "net/http" ) type responseJSON struct { Status bool `json:"status"` Message string `json:"message"` } type appConfig struct { Port string Host string } func sendSimpleResponse(w http.ResponseWriter, status bool, message string) { json.NewEncoder(w).Encod...
package handler import ( "context" "github.com/stretchr/testify/assert" "testing" ) func TestHandler_CheckInet(t *testing.T) { _, err := h.CheckInet(context.Background()) assert.NoError(t, err) } func TestHandler_CheckInetRound(t *testing.T) { err := h.CheckInetRound(context.Background()) assert.NoError(t, er...
// 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...
// Write a program that // - launches 10 goroutines // - each goroutine adds 10 numbers to a channel // - pull the numbers off the channel and print them package main import "fmt" func main() { c := make(chan int) const totalGoroutines = 2 const counter = 10 for i := 0; i < totalGoroutines; i++ { go write(i...
package env import ( "os" "path/filepath" "time" ) var ( WDA_USB_DRIVER = os.Getenv("WDA_USB_DRIVER") WDA_LOCAL_PORT = os.Getenv("WDA_LOCAL_PORT") WDA_LOCAL_MJPEG_PORT = os.Getenv("WDA_LOCAL_MJPEG_PORT") VEDEM_IMAGE_URL = os.Getenv("VEDEM_IMAGE_URL") VEDEM_IMAGE_AK = os.Getenv("VEDEM_IM...
package main import ( "os" _ "github.com/lib/pq" httplib "gitlab.com/semestr-6/projekt-grupowy/backend/go-libs/http-lib" "gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/attributes" "gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/categories" "gitlab.com/semestr-6/projekt-grupowy...
package latest // Version is the version of the providers config const Version = "v1beta1" // Config holds all the different providers and their configuration type Config struct { Version string `yaml:"version,omitempty"` Default string `yaml:"default,omitempty"` Providers []*Provider `yaml:"provider...
package models import ( "database/sql" "time" ) type AddressForm struct { IP string `json:"ip_address" gorm:"type:varchar(15);not null"` Mac string `json:"mac" gorm:"type:varchar(17);not null"` Hostname string `json:"hostname" gorm:"type:varchar(255)"` Reserved bool `jso...