text
stringlengths
11
4.05M
package main_test import ( "bytes" "io/ioutil" "os" "os/exec" "testing" "time" ) func TestDevOP(t *testing.T) { os.Remove("./testData/testData") exec.Command("go", "build").Run() os.Chdir("./testData") DEVOP := exec.Command("../devop") DEVOP.Stderr = os.Stderr DEVOP.Stdout = os.Stdout DEVOP.Start() ...
package main import ( "github.com/gin-gonic/gin" "github.com/jasondavindev/golang-todo-app/src/common" "github.com/jasondavindev/golang-todo-app/src/configs" "github.com/jasondavindev/golang-todo-app/src/task" "github.com/jasondavindev/golang-todo-app/src/user" _ "github.com/jinzhu/gorm/dialects/postgres" ) fun...
package main import ( "baumfalk/reversi/game" "bufio" "fmt" "os" "strconv" ) func getNumberFromIO(scanner *bufio.Scanner, min int, max int) int { scanner.Scan() text := scanner.Text() num, error := strconv.Atoi(text) for error != nil { fmt.Println(error) scanner.Scan() text = scanner.Text() num, erro...
package mainWindow import ( "github.com/myProj/scaner/new/include/appStruct" "github.com/therecipe/qt/widgets" ) func newInfoAreaLayout(component *appStruct.GuiComponent)*widgets.QVBoxLayout{ infoLayout := widgets.NewQVBoxLayout() infoTab := widgets.NewQTabWidget(nil) infoTab.AddTab(component.FileTree, "Найд...
/* Inspired by a tweet by Nathan W. Pyle There is, now, a standard method of converting your boring, normal human name into a mysterious, ethereal Ghost Name™️. Ably described by Mr Pyle... Use your first name: a - add “t” after it e - add “boo” after it h - becomes “s” n - add “oo” after it r - add “eee” after...
package ofdru import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func TestKkt(t *testing.T) { ts := httptest.NewServer( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/api/integration/v1/inn/INN1/kkts" { w.Header().Add("Content-Ty...
package main type ConfigureOptions struct { Values map[string]ConfigureOptionValue Bools map[string]ConfigureOptionBool } type ConfigureOptionValue struct { Name string Desc string Value *string } type ConfigureOptionBool struct { Name string Desc string Enabled *bool } func makeArgsBool() map[stri...
package parser import ( "errors" "fmt" "strconv" "strings" "unicode/utf8" "github.com/grubby/grubby/ast" ) var DebugStatements = []string{} const eof = -1 type token struct { typ tokenType value string } type tokenType int const ( tokenTypeError tokenType = iota tokenTypeEOF tokenTypeInteger tokenT...
package bitty /* Copyright 2020 IBM 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 2020 MongoDB 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...
package config import ( "fmt" "io/ioutil" ) func GenerateConfigFile(path string) error { fmt.Println("Generate configuration file at ", path) conf := []byte(ConfigBase) return ioutil.WriteFile(path, conf, 0644) } const ConfigBase = ` # Environments define different ways to interact with Trakit environments: ...
package graphql // This file will be automatically regenerated based on the schema, any resolver implementations // will be copied through when generating and any unknown code will be moved to the end. import ( "context" "github.com/GlitchyGlitch/typinger/auth" "github.com/GlitchyGlitch/typinger/dataloaders" "gi...
// 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 ( "fmt" "log" "path/filepath" ) type PictureSet struct { id int original string set []string } func getPictureSet(id int) (*PictureSet, error) { original, err := Db.Cmd("lindex", id, "0").Str() if err != nil { return nil, fmt.Errorf("Failed to find a PictureSet with id=%d", i...
package utils import ( "bytes" "crypto/md5" "crypto/rand" "encoding/base64" "fmt" "io" "reflect" "regexp" "strconv" "strings" "unsafe" ) //生成随机字符串 func RandString() string { b := make([]byte, 32) if _, err := io.ReadFull(rand.Reader, b); err != nil { return "" } return base64.URLEncoding.EncodeToStri...
package util import "golang.org/x/crypto/bcrypt" func PasswordBCrypto(password string) string { cryptPwd, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) return string(cryptPwd) } func VerifyPassword(hashPwd string, password string) bool { err := bcrypt.CompareHashAndPassword([]byte(hashPwd...
package main import ( "flag" "fmt" "os" ) func main() { // load file with default filepath // construct graph from file // take input then evaluate graph filepath := flag.String("file", "routes.csv", "a string") flag.Parse() file, err := os.Open(*filepath) if err != nil { fmt.Printf("cannot open file %v...
package main import ( "encoding/json" "fmt" "io/ioutil" pb "github.com/brotherlogic/discovery/proto" ) type Entry struct { Targets []string `json:"targets"` Labels Label `json:"labels"` } type Label struct { Job string `json:"job"` } // This writes out the file for prometheus func (s *Server) writeFile(...
package cmd import ( "fmt" "log" "os" "text/tabwriter" "github.com/HakShak/sanemame/db" "github.com/boltdb/bolt" "github.com/spf13/cobra" "github.com/spf13/viper" ) // nplayersCmd represents the nplayers command var nplayersCmd = &cobra.Command{ Use: "nplayers", Short: "A brief description of your comman...
package camt import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document03400104 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:camt.034.001.04 Document"` Message *DuplicateV04 `xml:"Dplct"` } func (d *Document03400104) AddMessage() *DuplicateV04 { d.Mes...
package node import ( "encoding/json" "go-neural_network/lib" ) type Source struct { path string entity struct { Data []DataEntity `json:"data"` } } type DataEntity struct { Properties map[string]float64 `json:"properties"` Result float64 `json:"result"` } func (source *Source) initDataSou...
// 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 openid import ( "crypto/rsa" "fmt" "net/http" "github.com/dgrijalva/jwt-go" ) const issuerClaimName = "iss" const audiencesClaimName = "aud" const subjectClaimName = "sub" const keyIDJwtHeaderName = "kid" type jwtTokenValidator interface { validate(r *http.Request, t string) (jt *jwt.Token, err error) ...
package main; import ( "com/eriq-augustine/mediaserver/auth" "com/eriq-augustine/mediaserver/server" ); func main() { server.LoadConfig(); // It is safe to load users after the configs have been loaded. auth.LoadUsers(); server.StartServer(); }
package git /* #include <git2.h> extern git_annotated_commit** _go_git_make_merge_head_array(size_t len); extern void _go_git_annotated_commit_array_set(git_annotated_commit** array, git_annotated_commit* ptr, size_t n); extern git_annotated_commit* _go_git_annotated_commit_array_get(git_annotated_commit** array, siz...
// Copyright (c) 2020 Zededa, Inc. // SPDX-License-Identifier: Apache-2.0 package volumemgr import ( "fmt" "strings" "github.com/containerd/containerd/mount" "github.com/lf-edge/eve/pkg/pillar/diskmetrics" "github.com/lf-edge/eve/pkg/pillar/types" "github.com/lf-edge/eve/pkg/pillar/vault" "github.com/lf-edge/...
package main import ( "container/heap" "fmt" "sort" ) func main() { fmt.Println(totalCost2([]int{ 17, 12, 10, 2, 7, 2, 11, 20, 8, }, 3, 4)) fmt.Println(totalCost2([]int{ 31, 25, 72, 79, 74, 65, 84, 91, 18, 59, 27, 9, 81, 33, 17, 58, }, 11, 2)) } type miniHeap struct { sort.IntSlice } func (h *miniHeap)...
package translation import ( "log" "regexp" "strings" ) // GopherTranslator GopherTranslator can translate type GopherTranslator interface { TranslateEnglishWordToGopher(word string) string TranslateEnglishSentenceToGopher(sentence string) string } // NewGopherTranslator NewGopherTranslator is a new trnslator i...
// Package autocert implements automatic management of TLS certificates. package autocert import ( "context" "crypto/tls" "encoding/base64" "errors" "fmt" "net" "net/http" "sort" "strings" "sync" "sync/atomic" "time" "github.com/caddyserver/certmagic" "github.com/mholt/acmez/acme" "github.com/rs/zerolo...
package meminfo type MemInfo struct { Available uint64 Free uint64 HaveAvailable bool Total uint64 } func GetMemInfo() (*MemInfo, error) { return getMemInfo() }
/* Given a list of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are 7 socks with colors [1, 2, 1, 2, 1, 3, 2]. There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is...
package main import "fmt" func main() { fmt.Println(twoSum([]int{2, 7, 11, 15}, 9)) fmt.Println(twoSum([]int{3, 2, 4}, 6)) fmt.Println(twoSum([]int{3, 3}, 6)) } func twoSum(nums []int, target int) []int { m := make(map[int]int) for i, v := range nums { if j, ok := m[v]; ok { return []int{j, i} } m[t...
package database import ( "log" "os" "posthis/entity" "time" "gorm.io/driver/mysql" "gorm.io/gorm" ) type User = entity.User type Post = entity.Post type Media = entity.Media type Like = entity.Like type Reply = entity.Reply type Repost = entity.Repost type Follow = entity.Follow var DB *gorm.DB func InitDB(...
package inspect import ( "fmt" "os" "os/exec" "sort" "github.com/quilt/quilt/stitch" "github.com/quilt/quilt/util" ) func getSlug(configPath string) (string, error) { var slug string for i, ch := range configPath { if ch == '.' { slug = configPath[:i] break } } if len(slug) == 0 { return "", fm...
package split_string import ( "reflect" "testing" ) func TestSplit(t *testing.T) { got := Split("abcbc", "b") want := []string{"a", "c", "c"} if !reflect.DeepEqual(got, want) { t.Errorf("want:%v but got :%v\n", want, got) } } func Test2Split(t *testing.T) { got := Split("a:b:c", ":") want := []string{"a", ...
package nutanix import ( "github.com/openshift/installer/pkg/terraform" "github.com/openshift/installer/pkg/terraform/providers" "github.com/openshift/installer/pkg/terraform/stages" ) // PlatformStages are the stages to run to provision the infrastructure in Nutanix. var PlatformStages = []terraform.Stage{ stage...
package ebby import ( "github.com/conest/ebby/game" ) // Init : 初始化 func defaultInitialFunc(c *game.Game) { c.GameData().Sys.Logger.Info("[game] Started") } // BeforeExit : 关闭前行为(保存数据等) func defaultBeforeExitFunc(c *game.Game) { c.GameData().Sys.Logger.Info("[game] Ternimated") } // emptyFunc : 空函数 func emptyFun...
// Copyright 2013 http://gumuz.nl/. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package treap/stack.go implements a simple stack datastructure, used by the Iterator. Items are a simple linked list and can have any value. The Stack has...
package proletarian import ( "bytes" "strings" "reflect" "fmt" "bufio" "time" "log" "os" "os/exec" "gopkg.in/yaml.v3" k8sml "KubeArch/kubearch/k8sml" ansible "KubeArch/kubearch/proletarian/ansible" ) type ProductionPlan struct { ProductionOrder []k8sml.Infrastructure Products map[string][]k8sml.K8sML...
package query import ( "database/sql" "errors" "github.com/ekkapob/buybits/model" ) func UserExist(db *sql.DB, username string) bool { var id int err := db.QueryRow("SELECT id FROM users WHERE username = $1", username).Scan(&id) return err != sql.ErrNoRows } func AddUser(db *sql.DB, user model.User) error { s...
package git import ( "io/ioutil" "testing" ) func checkout(t *testing.T, repo *Repository, commit *Commit) { tree, err := commit.Tree() if err != nil { t.Fatal(err) } err = repo.CheckoutTree(tree, &CheckoutOptions{Strategy: CheckoutSafe}) if err != nil { t.Fatal(err) } err = repo.SetHeadDetached(commit...
package actor import ( "testing" "time" "github.com/stretchr/testify/assert" ) func TestOneForOneStrategy_requestRestartPermission(t *testing.T) { cases := []struct { n string expectedResult bool expectedCount int s oneForOne rs RestartStatistics }{ { n: "no...
package application import ( "context" "fmt" "reflect" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/crossplane/crossplane-runtime/pkg/test" "github.com/ghodss/yaml" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "github.com/oam-dev/kubevela/apis/core.oam.dev/v1alph...
package graphql type SchemaConfig struct { Query *Object Mutation *Object Subscription *Object Types []Type Directives []*Directive Extensions []Extension } type TypeMap map[string]Type // Schema Definition // A Schema is created by supplying the root types of each type of operation, // q...
//////////////////////////////////////////////////////////////////////////////// // // // Copyright 2020 Broadcom. The term Broadcom refers to Broadcom Inc. and/or // // its subsidiaries. ...
package commands import ( "github.com/sad0vnikov/wundergram/logger" "gopkg.in/telegram-bot-api.v4" ) func sendMessageWithLogging(bot *tgbotapi.BotAPI, msg tgbotapi.Chattable) { _, err := bot.Send(msg) if err != nil { logger.Get("main").Errorf("error sending message: %v", err) } logger.Get("main").Debug("sent...
package logger import ( "fmt" "net" "os" ) // StderrChatter - 標準エラー・チャッター。 標準エラー出力とロガーを一緒にしただけです。 type StderrChatter struct { logger Logger } // NewStderrChatter - チャッターを作成します。 func NewStderrChatter(logger Logger) *StderrChatter { chatter := new(StderrChatter) chatter.logger = logger return chatter } // Trac...
package gcache import ( "container/list" "errors" "time" ) // Constantly balances between LRU and LFU, to improve the combined result. type ARC struct { baseCache store map[interface{}]*arcItem // t1 ("tier-1") is an internal cache tracking "recency" t1 *list.List // t2 ("tier-2") is an internal cache trackin...
package auth import ( "net/http" "github.com/aghape/auth/claims" "github.com/aghape/session" "github.com/aghape/core" ) // Context context type Context struct { *core.Context *Auth Claims *claims.Claims Provider Provider } // Flashes get flash messages func (context Context) Flashes() []session.Message { ...
/* Copyright 2015 Crunchy Data Solutions, 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 apperror const ( FailUnmarshalResponseBodyError ErrorType = "ER1000 Fail to unmarshal response body" // used by controller UnrecognizedEnum ErrorType = "ER1001 %s is not recognized %s enum" // used by enum DatabaseNotFoundInContextError ErrorType = "ER1002 Database is not found in context...
// Copyright The OpenTelemetry 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 agre...
package filter import ( "fmt" "gocherry-api-gateway/proxy/enum" ) const ( AuthF = "AuthFilter" BlackList = "BlackListFilter" Caching = "CachingFilter" Jwt = "JwtFilter" Limiting = "LimitingFilter" TraceF = "TraceFilter" Pre = "PreFilter" WhiteList = "WhiteList" ) /** 初始化插件 */ func Ini...
package main import "fmt" //init func init() { fmt.Println("init") } func init() { fmt.Println("init2") } func main() { fmt.Println("Main") }
package cpu import ( "io/ioutil" "runtime" "strconv" "strings" ) func GetCPUTicks() (idle, total uint64) { if "linux" == strings.ToLower(runtime.GOOS) { if contents, err := ioutil.ReadFile("/proc/stat"); nil == err { // 分割每一行 lines := strings.Split(string(contents), "\n") // 遍历每一行 for _, line := ra...
/***************************************************************** * Copyright©,2020-2022, email: 279197148@qq.com * Version: 1.0.0 * @Author: yangtxiang * @Date: 2020-08-26 17:30 * Description: *****************************************************************/ package regcenter import ( "github.com/go-xe2/x/os/xfil...
/* * Copyright 2018 Haines Chan * * This program is free software; you can redistribute and/or modify it * under the terms of the standard MIT license. See LICENSE for more details */ package store import ( "github.com/hainesc/anchor/pkg/utils" "net" ) // Store is the store interface for anchor type Store int...
package protocol import ( "bytes" ) type OpCommand struct { *Op Database string CommandName string Metadata Document CommandArgs Document InputDocs []Document } func (p *OpCommand) Encode() ([]byte, error) { bf := &bytes.Buffer{} if _, err := p.Append(bf); err != nil { return nil, err } return b...
package autoscaler import ( "fmt" "log" "math" "sort" ) var capacityTable map[string]float64 type InstanceCapacity map[InstanceVariety]float64 func (c InstanceCapacity) Total() float64 { t := 0.0 for _, cap := range c { t += cap } return t } func (c InstanceCapacity) Values() []float64 { a := []float64{...
package mempool import ( "encoding/json" "errors" "fmt" "math/rand" "os" "time" "github.com/ethereum/go-ethereum/event" "github.com/meshplus/bitxhub-kit/crypto" "github.com/meshplus/bitxhub-kit/crypto/asym" "github.com/meshplus/bitxhub-kit/log" "github.com/meshplus/bitxhub-kit/storage/leveldb" "github.com...
package main import ( "fmt" "io" "os" "strings" ) func simple() { reader := strings.NewReader("Clear is better than clever") p := make([]byte, 4) for { n, err := reader.Read(p) if err != nil { if err == io.EOF { fmt.Println("EOF:", n) break } fmt.Println(err) os.Exit(1) } fmt.Print...
package ops import ( "crypto/rand" "crypto/sha512" "encoding/base64" "time" ) // https://www.linode.com/docs/email/postfix/email-with-postfix-dovecot-and-mysql // http://wiki.dovecot.org/Authentication/PasswordSchemes // https://mad9scientist.com/dovecot-password-creation-php/ // Domain domain type Domain struct...
// 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 utils import ( "fmt" "github.com/dora1998/snail-bot/clock" "time" ) func ParseDateStr(str string) (time.Time, error) { loc, _ := time.LoadLocation("Asia/Tokyo") now := clock.Now() year := now.Year() const format = "2006/1/2" dateStr := fmt.Sprintf("%d/%s", year, str) t, err := time.ParseInLocation(...
package api import ( "fmt" "net/http" "github.com/gorilla/handlers" "github.com/gorilla/mux" "github.com/teejays/clog" ) // StartServer initializes and runs the HTTP server func StartServer(addr string, port int, routes []Route, authMiddlewareFunc MiddlewareFunc, preMiddlewareFuncs, postMiddlewareFuncs []Middle...
package main import ( "crypto/aes" "crypto/cipher" "crypto/md5" "encoding/hex" "flag" "github.com/harmony-one/harmony/crypto/bls" ffi_bls "github.com/harmony-one/bls/ffi/go/bls" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aw...
package redirect import ( "net" "net/http" ) // ForwardedPort returns a handler that checks if the X-Forwarded-Port header // is set. If it is, the handler verifies that it equals the required port, // otherwise the original request gets redirected to the required port. func ForwardedPort(port string, handler http....
// 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 ( "log" "net/http" "github.com/gorilla/websocket" ) type Message struct { Id string `json:"id"` Content map[string]interface{} `json:"content"` Edit string `json:"edit"` Position int `json:"position"` ContentType st...
package utils import ( "math/rand" "net/url" ) // Contains is a function to check the slice of string contains a string and returns in Int func Contains(t []string, s string) int { for i, v := range t { if v == s { return i } } return -1 } // RandomString returns randomized string with the given length f...
package tools import ( "reflect" "testing" ) func TestGetIntList(t *testing.T) { tests := []struct { input string expected []int err bool }{ {"1,2,3,4,5", []int{1, 2, 3, 4, 5}, false}, {"", []int{}, false}, {"1,invalid,3", []int{}, true}, } for _, test := range tests { result, err := GetI...
package main import ( "fmt" "github.com/mrjones/oauth" "github.com/ota42y/go-tumblr/tumblr" "github.com/typester/go-pit" ) var tumblrDomain string = "tumblr.com" func main() { p, err := pit.Get(tumblrDomain, pit.Requires{ "consumer_key": "", "consumer_secret": "", "access_token": "", ...
package _7_Reverse_Integer import ( "testing" ) func TestReverse(t *testing.T) { if ret := reverse(-12); ret != -21 { t.Error("not -21 with -12.") } if ret := reverse(1200); ret != 21 { t.Error("not 21 with 1200.") } if ret := reverse(1534236469); ret != 0 { t.Error("not 0 with 1534236469.") } if ret :=...
package gosnowth import ( "context" "io" "net/http" "net/http/httptest" "net/url" "strings" "testing" ) func TestRebuildActivity(t *testing.T) { t.Parallel() ms := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request, ) { if r.RequestURI == "/state" { _, _ = w.Write([]byte...
package graph import ( "fmt" "testing" ) func TestDenseGraph(t *testing.T) { g := NewDenseGraph(6, false) fmt.Println(g.graph) fmt.Println("vers:", g.VersNum(), "edges:", g.EdgeNum()) fmt.Println("添加边。。。") g.AddEdge(0, 1) g.AddEdge(0, 1) g.AddEdge(0, 2) g.AddEdge(0, 5) g.AddEdge(1, 2) g.AddEdge(1, 3) g.A...
package data import ( "github.com/open-policy-agent/kube-mgmt/pkg/types" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/dynamic" ) // resourceInterface knows how to use the method `Resource` of dynamic.Interface type resourceInterface interface { Resource(schema.GroupVersionResource) dynamic.Namespac...
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package engine import ( "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-05-01/resources" "github.com/Azure/go-autorest/autorest/to" ) func createAzureStackTelemetry(azureTelemetryPID string) DeploymentAR...
// +k8s:deepcopy-gen=package // +groupName=policy.experiments.k8s.io package v1alpha1
package queue import ( "fmt" "github.com/deckarep/golang-set" "go.uber.org/atomic" "time" ) const DebugPrefix = "[queue-debug]" const DefaultMaxJobs = 50000 type Config struct { MaxWorkers int TimeOut int MaxJobs int } type Job interface { Delay() time.Duration Work() ShouldWork() bool Key() string...
package main import ( "fmt" "sync" ) type Singleton struct{} var ins *Singleton var once sync.Once func GetInstance() *Singleton { once.Do(func() { ins = &Singleton{} fmt.Println("singleton init") }) return ins } func main() { var wg sync.WaitGroup for i := 0; i < 1000; i++ { wg.Add(1) go func() { ...
package main import ( "encoding/base64" "fmt" "os" "regexp" "strconv" "time" "github.com/immesys/wave/eapi/pb" logrus "github.com/sirupsen/logrus" ) var log = logrus.New() func init() { log.SetFormatter(&logrus.TextFormatter{FullTimestamp: true, ForceColors: true}) log.SetOutput(os.Stdout) log.SetLevel(l...
package password import ( "fmt" "strconv" "strings" ) func searchPasswordsMethod1(start, end int) int { validPasswords := 0 for i := start; i <= end; i++ { if validatePasswordMethod1(strconv.Itoa(i)) { validPasswords++ } } return validPasswords } func searchPasswordsMethod2(start, end int) int { val...
package loaders import ( "context" "time" "github.com/syncromatics/kafmesh/internal/graph/loaders/generated" "github.com/syncromatics/kafmesh/internal/graph/model" "github.com/syncromatics/kafmesh/internal/graph/resolvers" "github.com/pkg/errors" ) //go:generate mockgen -source=./topics.go -destination=./topi...
//main package has examples shown //in Hands-On Data Structures and algorithms with Go book package main // importing fmt package import "fmt" // main method func main() { fmt.Println("Hello World") }
package main import ( "fmt" "net/http" ) func hello(w http.ResponseWriter,r *http.Request) { fmt.Fprintf(w,"hello") fmt.Println("hello") } func main() { http.HandleFunc("/",hello) err:=http.ListenAndServe(":8080",nil) if err!=nil{ fmt.Println("http listen failed") } }
package tests import ( "net/http" "strings" "testing" "github.com/GoAdminGroup/go-admin/modules/config" "github.com/GoAdminGroup/go-admin/modules/db" "github.com/GoAdminGroup/go-admin/modules/db/dialect" "github.com/GoAdminGroup/go-admin/plugins/admin/modules/table" "github.com/GoAdminGroup/go-admin/tests/com...
package nats import ( "log" "time" "github.com/b2wdigital/goignite/pkg/config" "github.com/nats-io/nats.go" ) const ( MaxReconnects = "transport.client.nats.maxreconnects" ReconnectWait = "transport.client.nats.reconnectwait" HealthEnabled = "transport.client.nats.health.enabled" HealthDescriptio...
package TToT import ( "fmt" "github.com/AliceDiNunno/TwitterToTelegram/models" "github.com/dghubble/oauth1" "os" "regexp" "sort" "time" "github.com/jinzhu/gorm" "github.com/dghubble/go-twitter/twitter" _ "github.com/mattn/go-sqlite3" "gopkg.in/tucnak/telebot.v2" ) var twitterClient *twitter.Client type ...
package requests type WalletChangeSeedRequest struct { BaseRequest `mapstructure:",squash"` Seed string `json:"seed" mapstructure:"seed"` }
package main import ( "strconv" "fmt" "io" "runtime" "log" ) type Options struct { par1 int par2 string par3 float64 } func trace(s string) string{ fmt.Printf("entering: %s\n",s) return s } func untrace(s string){fmt.Printf("leaving: %s\n",s)} func main() { str := "abcdefg" //an,err := strconv.Atoi(str...
package libModel import ( "github.com/bb-orz/gt/utils" "io" "text/template" ) type FormatterGormDao struct { FormatterStruct } func NewFormatterGormDao() *FormatterGormDao { return new(FormatterGormDao) } func (f *FormatterGormDao) Format(name, table string, cols []Column) IFormatter { f.PackageName = name f...
package httpclientinterception import ( "net/http" ) type matcher interface { Match(*http.Request) bool } type matchMetadata struct { } // methodMatcher matches the request against the method value. type methodMatcher string func (method methodMatcher) Match(r *http.Request) bool { return r.Method == string(met...
package protocol import "testing" func TestClient(t *testing.T) { } // TODO test case: current sever is not the leader, the client is redirected to the new leader
package types import ( "bytes" "encoding/hex" ) const ( HashLength = 32 ) type Hash [HashLength]byte func BytesToHash(b []byte) Hash { var h Hash h.SetBytes(b) return h } func DefHash() Hash { return BytesToHash([]byte{0}) } // SetBytes sets the hash to the value of b. // If b is larger than len(h), b will...
package api import ( // "sub_account_service/app_server_v2/db" // "sync" // "time" // "github.com/golang/glog" ) // const ( // SUBWAY_MONTH = 2 // SUBWAY_DATE = 1 // FRISTDAY = 1 // TIMEOUT = 60 * time.Second // ADAY = 24 * time.Hour // RESETPENDING = 20 * time.Second // RESETTIMES = "...
package common // import ( // "bytes" // "compress/gzip" // "errors" // "io/ioutil" // ) // // GZipFromBytes receives bytes array // // and compresses that bytes array using gzip // func GZipFromBytes(src []byte) ([]byte, error) { // if len(src) == 0 { // return []byte{}, errors.New("input to gzip compress is ...
package cosmos import ( "bytes" "context" "errors" "net/http" "reflect" "strings" "github.com/google/uuid" ) // Client model type Client struct { key string domain string url string path string httpClient *http.Client rType string // dbs,colls,docs,udfs,sprocs,triggers rLin...
package auth import ( "bytes" "encoding/base64" "fmt" "math/rand" "net/http" "strings" "github.com/naelyn/go-docker-registry/types" ) // generate_headers func WriteAuthHeader(w http.ResponseWriter, repo types.Repo, access string) { sig := genRandomString() tok := fmt.Sprintf(`Token signature=%s,repository="...
package command import ( "flag" "fmt" "io" "os" "text/tabwriter" log "github.com/Sirupsen/logrus" "github.com/quilt/quilt/api/client" "github.com/quilt/quilt/api/client/getter" "github.com/quilt/quilt/db" "github.com/quilt/quilt/util" ) // Machine contains the options for querying machines. type Machine s...
package pathfileops import "testing" func TestFileAccessControl_New_01(t *testing.T) { textCode := "-rw-rw-rw-" fPermCfg, err := FilePermissionConfig{}.New(textCode) if err != nil { t.Errorf("Error returned by FilePermissionConfig{}.New(textCode). "+ "textCode='%v' Error='%v'", textCode, err.Error(...