text
stringlengths
11
4.05M
/* 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 有效字符串需满足: 左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。 示例 1: 输入: "()" 输出: true 示例 2: 输入: "()[]{}" 输出: true 示例 3: 输入: "(]" 输出: false 示例 4: 输入: "([)]" 输出: false 示例 5: 输入: "{[]}" 输出: true */ func isValid(s string) bool { //栈 if len(s)%2!=0 { //排除奇数个 ...
package Problem0354 import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) // tcs is testcase slice var tcs = []struct { envelopes [][]int ans int }{ { [][]int{ []int{46, 89}, []int{50, 53}, []int{52, 68}, []int{72, 45}, []int{77, 81}, }, 3, }, { [][]int{ []int{5, 4...
package sudoku import ( "fmt" "math/rand" ) type swordfishTechnique struct { *basicSolveTechnique } func (self *swordfishTechnique) humanLikelihood(step *SolveStep) float64 { //TODO: reason more carefully about how hard this technique is. return self.difficultyHelper(70.0) } func (self *swordfishTechnique) Des...
package actions import ( "errors" "github.com/barrydev/api-3h-shop/src/common/connect" "github.com/barrydev/api-3h-shop/src/factories" "github.com/barrydev/api-3h-shop/src/model" "strings" ) func UpdateShipping(shippingId int64, body *model.BodyShipping) (*model.Shipping, error) { queryString := "" var args []...
package Service import ( "EsAlertLog/utils" "github.com/olivere/elastic/v7" ) type ProcessClient struct { Pclient *elastic.Client ResChan chan utils.ResultInfo } //控制任务分发 func (pc *ProcessClient)Process(Rsi []utils.RuleInfo) { logger:=utils.CreateLogger() for _, Ri := range Rsi { //根据查询规则(TypeMatchPhase,TypeT...
package main import "fmt" func sum(numbers ...int) int { total := 0 for _, n := range numbers { total = total + n } return total } func main() { number := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} x := sum(number...) fmt.Println(x) }
package main import ( "fmt" ) // 79. 单词搜索 // 给定一个二维网格和一个单词,找出该单词是否存在于网格中。 // 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。 // 提示: // board 和 word 中只包含大写和小写英文字母。 // 1 <= board.length <= 200 // 1 <= board[i].length <= 200 // 1 <= word.length <= 10^3 // https://leetcode-cn.com/...
package common import ( "fmt" "net" "testing" ) func TestDns(t *testing.T) { ipRecords, _ := net.LookupIP("baidu.com") for _, ip := range ipRecords { fmt.Println(ip) } cname, _ := net.LookupCNAME("www.baidu.com") fmt.Println(cname) ptr, err := net.LookupAddr("114.114.114.114") if err != nil { fmt.Print...
package main import ( "fmt" "math/rand" "sort" "time" ) type traderBook struct { SellBook sellOrderBook BuyBook buyOrderBook } func (t *traderBook) filledOrder(o *order, q int) { if o.Sell { for i, v := range t.SellBook { if v.ID == o.ID { v.Quantity -= q if v.Quantity == 0 { t.SellBook = a...
package queries import ( "log" "github.com/jmoiron/sqlx" "gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/configuration" "gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/energy_resources/models" ) const GET_GUS_RESOURCE_BY_ID_SQL = ` SELECT * FROM energy_resources."GUSResource...
package services /* Scheduler is using for scheduling scanning component within K8S ecosystem. It takes cron expression to schedule tasks. */ import ( "fmt" "github.com/robfig/cron/v3" ) //https://pkg.go.dev/github.com/robfig/cron?utm_source=godoc type Scheduler struct { cronExpression string } func StartSchedu...
package api import ( "encoding/json" "net/http" "github.com/tlmiller/garage-door-controller/door" ) type TriggerResponse struct { StatusResponse err string `json:"error,omitempty"` } func doorTriggerHandler(res http.ResponseWriter, req *http.Request) { reqDoor := req.Context().Value(doorIdKey).(door.Door) tr...
package main import ( "github.com/aws/aws-lambda-go/events" "github.com/stretchr/testify/assert" "os" "testing" ) func init() { os.Setenv(SIGNING_KEY, "my signing key") } func TestHandleRequestValidToken(t *testing.T) { response, err := HandleRequest(nil, events.APIGatewayCustomAuthorizerRequest{ Authorizati...
package service import ( "context" "fmt" "sync/atomic" "github.com/go-ocf/cloud/grpc-gateway/pb" extCodes "github.com/go-ocf/cloud/grpc-gateway/pb/codes" "github.com/go-ocf/cloud/grpc-gateway/pb/errdetails" raEvents "github.com/go-ocf/cloud/resource-aggregate/cqrs/events" pbCQRS "github.com/go-ocf/cloud/resou...
package filters import ( "net" "github.com/jlorgal/odor/odor" ) // Malware filter. type Malware struct { blacklist []*net.IPNet } // NewMalware creates a Malware filter func NewMalware(config *odor.Config) (*Malware, error) { blacklist, err := odor.GetBlacklist("malware", config) return &Malware{blacklist: bla...
package model type Employee struct { UID int Username string Passwordjwt string PnameID int Fname string Lname string GroupUserID int HospitalDepartmentID int PositoinID int Status string }
// Copyright 2016 Google 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...
package check import ( "context" "fmt" "strings" ctxutil "github.com/mszostok/codeowners-validator/internal/context" "github.com/mszostok/codeowners-validator/pkg/codeowners" ) // DuplicatedPattern validates if CODEOWNERS file does not contain // the duplicated lines with the same file pattern. type DuplicatedP...
package randata import ( "math/rand" "strings" "time" "github.com/tahkapaa/test_stuff/randata/data" ) var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") var words = stringToArray(data.WordsStr) var countries = stringToArray(data.CountryStr) var initialized = false // Initialize ope...
package application import ( "fmt" "os" ) type systemInteractions interface { Printf(str string, args ...interface{}) Exit(exitCode int) } type realSystemInteractions struct{} func (r realSystemInteractions) Exit(exitCode int) { os.Exit(exitCode) } func (r realSystemInteractions) Printf(str string, args ...in...
package day6 import ( ds "aoc/datastructures" "aoc/util" ) func findDistinctEnd(input string, length int) int { for i := 0; i < len(input)-length-1; i++ { sub := input[i : i+length] set := ds.NewSet(util.ConvertToRunes(sub)) if len(set) == length { return i + length } } return -1 } func Part1(input s...
package jira import ( "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/httptest" "net/url" "testing" ) func TestCreateMapping(t *testing.T) { testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { t.Fatalf("wanted POST but found %s\n...
package v1alpha1 import ( "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type S3List struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata"` Items []S3 `json:"items"` } // +k8s:deepcopy-gen:interfaces=...
package data import ( "github.com/Kamva/mgm/v3" ) // ReviewPhrase is the model for the database ORM type ReviewPhrase struct { mgm.DefaultModel `bson:",inline"` Phrase string `json:"phrase" bson:"phrase"` Frequency int `json:"frequency" bson:"frequency"` } // NewReviewPhrase is a convenience ...
// EXERCISE: Parse Arg Numbers // // Use strconv.ParseInt function to get int8, int16, and // int32, and int64 values from command-line. // // HINT // The third argument to ParseInt function represents // the bitsize. // // So, giving it 8 returns an int8 convertable value; // whereas 16 returns an int16 converta...
package channelserver import ( "database/sql" "encoding/binary" "github.com/Andoryuuta/Erupe/server/channelserver/compression/nullcomp" "go.uber.org/zap" ) const ( CharacterSaveRPPointer = 0x22D16 ) type CharacterSaveData struct { CharID uint32 RP uint16 IsNewCharacter bool // Use prov...
package main import ( "fmt" "strconv" "strings" "github.com/thoas/go-funk" ) type program struct { memory map[int]int instructionSets []instructionSet } func (p *program) run(version int) { for _, instructionSet := range p.instructionSets { for _, instruction := range instructionSet.instructions {...
package parser import ( "github.com/PuerkitoBio/goquery" "fmt" "util" "spider/entity" ) type IndexPaser struct { List []entity.JobInfo } func (this *IndexPaser) SelectorService(i int, selection *goquery.Selection) { if selection.HasClass("warn") || selection.HasClass("space") || selection.HasClass("more") { ...
package sort import ( "fmt" "testing" ) func TestMergeSort(t *testing.T) { arr := []int{5, 7, 2, 5, 6, 8, 4, 13, 5, 6, 7} // 子序列 = len(当前序列) / 2 // {5, 7, 2, 5, 6} {8, 4, 13, 5, 6, 7} // {5, 7} {2, 5, 6} {8, 4, 13} {5, 6, 7} // {5} {7} {2} {5, 6} {8} {4, 13} {5} {6, 7} // 归...
package archive import ( "bufio" "compress/gzip" "crypto/rand" "encoding/hex" "os" "path/filepath" "testing" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" ) func tempFile(dir, prefix, suffix string) (*os.File, error) { if dir == "" { dir = os.TempDir() } else { err := os.MkdirA...
package server import ( "context" "fmt" "os" "path/filepath" "strings" "sync" "emperror.dev/errors" "github.com/apex/log" "github.com/creasty/defaults" "github.com/pterodactyl/wings/api" "github.com/pterodactyl/wings/config" "github.com/pterodactyl/wings/environment" "github.com/pterodactyl/wings/environ...
package v1 // Handle is handler for invoker service type Handle struct { }
package security type Permit []string type Permits map[string]Permit func (p Permits) Allowed(user string, db string) bool { for _, allowedUser := range p[db] { if user == allowedUser { return true } } return false }
package Model type Employee struct { Account Credit float64 } func (employee *Employee) AddCredits(credit float64) { employee.Credit += credit } func (employee *Employee) RemoveCredits(credit float64) { employee.Credit -= credit } func (employee *Employee) CheckCredits() float64 { return employee.Credit } fu...
package provisionerbeta import ( "bytes" "crypto/ecdsa" "crypto/ed25519" "crypto/rsa" "crypto/x509" "encoding/json" "encoding/pem" "fmt" "io/ioutil" "net/url" "github.com/pkg/errors" "github.com/smallstep/certificates/authority/provisioner" "github.com/smallstep/cli/crypto/pemutil" "github.com/smallstep...
/* * @lc app=leetcode.cn id=844 lang=golang * * [844] 比较含退格的字符串 */ // @lc code=start package main import "fmt" import "strings" func backspaceCompare(S string, T string) bool { a := getResult(S) b := getResult(T) return a == b } func getResult(s string) string { stack1 := []byte{} for i := len(s) -1 ; i >=...
// Package timeutil contains types and utilities for dealing with time and // duration values. package timeutil import ( "time" "github.com/AdguardTeam/golibs/errors" ) // Day is the duration of one day. const Day time.Duration = 24 * time.Hour // Duration is a wrapper for time.Duration providing functionality fo...
package main import ( _ "io/ioutil" "os" "github.com/FBreuer2/librsync-go" "github.com/sirupsen/logrus" "github.com/urfave/cli" ) func CommandSignature(c *cli.Context) { if len(c.Args()) > 2 { logrus.Warnf("%d additional arguments passed are ignored", len(c.Args())-2) } if c.Args().Get(0) == "" { logrus...
package main import "fmt" func main() { operatorBasic() //1 } func operatorBasic() { //#1 var value int = (((2+6)%3)*4 - 2) / 3 //Membuat variabel value dengan tipe data int var isEqual = (value == 2) //jika value sama dengan 2 fmt.Printf("nilai %d (%t) \n", value, isEqual) //Menampilkan nilai value ...
package type_aliases type t1 struct { } type T2=t1
package models import ( "fmt" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "reflect" ) var _ = Describe("Document", func() { var ( data = map[string]interface{}{ "value": "hi", } data_updated = map[string]interface{}{ "value": "Hi", } ) It("UpdateDocument", func() { for i, _ := range m...
package dht import ( "fmt" "github.com/libp2p/go-libp2p/core/event" "github.com/libp2p/go-libp2p/core/network" "github.com/libp2p/go-libp2p/core/peer" "github.com/libp2p/go-libp2p/p2p/host/eventbus" ) func (dht *IpfsDHT) startNetworkSubscriber() error { bufSize := eventbus.BufSize(256) evts := []interface{}{...
package main import ( "errors" "log" "math" "strconv" "strings" "time" ) func NewEntity(location [2]float64, entityType int, g *game) *entity { e := &entity{} e.Id = Uuid() return e } type entity struct { Id string Game *game Location [2]float64 Velocity [2]float64 Acceleratio...
package user import ( "context" "database/sql" "github.com/hardstylez72/bblog/ad/pkg/util" "github.com/jmoiron/sqlx" ) var ErrEntityAlreadyExists = util.ErrEntityAlreadyExists var ErrEntityNotFound = util.ErrEntityNotFound type repository struct { conn *sqlx.DB } func NewRepository(conn *sqlx.DB) *repository {...
package cloud // Runtime represents an environment runtime type Runtime struct { ID string `json:"id" yaml:"id" toml:"id"` Name string `json:"name" yaml:"name" toml:"name"` Description string `json:"description" yaml:"description" toml:"description"` EnvName string `json:"env" yaml:"env" toml:"...
package functions import ( "sort" ) // SortUsing works similar to sort.Slice. However, unlike sort.Slice the // slice returned will be reallocated as to not modify the input slice. func (ss SliceType) SortUsing(less func(a, b ElementType) bool) SliceType { // Avoid the allocation. If there is one element or less it...
package aesacc import ( "crypto/aes" "crypto/cmac" //"crypto/cmac" "crypto/cipher" //"encoding/hex" //"fmt" ) func GetAesECB(txt []byte, key []byte) []byte { //txt, _ := hex.DecodeString("4800F21500B300000204414000000000") //key, _ := hex.DecodeString("A7D8942966B2B7BF6109829AEE3EEAA9") //enc, _ := hex.Decod...
package user import ( "context" ) type ( repository interface { Get(ctx context.Context, id string) (*User, error) Create(ctx context.Context, user *User) error Update(ctx context.Context, user *User) error } Service struct { repo repository } ) func NewService(repo repository) *Service { return &Serv...
package restore_ip_address import "strconv" func restoreIpAddresses(s string) []string { result := []string{} if len(s) == 0 { return result } for size := 1; size <= 3; size++ { restoreIpAddress(&result, s, "", 1, 0, size) } return result } func restoreIpAddress(result *[]string, s, path string, step, begi...
/* * @lc app=leetcode.cn id=45 lang=golang * * [45] 跳跃游戏 II */ package solution // @lc code=start func jump(nums []int) int { max := func(x, y int) int { if x > y { return x } return y } step, pos, end, length := 0, 0, 0, len(nums) for i := 0; i < length-1; i++ { pos = max(pos, i+nums[i]) if pos...
package main import ( "crypto/rand" "fmt" "os" "github.com/drand/drand/cmd/relay-gossip/client" "github.com/drand/drand/cmd/relay-gossip/lp2p" "github.com/drand/drand/cmd/relay-gossip/node" dlog "github.com/drand/drand/log" "github.com/drand/drand/protobuf/drand" "github.com/ipfs/go-datastore" logging "gith...
package main import ( _ "github.com/go-sql-driver/mysql" _ "github.com/lib/pq" "log" "github.com/jinzhu/gorm" "fmt" "net/http" "html/template" "github.com/gorilla/mux" "strings" ) type Car struct{ Car string `json:car,omitempty` Urlsearch string } type Hatchback struct { HatchID uint `gorm:"prim...
// Package dirdepth is a tool for understanding the relative depths of directories. package dirdepth import ( "path/filepath" "sort" "strings" ) // ComparableDirs takes a current working directory and directories relative to the working directory type ComparableDirs struct { WorkingDir string ComparableDirs ...
// ˅ package main // ˄ type LimitedSupporter struct { // ˅ // ˄ Supporter limitId int // ˅ // ˄ } func NewLimitedSupporter(name string, limitId int) *LimitedSupporter { // ˅ return &LimitedSupporter{Supporter{name: name}, limitId} // ˄ } // Troubles with an ID below the limit are handled. func (self *...
package main import ( "fmt" "log" "os" "text/template" ) const ( bottlerocketUserData = ` [settings.kubernetes] api-server = "{{.Cluster.Endpoint}}" {{if .Cluster.CABundle}}{{if len .Cluster.CABundle}}cluster-certificate = "{{.Cluster.CABundle}}"{{end}}{{end}} cluster-name = "{{if .Cluster.Name}}{{.Cluster.Name}...
package main // #cgo LDFLAGS: -lm // #include <math.h> // // double ps(double a, double b) { // double result = pow(a, b); // result = sqrt(result); // return result; // } import "C" import "fmt" func Pow(b, e float64) float64 { return float64(C.pow(C.double(b), C.double(e))) } func Sqrt(b float64) float64 { re...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //678. Valid Parenthesis String //Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this st...
package main import ( "fmt" "regexp" ) // Package regexp adalah utilitas di Go-Lang untuk melakukan pencarian regular expression // Regular expressino di Go-Lang menggunakan library C yg dibuat Google bernama RE2 // https://github.com/google/re2/wiki/Syntax func main() { regex := regexp.MustCompile("e([a-z])o") ...
// Copyright 2021 Clivern. All rights reserved. // Use of this source code is governed by the MIT // license that can be found in the LICENSE file. package pkg import ( "bytes" "fmt" "io/ioutil" "os" "path/filepath" "github.com/drone/envsubst" "github.com/spf13/viper" ) // GetBaseDir returns the project base...
// Copyright 2020 The Operator-SDK 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 ...
package main import ( "encoding/json" "log" "net/http" ) type UserInfo struct { Name string `json:"name"` Age int `json:"age"` } func main() { http.HandleFunc("/api/query", func(w http.ResponseWriter, r *http.Request) { u := &UserInfo{ Name: "syhlion", Age: 18, } b, err := json.Marshal(u) i...
// Copyright 2017 Google 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...
package main import ( "errors" "fmt" "os" ) func doubleEven(i int) (int, error) { if i%2 == 0 { return 0, errors.New("処理対象は偶数のみです") } return i * 2, nil } func doubleEven2(i int) (int, error) { if i%2 != 0 { return 0, fmt.Errorf("%dは偶数ではありません", i) } return i * 2, nil } func main() { i := 19 double, e...
package notifications import ( "context" "time" "github.com/go-kit/kit/endpoint" "github.com/go-kit/kit/log" "github.com/go-kit/kit/ratelimit" "github.com/go-kit/kit/transport/grpc" "golang.org/x/time/rate" pbs "github.com/inhumanLightBackend/notifications/pb" grpcg "google.golang.org/grpc" ) type grpcTran...
package main import ( "os" "path/filepath" ) func check(e error) { if e != nil { panic(e) } } func createDir(path string){ if _, err := os.Stat(path); os.IsNotExist(err) { os.Mkdir(path,0777) } } func writeToFile(path string,content string) { f,err := os.Create(path) check(err) f.WriteString(content) ...
package arrays import ( "fmt" ) func Run(){ var numbers [3]int numbers[0] = 1 numbers[1] = 2 numbers[2] = 3 fmt.Println(numbers) strings := [4]string{"a","b","c","d"} fmt.Printf("%s",strings[1]) }
package structs import "encoding/xml" type CreditClaimRejectRequest struct { XMLName xml.Name `xml:"CreditClaimRejectRequest"` Text string `xml:",chardata"` Xsd string `xml:"xsd,attr"` Xsi string `xml:"xsi,attr"` BranchCode string `xml:"BranchCode"` Requester ...
package models import ( "database/sql" "fmt" "github.com/lempiy/echo_api/types/db" "os" _ "github.com/lib/pq" ) var Database db.Database var err error func init() { info := os.Getenv("DATABASE_URL") if info == "" { info = fmt.Sprintf("user=%s password=%s dbname=%s host=postgres port=5432 sslmode=disable", ...
package Problem0486 // PredictTheWinner 在 play1 能赢的时候,返回 true func PredictTheWinner(nums []int) bool { n := len(nums) // dp[i][j] 表示 nums[i:j+1] 中 play1 比 play2 多的得分 // dp[0][n-1] >=0 表示 play1 获胜 dp := make([][]int, n) for i := range dp { dp[i] = make([]int, n) // 只有 nums[i] 时,play1 比 play2 多 nums[i] 分 // ...
//go:build windows // +build windows /* Copyright © 2021 SUSE 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 ...
/* Command twotone converts black/white PNGs to other twotone combinations. Usage: export TAN=EAE0CC export BROWN=2D232A twotone -bg=$TAN -fg=$BROWN -in=fixtures/test.png -out=fixtures/out.png */ package main import ( "flag" "image" "image/color" "image/png" "log" "os" "strconv" ) var ( dropTransparency = f...
package main import ( "github.com/francescoforesti/appointments/be/logging" "github.com/francescoforesti/appointments/be/model" "github.com/francescoforesti/appointments/be/repository" routers "github.com/francescoforesti/appointments/be/rest" service "github.com/francescoforesti/appointments/be/service" "github...
package Framework_Definitions import ( "strings" ) // ------------------------------------------- Event Definitions ------------------------------------------- // // The use of EventType alias and the constants is like an enumerated type type EventType int // These are the EventTypes necessary in every application...
package main import ( "fmt" "./gameobjects" ) func main() { item2 := gameobjects.ItemsCacheMap[1] vasyan1, success := gameobjects.GetAccountCharacter("testTwo", "testPass") if success == true { item1 := gameobjects.NewItem(1) vasyan1.CharInventory["head"] = item1 vasyan1.CharInventory["Amul"] = item2 fm...
package main import ( "fmt" "runtime" "github.com/mndrix/tap-go" "github.com/opencontainers/runtime-tools/cgroups" "github.com/opencontainers/runtime-tools/validation/util" ) func main() { if "linux" != runtime.GOOS { util.Fatal(fmt.Errorf("linux-specific cgroup test")) } t := tap.New() t.Header(0) cas...
package main import ( "fmt" "os" "os/exec" "text/template" ) const code = ` package main import ( "fmt" ) type Name struct { first string last string full string } func (n *Name) FullName() string { n.full = n.first + " " + n.last return n.full } func Greet(name string) { fmt.Print...
/* Copyright 2023 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, softw...
package main import ( "bytes" "fmt" "io" "log" "net/http" "sync" "time" ) var wg1 sync.WaitGroup func init() { log.SetFlags(log.Lshortfile) } func main() { wg1.Add(1) go server1() time.Sleep(time.Second * 3) //客户端延时启动 go client1() wg1.Wait() } func server1() { defer wg1.Done() http.HandleFunc("/...
package env import ( "os" ) //GetVariable returns .env variable value func GetVariable(key string) string { return os.Getenv(key) }
package meta import ( "encoding/json" "fmt" ) // ErrAuthentication represents an error asserting an principal's identity. type ErrAuthentication struct { // Reason is a natural language explanation for why authentication failed. Reason string `json:"reason,omitempty"` } func (e *ErrAuthentication) Error() string...
package httprouter import ( "net/http" "github.com/wlMalk/gapi/middleware" "github.com/wlMalk/gapi/operation" "github.com/wlMalk/gapi/request" "github.com/wlMalk/gapi/response" "github.com/wlMalk/gapi/wrapper" "github.com/julienschmidt/httprouter" ) type Wrapper struct { router *httprouter.Router } func Wr...
package types import ( "context" "google.golang.org/grpc" plugin "github.com/hashicorp/go-plugin" sdk "github.com/cosmos/cosmos-sdk/types" codec "github.com/cosmos/cosmos-sdk/codec/types" ) type GRPCClient struct { broker *plugin.GRPCBroker client ModuleClient } func (m *GRPCClient) Handler(stateServer State...
package main import ( "fmt" ) // Log Log func Log(args ...interface{}) { fmt.Println(args...) } // SLog SLog func SLog(args ...interface{}) { fmt.Printf("%+v\n", args) }
package main import ( "gotcpserver" ) func main() { srv := gotcpserver.NewServer("127.0.0.1:9012") srv.Start() }
package cli import ( "bytes" "fmt" ) type HelpFunc func(map[string]CommandFactory) string func BasicHelpFunc(app string) HelpFunc { return func(factories map[string]CommandFactory) string { var buffer bytes.Buffer buffer.WriteString(fmt.Sprintf("usage: %s [--version] [--help] <command> [<args>]", app)) if...
package timeline import ( "github.com/gorilla/mux" "github.com/metalblueberry/dashboard/app" "net/http" ) type Timeline struct { InternalName string AutorizedUsers map[string]bool Query string updating bool } func LoadFromData(rawdata interface{}) Timeline { data := rawdata.(map[string]inter...
package controllers import ( "github.com/astaxie/beego/context" "io/ioutil" ) type helpController struct{ } var HelpCtl = &helpController{} func (this helpController)Page(ctx *context.Context){ hz,_:=ioutil.ReadFile("./views/help/auth_help.tpl") ctx.ResponseWriter.Write(hz) }
package instancestoresql import ( "context" "fmt" "time" "github.com/direktiv/direktiv/pkg/refactor/instancestore" "github.com/google/uuid" "go.uber.org/zap" "gorm.io/gorm" ) const ( table = "instances_v2" fieldID = "id" fieldNamespaceID = "namespace_id" fieldRevisionID = ...
package middlware import ( "fmt" "github.com/sirupsen/logrus" "github.com/valyala/fasthttp" ) func LoggingMiddleware(next fasthttp.RequestHandler) fasthttp.RequestHandler { return func(ctx *fasthttp.RequestCtx) { msg := fmt.Sprintf("URL: %s, METHOD: %s, REMOTE_ADDR%s", ctx.URI(), ctx.Method(), ctx.RemoteAddr...
package register import ( "fmt" "math/rand" "time" "github.com/samuel/go-zookeeper/zk" ) var zkConn *zk.Conn // Prepare connect to zk func Prepare() { conn, _, err := zk.Connect([]string{ZOOKSERVER}, time.Second) if err == nil { zkConn = conn } else { panic(err) } } // RandomSelectDataServer random pol...
package split import "strings" func SplitMultiSep(s string, sep []string) []string { var ret []string ret = strings.Split(s, sep[0]) if len(sep) > 1 { ret2 := []string{} for _, r := range ret { ret2 = append(ret2, SplitMultiSep(r, sep[1:])...) } ret = ret2 } return ret }
package geonames import ( "encoding/csv" "errors" "io" "os" "strconv" "github.com/mmcloughlin/geohash" ) type Location struct { City string Country string } type Lookup struct { root node } func New() *Lookup { return new(Lookup) } type node struct { key string location *Location children []*...
package account import ( "github.com/urfave/cli/v2" "github.com/alphatr/acme-lego/common" "github.com/alphatr/acme-lego/common/bootstrap" "github.com/alphatr/acme-lego/common/config" "github.com/alphatr/acme-lego/common/errors" "github.com/alphatr/acme-lego/model/account" "github.com/alphatr/acme-lego/model/cl...
package jsonproto import ( "fmt" "io" ) // Helper handlers // Error outputs a specified error // The error message should be plain text func Error(w io.Writer, error string) { fmt.Fprintln(w, error) } // NotFound replies to the Message with an error message indicating route // not able to be located /* func NotF...
package PDU import ( "github.com/andrewz1/gosmpp/Data" "github.com/andrewz1/gosmpp/Exception" "github.com/andrewz1/gosmpp/PDU/Common" "github.com/andrewz1/gosmpp/Utils" ) type AddressRange struct { Common.ByteData Ton byte Npi byte AddressRange string } func NewAddressRange() *AddressRange ...
package single import ( "os" "github.com/Nv7-Github/Nv7Haven/db" "github.com/gofiber/fiber/v2" ) func (s *Single) routing(app *fiber.App) { app.Post("/single_upload", s.upload) app.Get("/single_like/:id/:uid", s.like) app.Get("/single_list/:kind/:query", s.list) app.Get("/single_list/:kind", s.list) app.Get(...
package main import ( "fmt" "os" "os/signal" "syscall" "time" "github.com/Andoryuuta/Erupe/config" "github.com/Andoryuuta/Erupe/server/channelserver" "github.com/Andoryuuta/Erupe/server/entranceserver" "github.com/Andoryuuta/Erupe/server/launcherserver" "github.com/Andoryuuta/Erupe/server/signserver" "gith...
package env import ( "fmt" "testing" ) func TestEnv(t *testing.T) { a := GetAppID() fmt.Println(a) e := GetEnv() fmt.Println(e) h := GetHostname() fmt.Println(h) }
package producer_service import ( "github.com/gin-gonic/gin" "github.com/yjagdale/siem-data-producer/config/constant" "github.com/yjagdale/siem-data-producer/models/producer_model" "github.com/yjagdale/siem-data-producer/utils/response" ) func Produce(producerEntity producer_model.ProducerEntity, executionMode st...
package storage import "github.com/wgyuuu/storage_key" // 复合主键 type ComplexStorage interface { Storage GetKeyList(key storage_key.Key) ([]storage_key.Key, error) SetKeyList(key storage_key.Key, keyList []storage_key.Key) error } type ComplexStorageProxy struct { StorageProxy } func NewComplexStorageProxy(prefer...