text
stringlengths
11
4.05M
package main import ( "fmt" "time" "github.com/rwcarlsen/money/set" ) func main() { simulateLife() //simulateMortgage() } func simulateLife() { now := time.Now() // income salary := set.PieceWise(set.Month, set.Uniform(now, set.Month, 12 * 3, 75e3 / 12), set.Uniform(now, set.Month, 12 * 4, 93e3 / 12), ...
package miner import ( "fmt" abi "github.com/filecoin-project/go-state-types/abi" big "github.com/filecoin-project/go-state-types/big" "github.com/ipfs/go-cid" mh "github.com/multiformats/go-multihash" builtin "github.com/filecoin-project/specs-actors/actors/builtin" . "github.com/filecoin-project/specs-actor...
package make import ( "fmt" ) func test1() { a := make([]int, 5, 10) fmt.Printf("a:%v, add: %p, len: %d, cap: %d \n", a, a, len(a), cap(a)) for i := 0; i < 10; i++ { a = append(a, i) fmt.Printf("a:%v, add: %p, len: %d, cap: %d \n", a, a, len(a), cap(a)) } } func Test() { test1() }
package main import ( "context" "fmt" ) func main() { ProcessRequest("Jhone", "a1234") } func ProcessRequest(userId, authToken string) { ctx := context.WithValue(context.Background(), "UserID", userId) ctx = context.WithValue(ctx, "authToken", authToken) HandleRequest(ctx) } func HandleRequest(ctx context.Con...
package service import ( "github.com/GoGroup/Movie-and-events/model" "github.com/GoGroup/Movie-and-events/schedule" ) type ScheduleService struct { scheduleRepo schedule.ScheduleRepository } func NewScheduleService(schRepo schedule.ScheduleRepository) schedule.ScheduleService { return &ScheduleService{scheduleRe...
package service import ( "context" "fmt" "sync" "github.com/go-ocf/cloud/cloud2cloud-connector/events" "github.com/go-ocf/kit/codec/cbor" "github.com/go-ocf/kit/codec/json" coap "github.com/go-ocf/go-coap" "github.com/go-ocf/sdk/schema/cloud" "github.com/go-ocf/cqrs/event" "github.com/go-ocf/cqrs/eventsto...
// package main // // import ( // "expvar" // "fmt" // "net/http" // ) // // var visits = expvar.NewInt("visits") // // func handler(w http.ResponseWriter, r *http.Request) { // visits.Add(1) // fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:]) // } // // func main() { // http.HandleFunc("/...
package server import ( "net/http" "reflect" "strings" "time" "github.com/ItsJimi/casa/logger" "github.com/ItsJimi/casa/utils" "github.com/labstack/echo" "golang.org/x/crypto/bcrypt" ) var emailRegExp = "(?:[a-z0-9!#$%&'*+=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x2...
package cmds import ( "github.com/sirupsen/logrus" "github.com/urfave/cli" "github.com/ayufan/docker-composer/compose" ) func runEnableCommand(c *cli.Context) error { app, err := compose.ExistingApplication(c.Args()...) if err != nil { logrus.Fatalln("App:", err) } err = app.Enable() if err != nil { log...
// usage: go run predict_client.go --server_addr 127.0.0.1:9000 --model_name dense --model_version 1 package main import ( "flag" "fmt" framework "tensorflow/core/framework" pb "tensorflow_serving" "golang.org/x/net/context" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grp...
package keeper import ( // "fmt" sdk "github.com/cosmos/cosmos-sdk/types" // sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" abci "github.com/tendermint/tendermint/abci/types" ) func queryReceiverInfo( ctx sdk.Context, keeper Keeper, req abci.RequestQuery, receiver string, ) ([]byte, error) { dayInfos ...
package main func main() { c := CommandInvoker{} c.addToQueue(&SomeCommand{"Simone"}) c.addToQueue(&SomeCommand{"Gentili"}) c.addToQueue(&SomeSpecialCommand{"sensorario"}) }
package gocloud import ( "github.com/b2wdigital/goignite/pkg/config" ) // configs .. const ( Resource = "transport.client.gocloud.resource" Type = "transport.client.gocloud.type" Region = "transport.client.gocloud.region" ) func init() { config.Add(Type, "memory", "define queue type") config.Add(Resource...
package main import ( "fmt" "os" _ "github.com/mattn/go-sqlite3" "github.com/alokmenghrajani/sqlc/sqlc" ) func main() { os.Remove("/tmp/example1.db") db, err := sqlc.Open(sqlc.Sqlite, "/tmp/example1.db") panicOnError(err) defer db.Close() _, err = db.Exec("CREATE TABLE books (id int primary key, ti...
package explorer // 资源管理器 type exDataSet struct { Id string `json:"uuid,omitempty"` Name string `json:"name"` UserId string `json:"user_id"` Type string `json:"type,omitempty"` Description string `json:"description,omitempty"` } type explorer struct { Path string `json:"pat...
package core import ( "log" "github.com/jonmorehouse/gatekeeper/gatekeeper" router_plugin "github.com/jonmorehouse/gatekeeper/plugin/router" ) type RouterClient interface { RouteRequest(*gatekeeper.Request) (*gatekeeper.Upstream, *gatekeeper.Request, error) } type Router interface { starter RouterClient } f...
package main import ( "bytes" "github.com/jhyle/imgserver/api" "image" "image/jpeg" "io/ioutil" "net/http" "os" "strconv" "sync" "testing" "time" ) func TestImgServer(t *testing.T) { tmpPath, err := ioutil.TempDir("", "imgserver") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpPath) // start...
package modules import ( "fmt" "strings" ) // Channels ... func Channels() { switchingBetweenChannels() } type Message struct { To []string From string Content string } type FailedMessage struct { ErrorMessage string OriginalMessage Message } func switchingBetweenChannels() { msgCh := make(cha...
package handler import ( "fmt" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" "github.com/irham/agung/notes-bot/gdrive" "github.com/sirupsen/logrus" "golang.org/x/oauth2" ) type ( handler struct { bot *tgbotapi.BotAPI log *logrus.Logger } ) func New(bot *tgbotapi.BotAPI, log *logrus.Logger) *h...
package timeo import ( "fmt" "time" ) // 创建定时任务 var ( globalrounds int32 ) func main() { // var ch chan int // ticker := time.NewTicker(time.Second * 2) // go func(tickers *time.Ticker) { // for range tickers.C { // fmt.Println(time.Now().Format("2006-01-02 15:04:05")) // } // ch <- 1 // }(ticker) /...
package cmd import ( "fmt" "os" cobra "github.com/spf13/cobra" ) var cfgFike string var rootCmd = &cobra.Command{ Use: "reverse <command> [flags]", Short: "reverse is a go utility to reverse a string", Long: "reverse can reverse string from various source and write to various sources"} // Execute add all chi...
package cmd import ( "fmt" "io/ioutil" "log" "github.com/lhopki01/dirin/internal/config" "github.com/spf13/cobra" "github.com/spf13/viper" ) func registerListCmd(rootCmd *cobra.Command) { listCmd := &cobra.Command{ Use: "list", Short: "List all collections", Args: cobra.NoArgs, Run: func(cmd *cobra...
// Copyright 2018 Andreas Pannewitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package core // =========================================================================== // HeadS represents a series of Head. type HeadS []Head // Tai...
package actions import "github.com/stianeikeland/go-rpio" //-->System Information type Sysinfo struct{ Host HostInfo `json:"host"` Cpu CpuInfo `json:"cpu"` Mem MemInfo `json:"mem"` Disk DiskInfo `json:"disk"` } type HostInfo struct{ Uptime string `json:"uptime"` KernelVer string `json:"kernel_version"` P...
package dto type FocusingExercise struct { Exercise }
package route import ( "fmt" ) type missingRoutesError struct { method string } func (e *missingRoutesError) Error() string { return fmt.Sprintf("%s has no routes", e.method) }
package command import ( "bytes" "context" "strings" "testing" "mvdan.cc/sh/v3/interp" "mvdan.cc/sh/v3/syntax" ) func TestCommand(t *testing.T) { p := syntax.NewParser() file, err := p.Parse(strings.NewReader("printf 123 && printf '4'\"'\"'5''6'"), "") if err != nil { t.Fatal(err) } stdout := &bytes.B...
package validation import ( "bytes" "crypto/ecdsa" "database/sql" "encoding/asn1" "errors" "flag" "log" "math/big" "os" "strings" "time" "unicode" "github.com/SIGBlockchain/project_aurum/internal/accountstable" "github.com/SIGBlockchain/project_aurum/internal/block" "github.com/SIGBlockchain/project_au...
package goevent_test import ( "testing" "github.com/indie21/goevent" ) func TestNewTable(t *testing.T) { ta := goevent.NewTable() t.Logf("%#v", ta) } func TestTableOnTrigger(t *testing.T) { ta := goevent.NewTable() i := 0 err := ta.On("foo", func(j int) { i += j }) if err != nil { t.Error(err) } err = ...
// Copyright 2020 Thomas.Hoehenleitner [at] seerose.net // Use of this source code is governed by a license that can be found in the LICENSE file. package receiver import ( "bytes" "fmt" "io" "io/ioutil" "log" "github.com/rokath/trice/internal/com" "github.com/rokath/trice/internal/link" ) var ( // ShowInpu...
package pathways import ( "net/http" ) type ResponseWriter func(http.ResponseWriter) type Response struct { Response http.ResponseWriter Request *http.Request writer ResponseWriter } func ResponseFromContext(cx *Context, writer ResponseWriter) *Response { return &Response{ Request: cx.Request, Response...
package rp import ( "encoding/json" "net/http" "time" ) // Client is a client for working with the RP Web API. type Client struct { baseURL string authBearer string http *http.Client } // Launch that identifies a test run. type Launch struct { Name string `json:"name"` Description string ...
package apps import ( "fmt" "os" "os/exec" ) func (app *App) run_post_push_commands() error { for _, command := range app.PostPushCommands { err := app.run_post_push_command(command) if err != nil { return err } } return nil } func (app *App) run_post_push_command(command string) error { if app.confi...
// Pacakge dump is a NanoMDM service that dumps raw responses package dump import ( "os" "github.com/micromdm/nanomdm/mdm" "github.com/micromdm/nanomdm/service" ) // Dumper is a service middleware that dumps MDM requests and responses // to a file handle. type Dumper struct { next service.CheckinAndCommandServic...
package main import ( "flag" "lesson/fourth/configs" "lesson/fourth/internal/di" "os" "os/signal" "syscall" "time" "github.com/go-kratos/kratos/pkg/log" ) func main() { flag.Parse() log.Init(nil) defer log.Close() configs.Init() _, closeFunc, err := di.InitApp() if err != nil { panic(err) } c := ma...
package user import ( "context" "github.com/gudongkun/single_ucenter/enlight_ucenter_client" "github.com/gudongkun/single_ucenter/enlight_ucenter_client/proto/user" "github.com/micro/go-micro/v2/broker" ) //GetName 获取用户信息, enlight_ucenter_client是一个整体,子调父的方式也不可避免。 func GetName(ctx context.Context, uid uint64) (*us...
package crd const ( GroupName = "crd.alpha.io" Version = "v1" )
package handlers import ( "context" "encoding/json" "fmt" "log" "net/http" "net/http/httptest" "net/url" "reflect" "strings" "testing" "time" "github.com/DungBuiTien1999/bookings/internal/driver" "github.com/DungBuiTien1999/bookings/internal/models" ) var theTests = []struct { name string...
package fbmessenger import ( "bytes" "encoding/json" "fmt" "io/ioutil" "mime/multipart" "net/http" "net/textproto" "golang.org/x/net/context" ) const apiURL = "https://graph.facebook.com/v3.3" type httpDoer interface { Do(req *http.Request) (*http.Response, error) } /* Client is used to send messages and ...
package message import ( "errors" "fmt" "github.com/streadway/amqp" "time" ) type Publisher struct { getChannel GetChannel exchange string routingKey string timeout time.Duration } func NewPublisher(getChannel GetChannel, exchange, routingKey string, timeout time.Duration) *Publisher { return &Publishe...
/* * EVE Swagger Interface * * An OpenAPI for EVE Online * * OpenAPI spec version: 0.4.1.dev1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ package swagger // alliance object type GetCorporationsCorporationIdAlliancehistoryAlliance struct { // alliance_id integer AllianceId int3...
// Copyright 2018 The go-bindata Authors. All rights reserved. // Use of this source code is governed by a CC0 1.0 Universal (CC0 1.0) // Public Domain Dedication license that can be found in the LICENSE file. package bindata import "testing" // nolint: gochecknoglobals var sanitizeTests = []struct { in string ou...
package api import ( "encoding/json" "net/http" "onikur.com/text-to-img-api/utils" ) // ListFontsHandler ... type ListFontsHandler struct{} func (h *ListFontsHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) { var a []string if status := req.URL.Query().Get("status"); status == "disabled" { a = ...
/* * @lc app=leetcode id=72 lang=golang * * [72] Edit Distance * * https://leetcode.com/problems/edit-distance/description/ * * algorithms * Hard (38.45%) * Likes: 2252 * Dislikes: 34 * Total Accepted: 183.2K * Total Submissions: 476.3K * Testcase Example: '"horse"\n"ros"' * * Given two words word...
package services import "github.com/cloudfoundry-incubator/notifications/models" type TemplateUpdaterInterface interface { Update(models.Template) error } type TemplateUpdater struct { repo models.TemplatesRepoInterface database models.DatabaseInterface } func NewTemplateUpdater(repo models.Template...
package main import ( "fmt" "proxy" ) func main() { server := new(proxy.Proxy) err := server.NewProxy("172.16.64.156", 9876) if err != nil { fmt.Println(err) } server.Run() }
// Copyright 2018 Diego Bernardes. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package repository import ( "context" "encoding/json" "fmt" "net/url" "time" "github.com/pkg/errors" "github.com/diegobernardes/flare" ) // Resource...
package model import "time" type User struct { ID string `json:"id" gorm:"primaryKey"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` DeletedAt *time.Time `json:"deleted_at" sql:"index"` Name string `json:"name" gorm:"unique; not null"` //昵称 Email stri...
package main import ( "database/sql" "fmt" "log" "net/http" "time" _ "github.com/mattn/go-sqlite3" "golang.org/x/crypto/bcrypt" ) var DB *sql.DB func SetupDB() { var err error DB, err = sql.Open("sqlite3", DB_FILE) if err != nil { log.Fatal(err) } _, err = DB.Exec( `CREATE TABLE IF NOT EXISTS files ...
package main import "fmt" var numbers = []int{1, 2, 4, 8, 16} /* This func returns an anonymous func that stores the i variable as a value. By this way the i variable has a scope that goes over of counter. */ func counter() func() int { var i int return func() int { i++ return i } } func useCounter() { f :=...
package handler import ( "time" "github.com/labstack/echo/v4" "github.com/milobella/oratio/internal/ability" "github.com/milobella/oratio/internal/config" "github.com/milobella/oratio/pkg/anima" "github.com/milobella/oratio/pkg/cerebro" "github.com/sirupsen/logrus" ) // New initiates all the handlers and thei...
/** * @Author : henry * @Data: 2020-08-13 21:15 * @Note: **/ package models type Voucher interface { AddVoucher() }
package main import "text/template" var tmpl = template.Must(template.New("default").Parse(` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Disk Space Visualizer</title> <style type="text/css"> html, body { font: 14px/20px "Courier New", Courier, monospace } ul { list-style: none; pad...
package command import ( "fmt" "github.com/ajpen/termsnippet/core" "gopkg.in/urfave/cli.v1" ) func init() { InstallCommand(listSnippetCommand()) } const ( listSnippetTemplate = "%s: %s\n\n" ) func listSnippetCommand() cli.Command { cmd := cli.Command{ Name: "list", Description: "list all saved sn...
package models import ( "github.com/astaxie/beego" "database/sql" "fmt" ) type Application struct { Id int64 Title string } func GetFrist10() (result []Application, err error){ var rows *sql.Rows rows, err = DB.Query("select id, title from Application order by id desc limit 10") if e...
package common import ( "testing" "github.com/root-gg/utils" "github.com/stretchr/testify/require" ) func TestUnmarshalUpload(t *testing.T) { u := &Upload{} u.NewFile() bytes, _ := utils.ToJson(u) upload := &Upload{} version, err := UnmarshalUpload(bytes, upload) require.NoError(t, err, "unmarshal upload e...
package AAC import ( "github.com/panda-media/muxer-fmp4/utils" "strings" ) const ( AOT_NULL = iota // Support? Name AOT_AAC_MAIN ///< Y Main AOT_AAC_LC ///< Y Low Complexity AOT_AAC_SSR ///< N (code in SoC repo) Scalable Sample Rate ...
package v1 import ( "github.com/freelifer/gohelper/pkg/e" "github.com/gin-gonic/gin" ) // @Summary 密码列表 // @Tags passwd // @Produce json // @Success 200 {string} json "{"code":200,"data":{"session_id":"xxxxxxxxxxx"},"msg":"ok"}" // @Router /v1/passwds [get] func PasswdList(c *gin.Context) { e.SuccessJ...
package api import ( "encoding/json" "github.com/EmpregoLigado/cron-srv/mock" "github.com/EmpregoLigado/cron-srv/models" "github.com/nbari/violetear" "net/http" "net/http/httptest" "strconv" "strings" "testing" ) func TestEventsIndex(t *testing.T) { schedulerMock := mock.NewScheduler() repoMock := mock.New...
package controller import ( "github.com/bearname/videohost/internal/videoserver/domain" "github.com/bearname/videohost/internal/videoserver/domain/model" ) type CreatePlayListRequest struct { Name string `json:"name"` Privacy model.PrivacyType `json:"privacy"` VideosId []string `json:"vi...
/* package core модуль time_to_ready содержит объекты, которые змейка может съесть */ package game import ( "github.com/JoelOtter/termloop" ) //createTimeObj создать отрисовку обратного отсчёта func createTimeObj(text string) *timeToReady { timeObj := new(timeToReady) timeObj.Text = termloop.NewText(7, (high/2)-1...
package utils import ( "testing" "github.com/stretchr/testify/assert" ) func TestValidate64HexHash(t *testing.T) { valid := "1A2E95A2DCF03143297572EAEC496F6913D5001D2F28A728B35CB274294D5A14" assert.Equal(t, true, Validate64HexHash(valid)) // invalid, not hex invalid := "1A2E95A2DCZ03143297572EAEC496F6913D5001D...
package Plugins import ( "../Misc" "../Parse" "fmt" "golang.org/x/crypto/ssh" "sync" "time" ) const SSHPORT = 22 func SSH(info Misc.HostInfo, ch chan int, wg *sync.WaitGroup) { var err error config := &ssh.ClientConfig{ User: info.Username, Auth: []ssh.AuthMethod{ssh.Password(info.P...
package humanize import ( "go/ast" "strings" ) // FuncType is the single function type FuncType struct { pkg *Package Parameters []*Variable Results []*Variable } func (f *FuncType) getDefinitionWithName(name string) string { return "func " + name + f.Sign() } // Sign return the function sign func (f *Fun...
package resin import "testing" var testToken string = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6Mjc1LCJ1c2VybmFtZSI6InBhYmxvY2FycmFuemEiLCJlbWFpbCI6InNvbWVvbmVAZ21haWwuY29tIiwic29jaWFsX3NlcnZpY2VfYWNjb3VudCI6W10sImhhc19kaXNhYmxlZF9uZXdzbGV0dGVyIjpmYWxzZSwiand0X3NlY3JldCI6InNlY3JldHNlY3JldCIsImhhc1Bhc3N3b3JkU2V0Ij...
package tests import ( "testing" "github.com/WindomZ/quizzee" "github.com/WindomZ/testify/assert" ) func TestAnswer_Parse(t *testing.T) { a := quizzee.NewAnswer("鲁迅:周樟寿") assert.NoError(t, a.Parse()) assert.Equal(t, []string{"鲁迅", "周樟寿"}, a.Keys) }
package main import ( "database/sql" "fmt" "log" _ "github.com/lib/pq" ) func main() { db, err := sql.Open("postgres", "postgres://jeoysqgj:Yqpkng49GujaIUn9LrGfzP1bRD3JHFAM@suleiman.db.elephantsql.com:5432/jeoysqgj") if err != nil { log.Fatal("Connect to database error", err) } defer db.Close() stmt, er...
package wallet import "testing" func TestWallet(t *testing.T) { t.Run("Deposit", func(t *testing.T) { wallet := Wallet{} wallet.Deposit(Bitcoin(10)) want := Bitcoin(10) assertBalance(t, wallet, want) }) t.Run("Withdraw", func(t *testing.T) { wallet := Wallet{Bitcoin(10)} err := wallet.Withdraw(Bitc...
package validator import ( "strings" ) type EmailDomainAllowed struct { Value string AllowedDomains []string } func (v EmailDomainAllowed) Validate() (bool, Message) { stringParts := strings.Split(v.Value, "@") if len(stringParts) < 2 { return false, Message("Email value doesnt contain '@'") } dom...
package serato_test import "testing" func TestReadSession(t *testing.T) { t.Skip() }
// Package main is the entrypoint for the github.com/wreckerlabs/goliccop utility // which helps developers honor license demands. package main import ( "errors" "flag" "fmt" "go/parser" "go/token" "io/ioutil" "os" "path/filepath" "strings" "sync" "github.com/dustin/go-humanize" ) var ( verbose = flag.Bo...
package utils import ( "testing" "time" "github.com/jonmorehouse/gatekeeper/gatekeeper/test" ) type validConfig struct { Str string `flag:"str" default:"default"` Dur time.Duration `flag:"duration" default:"1m"` Bool bool `flag:"bool" default:"false"` Uint uint `flag:"ui...
package router import ( "fmt" "log" s "github.com/nedp/command/sequence" ) type ContParams struct { ID int Router *Router } func (ContParams) IsParams() {} // Marker // Need to use a closure to capture the router. func NewContParams(r *Router) func() Params { return func() Params { p := new(ContParams) p....
package main import ( "fmt" "math/rand" "strings" "time" ) // Data - some data to process type Data struct { Before string After string } func main() { // init our random number generator rand.Seed(time.Now().Unix()) // blocking channels - no buffer specified // only a single Data instance can be placed ...
package suites import ( "fmt" "testing" "github.com/go-rod/rod" ) func (rs *RodSession) verifyIsPublic(t *testing.T, page *rod.Page) { page.MustElementR("body", "headers") rs.verifyURLIs(t, page, fmt.Sprintf("%s/headers", PublicBaseURL)) }
package csms import ( "context" "net" "sync" "testing" insecure "gx/ipfs/QmWmeXRTSyWvjPQZgXjXTj2aP74tMSgJwWi1SAvHsvBJVj/go-conn-security/insecure" sst "gx/ipfs/QmWmeXRTSyWvjPQZgXjXTj2aP74tMSgJwWi1SAvHsvBJVj/go-conn-security/test" ) func TestCommonProto(t *testing.T) { var at, bt SSMuxer atInsecure := insecur...
package api import ( "context" internalclient "github.com/chanioxaris/go-datagovgr/internal/client" "github.com/chanioxaris/go-datagovgr/types" ) // Health holds required info to consume Health related endpoints. type Health struct { client *internalclient.Client } // NewHealth creates a new instance. func NewH...
package debug import ( "fmt" "github.com/darkliquid/leader1/state" "html/template" "log" "net" "net/http" _ "net/http/pprof" "os" "runtime" "sync" ) var memTemplate string = `<html><head><title>Memstats</title></head><body> <h1>Memstats</h1> <h2>General</h2> <dl> <dt>Alloc</dt> <dd>{{.Alloc}}</dd> <dt>Total...
package handlers import ( "fmt" "htmlparser/analyser" "htmlparser/httpclient" "os" "github.com/gin-gonic/gin" "github.com/montanaflynn/stats" "htmlparser/models" ) func Prometheus(c *gin.Context) { appSparkMetrics, err := getMetrics() if err != nil { c.Error(err) return } var schedulingDelays []floa...
package main import ( "fmt" ) func main() { fmt.Println(addDigits(678)) } func addDigits(num int) int { for num >= 10 { next := 0 for num != 0 { next = next + num%10 num /= 10 } num = next } return num }
package main //"reflect" //"strings" //"testing" /* var xmltest = []struct { xmltext string err error result []TalonInfo }{ { `<?xml version="1.0" encoding="WINDOWS-1251"?><?BSERTIF1 version="0.2"?><BIRTH_SERTIF xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <HEADER DATE="000" TO="" KPP="" INN=""...
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { fmt.Println("Printing Fibonacci numbers..") reader := bufio.NewReader(os.Stdin) for { generator := calculateFibonacci() input, _ := reader.ReadString('\n') value, err := strconv.Atoi(strings.TrimSpace(input)) ...
package model // StateOverViewResp 博客统计返回 type StateOverViewResp struct { ID string `json:"id"` Title string `json:"title"` Tags []string `json:"tags"` Author string `json:"author"` Pv int64 `json:"pv"` Uv int64 `json:"uv"` } // StatDetailResp 博客趋势详情 type StatDetailResp struct { Date string `json:"date"` Pv i...
package main import "fmt" func largestPrime(n uint64) uint64 { var largest uint64 = 2 for n > 1 { for n%largest == 0 { n /= largest } largest++ } return largest - 1 } func main() { fmt.Println(largestPrime(13195)) fmt.Println(largestPrime(600851475143)) } // Find the largest prime factor of a number....
package matchers import ( "bytes" "fmt" "reflect" "gx/ipfs/QmUWtNQd8JdEiYiDqNYTUcaqyteJZ2rTNQLiw3dauLPccy/gomega/format" ) type EqualMatcher struct { Expected interface{} } func (matcher *EqualMatcher) Match(actual interface{}) (success bool, err error) { if actual == nil && matcher.Expected == nil { return...
package main import ( "fmt" "time" ) /* channel ประกาศโดยใช้คำว่า chan ประเภทของสิ่งที่จะส่งเข้าไปยัง channel สามารถระบุได้ว่า channel นี้จะให้ทำเฉพาะรับหรือส่ง func pinger(c chan<-string) คือ ทำได้แค่ส่งข้อความไปที่ c เท่านั้น func pinger(c <-chan string) คือ channel ที่ไม่ได้ระบุทิศทาง สามารถใช้ได้ทั้ง 2 ทิศทางทั...
package gameplay import ( "testing" "github.com/stretchr/testify/assert" ) func TestAddReview(t *testing.T) { var game GamePlay game.Players = make([]Player, 3) game.Players[0] = Player{ Name: "Todd", Uid: 1, Song: &Song{ Url: "https://mysong.url", Description: "Goodish song but not my fa...
package resourcetypes import ( "errors" ) func Destroy(id string) error { var exists bool for index, resourcetype := range mockResourceTypes { if resourcetype.ID == id { mockResourceTypes = append(mockResourceTypes[:index], mockResourceTypes[index+1:]...) exists = true } } if !exists { return error...
package helpers import ( "crypto/sha1" "encoding/hex" "path" "github.com/fd/forklift/util/user" ) func Path(ref string) (string, error) { sha := sha1.New() sha.Write([]byte(ref)) home, err := user.Home() if err != nil { return "", err } return path.Join(home, ".forklift", "deploypacks", hex.EncodeToStr...
package routes import ( "github.com/adamveld12/sessionauth" "github.com/go-martini/martini" ) func RegisterRoutes(app *martini.ClassicMartini) { app.Group("/", registerPageRoutes) app.Group("/api/v1", registerApiRoutes, sessionauth.LoginRequired) }
package cli import ( "fmt" "os" "github.com/irisnet/irishub/app/protocol" "github.com/irisnet/irishub/app/v1/service" "github.com/irisnet/irishub/client/context" "github.com/irisnet/irishub/client/utils" "github.com/irisnet/irishub/codec" sdk "github.com/irisnet/irishub/types" "github.com/spf13/cobra" "gith...
package main import ( "fmt" e "github.com/mzmico/mz/rpc_service" _ "github.com/mzmico/user-service/impls" ) func main() { s := e.Default() err := s.Run() if err != nil { fmt.Println(err) } }
/* The Chi-Squared (χ²) goodness of fit test estimates if an empirical (observed) distribution fits a theoretical (expected) distribution within reasonable margins. For example, to figure out if a die is loaded you could roll it many times and note the results. Because of randomness, you can't expect to get the same f...
package utils import ( "crypto/hmac" "crypto/sha256" "encoding/hex" ) // GenerateSha256 generate sha256 func GenerateSha256(key, data string) string { // Create a new HMAC by defining the hash type and the key (as byte array) h := hmac.New(sha256.New, []byte(key)) // Write Data to it h.Write([]byte(data)) // ...
package ipam import ( "fmt" "net" "reflect" "testing" "github.com/giantswarm/apiextensions/pkg/apis/provider/v1alpha1" "github.com/giantswarm/micrologger/microloggertest" ) func mustParseCIDR(val string) net.IPNet { _, n, err := net.ParseCIDR(val) if err != nil { panic(err) } return *n } func Test_sele...
package bob import ( "strings" ) // Hey triggers a response from Bob func Hey(s string) (response string) { s = strings.TrimSpace(s) isQuestion := strings.HasSuffix(s, "?") if len(s) == 0 { return "Fine. Be that way!" } else if isYelling(s) && isQuestion { return "Calm down, I know what I'm doing!" } else i...
package msg_queue import ( "github.com/nsqio/go-nsq" "time" "strings" "git.zhuzi.me/zzjz/zhuzi-bootstrap/lib/log" "os" "os/signal" "syscall" "sync" ) var producer *nsq.Producer var addrNsqLookups []string var logLevel nsq.LogLevel // 在调用Publish和Listen之前需要Init // addrNsqp: 单个nsq地址, addrNsqLookupp:lookup地址 可...
package seekbuf // TODO: test
package main import ( "fmt" "reflect" ) /* class Account<T>{ private T id; private int sum; Account(T id, int sum){ this.id = id; this.sum = sum; } public T getId() { return id; } public int getSum() { return sum; } public void setSum(int sum) { this.sum = sum; } } */...
package main import ( "archive/tar" "compress/gzip" "fmt" "io" "log" "os" "path/filepath" "strings" "github.com/spf13/cobra" ) var ( targzAbsPath string ) func main() { rootCmd := &cobra.Command{ Use: "app", } //tar subcommand var ( tarSource string tarTarget string ) tarCmd := &cobra.Command{...