text
stringlengths
11
4.05M
package imapmaildir import ( "errors" "fmt" "io" "os" "path/filepath" "strconv" "strings" "time" "github.com/asdine/storm/v3" "github.com/emersion/go-imap" "github.com/emersion/go-imap/backend/backendutil" "github.com/emersion/go-maildir" "go.etcd.io/bbolt" ) type Mailbox struct { b *Backend // DB ha...
package main import ( "crypto/hmac" "crypto/sha256" "encoding/base64" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os" "github.com/gorilla/mux" ) func main() { log.Println("starting server...") defer log.Println("shutting down server...") go registerWebhook() m := mux.NewRouter() m.HandleFunc(...
package main import "fmt" func search(s []int, e int) int { low := 0 high := len(s) - 1 for low < high { mid := low + ((high - low) / 2) if s[mid] < e { low = mid + 1 } else { high = mid } } if low < len(s)-1 && s[low] == e { return low // found } return -1 // not found } func main() { s...
package main func main() { t := NewTermbox() t.Display() }
package service import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) var db *gorm.DB var err error func InitDB() { user := "root" password := "mysql" dbname := "todo" db, err = gorm.Open("mysql", user+":"+password+"@tcp(mysql:3306)/"+dbname+"?charset=utf8&parseTime=True&loc=Loc...
package main const ( Version = `confort version 1.0.0 Copyright (C) 2019, jiro4989 Released under the MIT License. https://github.com/jiro4989/confort` )
package api // Error represents a handler error. It provides methods for a HTTP status // code and embeds the built-in error interface. type Error interface { error Status() int } type StatusError struct { Code int Err error } // Allows StatusError to satisfy the error interface. func (se StatusError) Error() s...
package core import "time" const sampleTime string = "2006-01-02 15:04:05" type LocalTime time.Time // func (lt *LocalTime) MarshaJSON() ([]byte, error) { // b := make([]byte,0,len(sampleTime)+2) // b = append(b, '"') // if len(lt.String()) >0 { // b= time.Time(*lt).AppendFormat(b,sampleTime) // } // b = ap...
package config import ( "io/ioutil" "log" "gopkg.in/yaml.v2" ) // YamlConfig yaml config type YamlConfig struct { Redis struct { Address string `yaml:"address"` Password string `yaml:"password"` } Mysql struct { Username string `yaml:"username"` Password string `yaml:"password"` } } /** or */ // typ...
/* * @lc app=leetcode.cn id=354 lang=golang * * [354] 俄罗斯套娃信封问题 */ /* 算法思路 先对信封的宽度进行升序排序,然后对宽度相同的信封进行高度降序 1、先排序 2、在对高度一栏进行最长子序列计算 */ // @lc code=start import ( "sort" ) type Envelops [][]int func (e Envelops) Len() int { return len(e) } func (e Envelops) Swap(i,j int) { e[i],e[j] = e[j],e[i] } func (e Env...
package main import ( "bufio" "bytes" "file-server/pkg/rpc" "io" "io/ioutil" "log" "net" "os" "testing" "time" ) func Test_uploadFileToServer(t *testing.T) { const addr = "localhost:7777" go func() { listener, err := net.Listen("tcp", addr) if err != nil { t.Fatalf("can't listen on %s: %v", addr, ...
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" _ "net/http/pprof" "strconv" "strings" "time" ) var statsd = &StatsD{Namespace: "leftpad", SampleRate: 0.5} func init() { var f, err = ioutil.TempFile("", "leftpad.log") if err != nil { panic(err) } log.SetOu...
package main import "fmt" func main() { //声明式变量 //一次申报多个 var a, b, c string a = "hello" b = "world" c = "golang" fmt.Println(a, b, c) }
/* Package gocosmos provides database/sql driver and a REST API client for Azure Cosmos DB SQL API. */ package gocosmos const ( // Version of package gocosmos. Version = "0.1.4" )
/* * Copyright (c) 2019 WSO2 Inc. (http:www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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/license...
package main import ( "fmt" "../../../unimatrix" ) func main() { unimatrix.SetURL("http://us-west-2.api.acceptance.unimatrix.io") operation := unimatrix.NewRealmOperation( "5cbc6bb3db90e2f1236e005f9054776c", "artifacts", ) // create a new query query := unimatrix.NewQuery(). Where("type_name:eq", "vide...
/* * Created on Sun Apr 07 2019 20:57:3 * Author: WuLC * EMail: liangchaowu5@gmail.com */ func prefixesDivBy5(A []int) []bool { result := []bool{} curr := 0 for _, num := range A { curr = (curr * 2 + num) % 5 if curr == 0 { result = append(result, true) } else { result = append(result, false) } ...
package main import ( "fmt" "log" "time" ) func httpEvenNumToString(num int) (string, error) { log.Println("Before mock http request") // Simulates an HTTP request time.Sleep(time.Duration(num) * time.Second) if num%2 == 0 { return fmt.Sprintf("EVEN: %d", num), nil } else { return "", fmt.Errorf("ERROR OD...
package go_dev import ( "database/sql" _ "github.com/lib/pq" // "fmt" ) func CreatePost(taskID int, user, title, content string, db *sql.DB) bool { sqlStatement := `INSERT INTO posts (task,users,title,content) values($1, $2, $3, $4);` _, err := db.Exec(sqlStatement, taskID, title, user, content) if err != n...
/* * @lc app=leetcode id=79 lang=golang * * [79] Word Search * * https://leetcode.com/problems/word-search/description/ * * algorithms * Medium (35.70%) * Likes: 4250 * Dislikes: 199 * Total Accepted: 522.2K * Total Submissions: 1.5M * Testcase Example: '[["A","B","C","E"],["S","F","C","S"],["A","D"...
// // Copyright (c) SAS Institute 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 agre...
package main import ( "errors" "flag" "fmt" "os" "sort" "github.com/c-14/grue/config" ) const version = "0.3.1-next" func usage() string { return `usage: grue [--help] {add|delete|fetch|import|init_cfg|list|rename} ... Subcommands: add <name> <url> delete <name> fetch [-init] [name] import <config> ini...
//可以看到append()的操作,cap默认增加2倍 package main import ( "fmt" ) func main() { //声明一个arr var a [5]int = [...]int{1, 2, 3, 4, 5} //对arr进行切片 slice := a[:] fmt.Println(slice) fmt.Printf("the slice memory address is %p\nslice is %v\nlen is %d\ncap is %d\n", &slice, slice, len(slice), cap(slice)) slice = append(slice,...
package main import "sort" type Triples [][]int // Leetcode 987. (medium) func verticalTraversal(root *TreeNode) [][]int { if root == nil { return [][]int{} } triples := recursiveVerticalTraversal(root, 0, 0, [][]int{}) sort.Sort(Triples(triples)) res := [][]int{} preX := -1 << 31 tmp := []int{} for _, tri...
package wire import ( "strings" "testing" "github.com/stretchr/testify/require" ) // mockTypeSubType creates a TypeSubType func mockTypeSubType() *TypeSubType { tst := NewTypeSubType() tst.TypeCode = FundsTransfer tst.SubTypeCode = BasicFundsTransfer return tst } // TestTypeSubType validates mockTypeSubType ...
// Copyright (c) 2018-present, MultiVAC Foundation. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. package iconsensus import ( "github.com/multivactech/MultiVAC/model/shard" ) // DepositFetcher get deposited information. type DepositFetc...
package versions import ( "go/build" "os" "path/filepath" "testing" "github.com/google/go-cmp/cmp" "github.com/senseyeio/diligent" ) func Test_goModCache(t *testing.T) { t.Parallel() tests := []struct { name string setup func() func() output string }{ { "GOMODCACHE", func() func() { ol...
package mesh import ( "fmt" "github.com/layer5io/meshery/mesheryctl/pkg/utils" "github.com/pkg/errors" "github.com/spf13/cobra" ) var ( availableSubcommands []*cobra.Command ) // MeshCmd represents the Performance Management CLI command var MeshCmd = &cobra.Command{ Use: "mesh", Short: "Service Mesh Lifecy...
package shared import ( "log" "os" "path" "path/filepath" "testing" lxd "github.com/lxc/lxd/shared" "github.com/stretchr/testify/require" "gopkg.in/flosch/pongo2.v3" ) func TestVerifyFile(t *testing.T) { wd, err := os.Getwd() if err != nil { t.Fatalf("Failed to retrieve working directory: %v", err) } t...
package LeetCode func generateParenthesis(n int) []string { const left = '(' const right = ')' var nLeft int for n > 0 { } } func generateFunc(n int, nleft int, nright int, runes *[][]rune, alreadys []rune) { if nleft < n { } }
package main import "fmt" func digital(number int, ch chan int) { for number != 0 { digit := number % 10 ch <- digit number /= 10 } close(ch) } func main() { fmt.Println() ch := make(chan int, 5) go digital(25123412, ch) for v := range ch { fmt.Println("Now i get: ", v) } fmt.Println("Done") }
/* Copyright 2018 Cai Gwatkin 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 dis...
package services import ( "github.com/mobilemindtec/go-utils/app/models" beego "github.com/beego/beego/v2/server/web" "github.com/beego/beego/v2/core/logs" "encoding/json" "encoding/base64" "encoding/hex" "crypto/sha1" "crypto/hmac" "io/ioutil" "net/http" "strings" "bytes" "fmt" ) type MailSer...
package client import ( "fmt" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // DeletePod deletes the pod func (cli *Client) DeletePod(pod *corev1.Pod) error { return cli.podInterface.Delete(pod.Name, &metav1.DeleteOptions{}) } // GetExternalIPOfPod returns the external IP address o...
package evaluator import ( "path/filepath" "../object" ) var stdPath = object.Record{ Stoned: true, Values: map[string]object.Object{ "join": object.BuiltinFunction(func(args ...object.Object) object.Object { if err := checkAllArgType("env.get", args, object.STRING); err != nil { return err } str...
package models import ( "net/http" validator "github.com/go-playground/validator/v10" "github.com/muhammadsyazili/echo-rest/db" "github.com/muhammadsyazili/echo-rest/helpers" "github.com/muhammadsyazili/echo-rest/template" ) type User struct { Id int `json:"id"` Name string `json:"name" validate:"required,max...
package main import( "os" "fmt" "path" "log" "github.com/forj-oss/goforjj" "github.com/xanzy/go-gitlab" ) //gitlabConnect connect user to gitlab (TODO) func (gls *GitlabPlugin) gitlabConnect(server string, ret *goforjj.PluginData) *gitlab.Client { // gls.Client = gitlab.NewClient(nil, gls.token) //Set url ...
// Copyright 2016 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
// Copyright (C) 2019 Google 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 t...
package services import ( "net/smtp" ) // Send will send email func Send(from string, pass string, to string, subject string, body string) error { msg := "From: " + from + "\n" + "To: " + to + "\n" + "Subject: " + subject + "\n\n" + body err := smtp.SendMail( "smtp.gmail.com:587", smtp.PlainAuth("", fro...
// Copyright 2021 Dataptive SAS. // // 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 ...
package e import ( "context" "fmt" "sync" "time" eostest "github.com/digital-scarcity/eos-go-test" "github.com/k0kubun/go-ansi" "github.com/schollz/progressbar/v3" "github.com/eoscanada/eos-go" "github.com/spf13/viper" "go.uber.org/zap" ) type Environment struct { A *eos.API X contex...
package controllers import ( "github.com/gin-gonic/gin" ) // NewsController <controller> // is used for describing controller actions for news. type NewsController struct{} // Get <function> // is used to handle get action of news controller which will return <count> number of news. // url: /v1/news?count=80 , by d...
package main // Leetcode 64. (medium) func minPathSum(grid [][]int) int { if len(grid) == 0 { return 0 } if len(grid[0]) == 0 { return 0 } mr, mc := len(grid), len(grid[0]) for i := 1; i < mr; i++ { grid[i][0] += grid[i-1][0] } for i := 1; i < mc; i++ { grid[0][i] += grid[0][i-1] } for i := 1; i < m...
package runtime import ( "container/list" "context" "errors" "fmt" "os" "os/signal" "reflect" "runtime" "sync" "syscall" "time" "go.uber.org/dig" ) var ( Debug = func(a ...any) { fmt.Println(a...) } ) func Debugf(format string, a ...any) { Debug(fmt.Sprintf(format+"\n", a...)) } type Hook struct { ho...
package models import "github.com/jinzhu/gorm" type ProductTag struct { gorm.Model TagId int ProductId int }
package main import ( "encoding/binary" "fmt" "io" "log" "net" "os" "time" "govenom/payloads/exfilwriter" ) var ( // set during compilation via -X ldflag address string network string exfilCfg string exfilTimeout string ) func receiveShellcode(r io.Reader) ([]byte, error) { sizeBuffer :=...
package logic import ( "math/rand" "time" ) const ( ProbabilityDefault = 0 ProbabilityMax = 10000 ) type Probability int func (p Probability) UnderProbability() bool { if p == ProbabilityDefault || p > ProbabilityMax { return true } return rand.Intn(ProbabilityMax) < int(p) } func init() { rand.Seed(...
package main import "CMDB/api/cmd" func main(){ cmd.Execute() } /* go run main.go -f ../api/etc/demo.toml start 1.127.0.0.1:8050/host 2.快捷启动: ./CMDB-api start -f ../api/etc/demo.toml 3.开始前端 3:04:10 4.前端启动指令 进入ui后 输入 npm run serve 5.28讲看完 */
/* Max Points on a Line Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. Example 1: Input: [[1,1],[2,2],[3,3]] Output: 3 Explanation: ^ | | o | o | o +-------------> 0 1 2 3 4 Example 2: Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] Output: 4 Explanat...
package main import ( "github.com/ajhager/engi" "math/rand" "github.com/Rubentxu/lbricks" "fmt" ) var ( bots []*Bot on bool num int region *engi.Region batch *engi.Batch ) type Bot struct { *engi.Sprite DX, DY float32 } type Game struct { *engi.Game EventSystem *lbricks.EventSystem } func (g...
package pubsub import ( "container/list" "sync" ) /* ErrSubscriptionNotFound returns on poll in case subscribe has not been done before */ type ErrSubscriptionNotFound struct{} func (ErrSubscriptionNotFound) Error() string { return "Subscription not found" } /* Queue contains list for every subscription. so messa...
package main import ( "log" "net/http" "github.com/gorilla/mux" "github.com/phazon85/go_contacts/handler" "github.com/phazon85/go_contacts/services" "github.com/phazon85/multisql" ) const ( configFile = "dev.yaml" driverName = "postgres" ) func main() { //load DB connection db := multisql.NewDBObject(con...
package main import ( "fmt" "strconv" ) func main() { s := "12" fmt.Println(numDecodings(s)) } func numDecodings(s string) int { if len(s) == 0 || s[0] == '0' { return 0 } magic := make([]int, len(s)+1) magic[0], magic[1] = 1, 1 for i := 2; i < len(s)+1; i++ { if s[i-1] != '0' { magic[i] += magic[i-...
package compute // import "yunion.io/x/onecloud/pkg/mcclient/options/compute"
package network import "crypto/x509" func AppendCertsFromPEM(certsPEM ...string) (*x509.CertPool, error) { systemCertPool, err := x509.SystemCertPool() if err != nil { return nil, err } for _, cert := range certsPEM { systemCertPool.AppendCertsFromPEM([]byte(cert)) } return systemCertPool, nil }
package dockeringo import ( "github.com/docker/docker/api/types" "github.com/docker/docker/client" ) type Controller struct { cli *client.Client } type VolumeMount struct { HostPath string Volume *types.Volume } func NewController() (c *Controller, err error) { c = new(Controller) c.cli, err = clie...
package main_test import ( "testing" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) func TestSarge(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Sarge Suite") }
package main import ( "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "html/template" "net/http" "video-stream/controller" ) type VideoPage struct { Filename string } func main() { r := chi.NewRouter() r.Use(middleware.RequestID) r.Use(middleware.RealIP) r.Route("/web", func(r chi.Router) { ...
package registry import ( "context" ) type Registry interface { Init(ctx context.Context, opts ...interface{}) (error) Register (ctx context.Context, service *Service) (error) Deregister (ctx context.Context, service *Service) (error) QueryService (ctx context.Context, name string) (map[string]*Service, error) ...
// Copyright 2018 Istio 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 i...
// Package wkb is for decoding ESRI's Well Known Binary (WKB) format // sepcification at https://en.wikipedia.org/wiki/Well-known_text_representation_of_geometry#Well-known_binary package wkb import ( "bytes" "encoding/binary" "encoding/hex" "errors" "io" "github.com/paulmach/orb" "github.com/paulmach/orb/enco...
package solutions func flatten(root *Node) *Node { if root == nil { return root } dummyHead := &Node{0, nil, root, nil} var current, previous *Node = nil, dummyHead var stack []*Node stack = append(stack, root) for len(stack) > 0 { current = stack[len(stack) - 1] ...
// Copyright 2020 TSINGSEE. // http://www.tsingsee.com // 日志模块配置 // Creat By Sam // History (Name, Time, Desc) // (Sam, 20200506, 创建文件) package util import ( "go.uber.org/zap" "go.uber.org/zap/zapcore" "gopkg.in/natefinch/lumberjack.v2" "os" "time" ) // 操作日志 var operationLogger *zap.Logger // 获取日...
package Test type Interface interface { InterfaceMethod(int) string OtherMethod() io.Reader }
package main import ( "fmt" "strings" ) func ifSemiColon() { // se puede asignar justo despues del if un valor y tras un punto y coma compararlo if y := true; y { fmt.Println(y) } } func main() { name := "crispycreiker" clase := "guerrero/clerigo" nivel := 23 // lo siguiente chequea que la string clase co...
package types import ( "gopkg.in/mgo.v2/bson" ) type User struct { ID bson.ObjectId `bson:"_id,omitempty" json:"id,omitempty"` Name string `bson:"name" json:"name"` UserName string `bson:"username" json:"username"` Email string `bson:"email" json:"email"` Password string ...
package typeutils import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) const aliasName = "test" type example1 struct{} type example2 struct{} func TestAlias(t *testing.T) { Reg := NewRegistry() reg, ok := Reg.(*registry) require.True(t, ok) require.NotNil(t, reg) ...
package errors import ( "runtime" "strings" ) // stack represents a stack of program counters. type stack []uintptr func callers(skip int) stack { const depth = 32 var pcs [depth]uintptr n := runtime.Callers(3+skip, pcs[:]) var st stack = pcs[0:n] return st } type frame struct { Func string Path string Li...
package utils var ( ErrSystem = []byte("system error") ErrClientProtocol = []byte("client protocol error") )
package main import "fmt" func main() { fmt.Print("Enter a character: ") var val byte fmt.Scanf("%c", &val) fmt.Printf("Character value: %c", val) fmt.Printf("\nASCII value: %d", val) }
package routes import ( "encoding/json" "io" "net/http" ) // simpleResponse delivers success status and a message type simpleResponse struct { Success bool `json:"success"` Message string `json:"message"` } // helloWorld is a handler that responds with the string "Hello World" func helloWorld(w http.ResponseW...
package models type ApiMenus struct { List []*Menu }
package main import "fmt" func main() { var x [5]int fmt.Printf("Type: %T\n", x) fmt.Println("Enter array values") for i := 0; i < 5; i++ { fmt.Scan(&x[i]) } fmt.Println("Length of Array", len(x)) fmt.Println("Value at 2th position", x[1]) x[1] = 27 fmt.Println("Value at 2th positi...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package fixture provides ti50 devboard related fixtures. package fixture import ( "context" "time" "google.golang.org/grpc" "chromiumos/tast/common/firmware/ti50" ...
package main import ( "fmt" "net/http" ) type Hello struct { Str string } func (h Hello) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, h.Str); } func main() { h0 := Hello{"Hey, world."} http.ListenAndServe("localhost:4000", h0) }
package update import ( "encoding/json" "fmt" "net/http" "github.com/ocoscope/face/db" "github.com/ocoscope/face/utils" "github.com/ocoscope/face/utils/answer" ) func CompanyLogo(w http.ResponseWriter, r *http.Request) { type tbody struct { CompanyID, UserID uint AccessToken, Logo string } var body tb...
package sgml import ( "strings" "github.com/bytesparadise/libasciidoc/pkg/types" "github.com/davecgh/go-spew/spew" "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) func (r *sgmlRenderer) prerenderTableOfContents(ctx *context, toc *types.TableOfContents) error { if toc == nil || toc.Sections == nil { ...
package serv import ( "context" "errors" "github.com/go-kit/kit/endpoint" ) // Endpoints are exposed type Endpoints struct { CalcEndpoint endpoint.Endpoint } // MakeCalcEndpoint returns the response from our service "Calc" func MakeCalcEndpoint(srv Service) endpoint.Endpoint { return func(ctx context.Context, ...
package main import ( "time" "github.com/JekoMonstar/Jas.Atlantis/config" "github.com/JekoMonstar/Jas.Atlantis/examples/common/sdk" "github.com/JekoMonstar/Jas.Atlantis/plugin" "google.golang.org/grpc/grpclog" ) func main() { plugin.UseLog(true) cfg := &config.Config{ Addr: "localhost:9090", Timeout: 3...
package credhub_helpers import ( "encoding/json" "fmt" "os/exec" "time" "strings" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/onsi/gomega/gexec" ) type CredHubCLI struct { ClientName string ClientSecret string } func NewCredHubCLI(clientName, clientSecret string) *CredHubCLI { ...
package controller import ( "fmt" "time" "github.com/pkg/errors" "k8s.io/apimachinery/pkg/labels" kubeinformers "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes" kubelisters "k8s.io/client-go/listers/core/v1" "k8s.io/client-go/rest" "github.com/solo-io/gloo-api/pkg/api/types/v1" kubeplugin "github...
package master import ( "context" "encoding/json" "fmt" "go.etcd.io/etcd/clientv3" "testsrc/go-destributed-crontab/common" "time" ) //任务管理器 type JobMgr struct { client *clientv3.Client kv clientv3.KV lease clientv3.Lease } var ( //单例 G_jobMgr *JobMgr ) //初始化管理器 func InitJobMgr() (err error) { //初始化...
package main import ( "io/ioutil" "strings" "gopkg.in/yaml.v2" ) func getConf(path string) (*config, error) { c := &config{} buf, err := ioutil.ReadFile(path) if err != nil { return nil, err } err = yaml.Unmarshal(buf, c) if err != nil { return nil, err } return c, nil } func in(l []string, str str...
package sweetmarias import ( "context" "io" "net/http" "os" "testing" "net/http/httptest" "github.com/frioux/leatherman/internal/testutil" ) func TestLoadCoffee(t *testing.T) { t.Parallel() ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-T...
package ion import ( "bytes" "math" "math/big" "testing" "time" ) func TestIgnoreValues(t *testing.T) { r := NewReaderStr("(skip ++ me / please) {skip: me, please: 0}\n[skip, me, please]\nfoo") _next(t, r, SexpType) _next(t, r, StructType) _next(t, r, ListType) _symbol(t, r, "foo") _eof(t, r) } func Tes...
package retinaws import ( "github.com/gorilla/websocket" "io" "log" "net" "sync" "time" ) // This code inspired by the chat example by Gary Burd here: // https://github.com/gorilla/websocket/blob/master/examples/chat/conn.go // // But all bugs are mine const ( // Time allowed to write a message to the peer. ...
package generator type status struct { value interface{} done bool err error } func (s status) Data() (interface{}, bool, error) { return s.value, s.done, s.err } type retStatus interface { Type() string Data() (interface{}, bool, error) } type yieldRetStatus struct { value interface{} } func (yieldRetSt...
package handlers import ( "errors" "net/http" "github.com/heptiolabs/healthcheck" elastic "github.com/olivere/elastic/v7" ) func healthzHandler(client *elastic.Client) http.Handler { health := healthcheck.NewHandler() health.AddReadinessCheck("elasticsearch", esCheck(client)) return health } func esCheck(cli...
package models import ( "time" "github.com/juliotorresmoreno/unravel-server/db" ) type Noticia struct { Id uint `xorm:"bigint not null autoincr pk" json:"-"` Usuario string `xorm:"varchar(100) not null index" valid:"required" json:"usuario"` Noticia string `xorm:"text not null" valid:"require...
package main import ( "github.com/urfave/cli" ) var getCommand = cli.Command{ Name: "get", HelpName: "get", Usage: `Display one or more resources`, Description: "With this command you can list resources", ArgsUsage: `eli get RESOURCE [options] # Get table of running pods eli get pods`, Sub...
package k8s import ( "testing" "github.com/stretchr/testify/assert" "github.com/tilt-dev/tilt/internal/k8s/testyaml" ) func TestStatefulsetPodManagementPolicy(t *testing.T) { ss, err := ParseYAMLFromString(testyaml.RedisStatefulSetYAML) assert.Nil(t, err) newEntity := InjectParallelPodManagementPolicy(ss[0])...
package main import( "net" "os" "fmt" ) var clientsConnected map[string]*net.UDPAddr var globalNext int func ErrorHandle(err error){ if err != nil { fmt.Println("We have a error: " , err) fmt.Println("Exitting") os.Exit(0) } } func PrintErrorIfExists(err error){ if err != nil { ...
package queue import ( "github.com/gin-gonic/gin" jsoniter "github.com/json-iterator/go" "gopkg.in/confluentinc/confluent-kafka-go.v1/kafka" "starter/pkg/app" "sync" ) type ( // Consumer 消费者 Consumer struct { conf kafka.ConfigMap once sync.Once topics []string // 消费标签列表 reBalance kafka.Reb...
package pg import ( "context" "fmt" "github.com/jackc/pgx/v4/pgxpool" ) type DB struct { *pgxpool.Pool } func Dial(url string) (*DB, error) { conn, err := pgxpool.Connect(context.Background(), url) if err != nil { return nil, fmt.Errorf("error while connecting to database, %v", err) } return &DB{conn}, ni...
// Copyright (c) 2018 The MATRIX Authors // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php package support import ( "github.com/MatrixAINetwork/go-matrix/common" "github.com/MatrixAINetwork/go-matrix/log" "github.com/MatrixAINet...
package main import ( "encoding/json" "log" "github.com/gin-gonic/gin" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" ) func initServer(config *Config, bot *tgbotapi.BotAPI) (*gin.Engine, error) { router := gin.Default() router.Use(setBot(bot)) router.POST("/"+config.APIToken, replyRoute) retu...
package restapi import ( "context" "net/http" "time" "github.com/7phs/coding-challenge-search/config" "github.com/7phs/coding-challenge-search/restapi/handler" "github.com/gin-gonic/gin" log "github.com/sirupsen/logrus" ) const ( readTimeout = 5 * time.Second writeTimeout = 10 * time.Second shutdown...
package eventsapi import ( "io/ioutil" "net/http" "strconv" "strings" "testing" "time" ) func TestNewSlackRequest(t *testing.T) { t.Run("valid request", func(t *testing.T) { signature := "signature" now := time.Unix(1234567890, 0) payload := "payload" req := &http.Request{ Header: map[string][]strin...
package pitchforkscrapper import ( "testing" "time" "github.com/stretchr/testify/suite" ) type ScrapeTestSuite struct { suite.Suite } func (s *ScrapeTestSuite) TestParticularAlbum_CorrectDetailsReturned() { a, err := GetAlbumPageInfo("https://pitchfork.com/reviews/albums/16039-take-care/") s.NoError(err, "Sho...