text
stringlengths
11
4.05M
package TF2RconWrapper import ( "errors" "regexp" "time" ) const ( // "Username<userId><steamId><Team>" // "1<2><3><4>" <- regex group logLineStart = `^"(.*)<(\d+)><(\[U:1:\d+\])><(\w+)>" ` // "5" <- regex group logLineEnd = ` "(.*)"` logLineStartSpec = `^"(.*)<(\d+)><(\[U:1:\d+\])><(\w*)>" ` ) // regexes ...
package readAvaatechSpe import ( "errors" "os" "strings" ) func (spe *SPE) ParseFolder() error { var pathPts []string var pathLength int pathPts = strings.Split(spe.FilePath, string(os.PathSeparator)) pathLength = len(pathPts) if pathLength == 1 { spe.Folder = "Root" } else if pathLength == 2 { if string...
package model import ( "github.com/SDkie/metric_collector/db" "gopkg.in/mgo.v2/bson" ) //go:generate easytags metric_mongo.go json //go:generate easytags metric_mongo.go bson const METRIC_MONGO_COLLECTION = "metric_collector" type MetricMongo struct { Id bson.ObjectId `bson:"_id" json:"id"` MetricStru...
package main import "golang.org/x/tour/reader" type MyReader struct{} // TODO: Add a Read([]byte) (int, error) method to MyReader. func (mr *MyReader) Read(b []byte) (int, error) { count := 0 for i,_ := range b { if b[i] != byte('A'){ b[i] = byte('A') count++ } } return count, nil } func main() { r...
package sortedArrayToBST import ( "math" "testing" ) func Test_sortedArrayToBST(t *testing.T) { type args struct { nums []int } tests := []struct { name string args args }{ // TODO: Add test cases. { name: "first", args: args{ nums: []int{-10, -3, 0, 5, 9}, }, }, { name: "second", ...
package main import ( "fmt" //"time" ) func main() { c :=make(chan int) done :=make(chan bool) n:=2 for i:=0;i<n;i++{ go func() { for i := 0; i < 10; i++ { c <- i } done<-true }() } go func() { for i := 0; i < n; i++ { <-done } close(c) }() for n:=range c{ fmt.Println(n...
package main import ( "fmt" "time" ) //go 内置常用的时间常量. 无法使用 秒/1000 获取毫秒! func main() { now := time.Now() time.Sleep(time.Nanosecond * 100) //休眠100纳妙 time.Sleep(time.Microsecond * 100) //休眠100微妙 time.Sleep(time.Millisecond * 100) //休眠100毫秒 time.Sleep(time.Second * 100) //休眠100秒 time.Sleep(time.Minute * 10...
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0. package restore_test import ( "bytes" "fmt" "math" "math/rand" "testing" "time" "github.com/pingcap/errors" backuppb "github.com/pingcap/kvproto/pkg/brpb" "github.com/pingcap/tidb/br/pkg/conn" berrors "github.com/pingcap/tidb/br/pkg/errors" "githu...
package service import ( "context" "log" "time" ) type TimeServe struct { } func (timeServe *TimeServe) GetCurrtentTime(ctx context.Context) (r int32, err error) { currentTime := time.Now() log.Println("GetCurrtentTime() ") return int32(currentTime.Hour()), nil } func NewTimeServerHandle() *Tim...
package main import ( "github.com/cheikhshift/db" "fmt" "log" ) type MyObject db.MyObject func main() { dbs,err := db.Connect("localhost","database") if err != nil { log.Fatal(err) } fmt.Println("Save object") obj := MyObject{TestField:"second", FieldTwo: "Ivalud@update.com"} dbs.New(&obj) err = dbs....
package models import ( "log" "testing" "time" ) func TestTable(t *testing.T) { var table = NewTable() var s = struct { Topic string Channel string }{ "hello", "world", } log.Println(table.Get(s)) // var b = []struct { // Ip string // Httpport int // Tcpport int // }{ // { // "lo...
/* Computers live by binary. All programmers know binary. But the 2**x bases are often neglected as non-practical, while they have beautiful relations to binary. To show you one example of such a beatiful relation, 19 will be my testimonial. 19 10011 103 23 13 j 19 is decimal, included for clarity. 10011 is 19 in ...
package models import ( "time" "github.com/astaxie/beego/orm" ) type ReportRecord struct { RecordId int64 `orm:"pk;auto"` UserID string RecordInfo string RecordType int RecordTime time.Time } func init() { orm.RegisterModel(new(ReportRecord)) } func GetRecordByName(p_ID string, start int, end int) (...
package actions import ( "html/template" "log" "models" "testing" "time" ) func TestSavePost(t *testing.T) { x := models.Post{} x.Title = "This is title" x.Id = "761" x.Content = template.HTML(`<p><img src="http://bcs.duapp.com/huangj-in/images/IMG_1289.jpg" alt="编写可维护的 JavaScript 封面"></p><p>这本书不是工具书,他不像《Ja...
package generate_test import ( "os" "path/filepath" "runtime" "testing" rfc2119 "github.com/opencontainers/runtime-tools/error" "github.com/opencontainers/runtime-tools/generate" "github.com/opencontainers/runtime-tools/specerror" "github.com/opencontainers/runtime-tools/validate" "github.com/stretchr/testif...
package main import ( "fmt" "io/ioutil" "os" ) func main() { if len(os.Args) != 5 { fmt.Println(" bin_to_array package variable.name infile outfile ") return } pkg := os.Args[1] varname := os.Args[2] infile := os.Args[3] outfile := os.Args[4] data, err := ioutil.ReadFile(infile) if err != nil { fm...
package c16_cbc_bitflipping_attacks import ( "bytes" "github.com/vodafon/cryptopals/set2/c10_implement_cbc_mode" ) type Enc struct { key []byte head []byte tail []byte } func DefaultEnc(key []byte) Enc { return Enc{ key: key, head: []byte("comment1=cooking%20MCs;userdata="), tail: []byte(";comment2=%2...
package main import ( "fmt" "log" "os" "time" "github.com/faiface/beep" "github.com/faiface/beep/mp3" "github.com/faiface/beep/speaker" ) func main() { f, err := os.Open("../Miami_Slice_-_04_-_Step_Into_Me.mp3") if err != nil { log.Fatal(err) } streamer, format, err := mp3.Decode(f) if err != nil { ...
package main import ( "flag" "image" "image/png" "io" "log" "os" "github.com/yunomu/qrcode" ) var ( content = flag.String("content", "It will b file, tomorrow.", "QRcode content") logoFile = flag.String("logo", "", "logo file (PNG)") outFile = flag.String("o", "out.png", "outfile") ) func init() { flag...
package entity import ( "errors" "github.com/sirupsen/logrus" ) //ErrNotFound not found var ErrNotFound = errors.New("Not found") // Op A unique string operation pointing to a function // Multiple operations can construct a friendly stack trace. type Op string // Kind category of the error type Kind int const (...
package main // 递归 + 位运算 实现加法 func getSum(a int, b int) int { sum, carry := a^b, (a&b)<<1 if carry == 0 { return sum } return getSum(sum, carry) } // 迭代 + 位运算 实现加法 func getSum(a int, b int) int { for { num1 := (a & b) << 1 num2 := a ^ b if num1 == 0 { return num2 } a, b = num1, num2 } } /* 题目链接...
package main import ( "flag" "fmt" "os" "google.golang.org/grpc" "example.com/pkg/example" ) var address string var port int var command string var filter string var data string func main() { flag.StringVar(&address, "address", "127.0.0.1", "The service server address to connect to, default address is 127.0...
// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris package main import ( "io" "net" "os" ) func sendfile(c *net.TCPConn, f *os.File, fi os.FileInfo) { io.Copy(c, f) }
package controllers import ( "net/http" apiRequest "github.com/alexhornbake/go-crud-api/lib/api_request" apiResponse "github.com/alexhornbake/go-crud-api/lib/api_response" models "github.com/alexhornbake/go-crud-api/models" schemas "github.com/alexhornbake/go-crud-api/schemas" ) func showUser(w http.ResponseWri...
package app import ( "encoding/gob" "html/template" "log" "net/http" "os/exec" "path/filepath" "strings" ) type LoginTemplate struct { Msg string Type string } type IndexTemplate struct { CsvFiles []string } var Templates *template.Template func init() { ReloadTemplates() gob.Register(LoginTemplate{}...
package pipeline import ( "context" "fmt" ) // Print prints w.in and repalys it // on w.out func (w *Worker) Print(ctx context.Context) { for { select { case <-ctx.Done(): return case val := <-w.in: fmt.Println(val) w.out <- val } } }
package common import "fmt" func PrintGreeting(name string) { fmt.Printf("hello,%s\n",name) } func PrintPassed(passed bool) { if passed { fmt.Println("congratulations,you passed the exam!") } else { fmt.Println("sorry,you failed to pass the exam!") } } func PrintAverageScore(averageScore float64) { fmt.Pri...
/* Bridge 桥接模式: 将抽象部分与它的实现部分分离,使它们都可以独立地变化 个人想法:组合/聚合复用原则 作者: HCLAC 日期: 20170306 */ package bridge import ( "fmt" ) type Person interface { SetCloth(c Clothes)error Dress()error Undress()error } type Worker struct{ cloth Clothes name string } func NewWorker() Person{ p := Worker{} p.name ...
package main import ( "fmt" "runtime" ) func main() { fmt.Println(runtime.NumCPU()) //fmt.Println(runtime.CPUProfile()) n := runtime.GOMAXPROCS(2) fmt.Println(n) for { go fmt.Print(0) //子 fmt.Print(1) //主 } }
package libs // https://github.com/google/re2/wiki/Syntax const ( EmailPattern = `^[a-zA-Z0-9.!#$%&'*+\/=?^_`+"`"+`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$` UsernamePattern = `^[[:alpha:]]{1}[[:word:]]{3,16}$` )
package dht type Peer struct { ID ID Addr string } type Peers map[ID]*Peer func NewPeers(items ...*Peer) Peers { ps := Peers{} for _, item := range items { ps[item.ID] = item } return ps } func (ps Peers) Keys() IDList { result := IDList{} for id, _ := range ps { result = append(result, id) } return...
package util import ( "log" ) func CheckErr(err error) { if err != nil { log.Panicln(err) } }
// Copyright 2013-2014 go-diameter authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package diam import ( "errors" "reflect" ) // Unmarshal stores the result of a diameter message in the struct // pointed to by dst. // // Unmarsh...
package models import ( . "asdf" "github.com/astaxie/beego/logs" ) func init() { logInit() radParamInit() dbInit() aliveInit() } func logInit() { log.log = logs.NewLogger(10000) log.log.SetLogger("console", "") // use file SetLogger(&log) }
// Copyright 2016 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 main import ( "flag" "github.com/electroprovodka/loadbalancer/config" "github.com/electroprovodka/loadbalancer/proxy" log "github.com/sirupsen/logrus" ) func parseFlags() string { var config string flag.StringVar(&config, "config", "", "path to the proxy config") flag.Parse() if config == "" { log....
package git import ( "bytes" "fmt" "io" "os/exec" "strings" ) // Do does git given git command with params func Do(command string, params ...string) (io.Reader, error) { commandLine := strings.Join(append([]string{"git", command}, params...), " ") cmd := exec.Command("git", append([]string{command}, params...)...
package registry import ( "encoding/json" "io/ioutil" "path/filepath" "github.com/ghodss/yaml" ) const ( defaultCacheTtlSeconds = 600 ) type RepoConfig struct { // Feast project name Project string `json:"project"` // Feast provider name Provider string `json:"provider"` // Path to the registry. Custom re...
package types import "time" type CalculateRequest struct { StartLat float64 `json:"start_lat"` StartLong float64 `json:"start_long"` EndLat float64 `json:"end_lat"` EndLong float64 `json:"end_long"` } type CalculateResponse struct { Distance int64 `json:"distance"` Duration int64 `json:"duration"` Err...
package main import ( "bufio" "fmt" "os" ) var hIndex int var vIndex int func main() { filePath := os.Args[1] file, _ := os.Open(filePath) defer file.Close() reader := bufio.NewReader(file) scanner := bufio.NewScanner(reader) deliveryMap := make(map[int]map[int]int) //deliveryMap := make([]map[int]in...
package identity import ( "fmt" "log" "net/http" "os" "testing" "github.com/databrickslabs/databricks-terraform/common" "github.com/databrickslabs/databricks-terraform/internal/qa" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/stretchr/testify/assert" ) func TestScimUserAPI_Creat...
package socks import ( "context" "encoding/binary" "io" "net" "github.com/cybozu-go/log" "github.com/cybozu-go/well" ) func (s *Server) handleSOCKS4(ctx context.Context, conn net.Conn, cmdByte byte) net.Conn { var responseData [8]byte responseData[1] = byte(Status4Rejected) fields := well.FieldsFromContext(...
package packages import ( "context" "github.com/profzone/eden-framework/pkg/courier" "github.com/profzone/eden-framework/pkg/courier/httpx" ) func init() { Router.Register(courier.NewRouter(CreatePackageTemplate{})) } // 创建导出任务 type CreatePackageTemplate struct { httpx.MethodPost } func (req CreatePackageTempl...
package main import ( "encoding/json" "fmt" "io/ioutil" "math/rand" "net" "net/http" "strings" ) type App struct { Service string `json:"service"` Host string `json:"host"` IP string `json:"ip"` Port string `json:"port"` } func GetEndpoint(name string) []App { reader := strings.NewReader("") ...
package main import ( "manga-api/httpd/handler" "github.com/gin-gonic/gin" ) func main() { defer handler.Db.Close() router := gin.Default() router.GET("/", handler.RefAllMangas()) router.GET("/release/:title", handler.RefSpecifiedManga()) router.Run() }
/** * Author: Admiral Helmut * Created: 12.06.2019 * * (C) **/ package classes type AnalysisTool struct { analysisTool_id int `db:"analysisTool_id"` name string `db:"name"` executionString string `db:"executionString"` } func NewAnalysisTool(analysisTool_id int, name string, executionString string) *Ana...
package main import ( "fmt" "unicode" "unicode/utf8" ) func squashSpace(bs []byte) []byte { var isLastSpace bool i, j := 0,0 for j < len(bs) { r, s := utf8.DecodeRune(bs[j:]) if unicode.IsSpace(r) { if !isLastSpace { bs[i] = ' ' i++ isLastSpace = true } } else { isLastSpace = false ...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-01-03 13:29 # @File : coincc.go # @Description : # @Attention : */ package coincc import ( "fmt" "github.com/hyperledger/fabric/core/chaincode/shim" "github.com/hyperledger/fabric/protos/peer" ) type CoinCC struct { } func (c *CoinCC) Init(stub shim.C...
// 1.题目描述 // 2.算法实现 // 2.1 算法思路 /* 解题思路 ![每一项分为计数和数字两部分](https://pic.leetcode-cn.com/e4d0e2acba7004bc831af05e0f62a10e63f317c8b1c7754fc5bf3fd8bbbe38f5-image.png) 根据题目,可以理解为每个N值都会分解为以1和2为元素的字符串序列,其每一项的值都可以划分为count+num 全部思路如下 1.递归(如果迭代请绕道) 2.找到最底层即n=1返回本身:"1" 3.有了这个"1" 开始递归下面一层,即设定一个count=1(因为第一层已经有了一个1) 4.循环,条件...
/* Copyright 2020 The Qmgo 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, sof...
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package i18n //go:generate go-bindata -nometadata -nocompress -pkg $GOPACKAGE -prefix ../../ -o translations_generated.go ../../translations/... //go:generate gofmt -s -l -w translations_generated.go // resourceloader use ...
package memcache import ( "fmt" "testing" ) func Test_consistentHash_Init(t *testing.T) { var h consistentHash for replicasCount := 1; replicasCount <= 1000; replicasCount *= 10 { for bucketsCount := 1; bucketsCount <= 1000; bucketsCount *= 10 { h.ReplicasCount = replicasCount h.BucketsCount = bucketsCoun...
package rhel84 import ( "encoding/json" "fmt" "math/rand" "path/filepath" "github.com/osbuild/osbuild-composer/internal/crypt" "github.com/osbuild/osbuild-composer/internal/distro" osbuild "github.com/osbuild/osbuild-composer/internal/osbuild2" "github.com/osbuild/osbuild-composer/internal/blueprint" "githu...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //675. Cut Off Trees for Golf Event //You are asked to cut off trees in a forest for a golf event. The forest is represented as a non-negative 2D map, ...
// Copyright 2019 Kuei-chun Chen. All rights reserved. package analytics import ( "errors" "io/ioutil" "os" "strings" "time" ) func getFilenames(filenames []string) []string { var err error var fi os.FileInfo fnames := []string{} for _, filename := range filenames { if fi, err = os.Stat(filename); err != ...
package execute import ( "PrincessMononoke/models" "fmt" "strings" "testing" ) func TestVerifyJSON(t *testing.T) { s, e := VerifyJSON(`$.data==2 && ($.items[0].name=="test" || $.items[1].value==true)`, `{"data":2,"items":[{"name":"test"},{"value":true}]}`) if e != nil { t.Fatal(e) } if s != true { t.Fatal...
package pool import ( "errors" "testing" ) func TestPool_AddingAfterShutdown(t *testing.T) { t.Run("Adding on Shutdown", func(t *testing.T) { // chWait := make(chan struct{}) p := New(1) p.Shutdown() xid, err := p.Add(func(taskID string) error { // <-chWait return nil }) if xid != "" { t.E...
package onvif import ( "fmt" "log" "testing" ) func TestGetProfiles(t *testing.T) { log.Println("Test GetProfiles") res, err := testDevice.GetProfiles() if err != nil { t.Error(err) } js := prettyJSON(&res) fmt.Println(js) } func TestGetStreamURI(t *testing.T) { var res MediaURI log.Println("Test Ge...
package imap import ( "crypto/tls" "fmt" "time" db "../db" . "github.com/logrusorgru/aurora" ) const ( port = ":993" ) // Envelope - struct for data from envelope of mails type Envelope struct { Date string Subject string Sender string Email string Seen bool UID int } // Letter - struct wh...
package cmd import ( "fmt" "os" "github.com/spf13/cobra" ) var version = "dev" // VakuCmd is the root command for the Vaku CLI var VakuCmd = &cobra.Command{ Use: "vaku", Short: "Vaku CLI extends the official Vault CLI with useful high-level functions", Long: `Vaku CLI extends the official Vault CLI with use...
package main import ( "bytes" "encoding/json" "io/ioutil" "log" "net/http" "os" "time" ) func main() { if len(os.Args) != 3 { log.Fatal("usage: standard-backup hostname credentials.json") } creds, err := ioutil.ReadFile(os.Args[2]) if err != nil { log.Fatal(err) } hc := &http.Client{Timeout: 60 * ti...
package method import ( "strings" "github.com/bot/myteambot/app/utility" "github.com/bot/myteambot/app/utility/repository" ) // AddGroup _ func AddGroup(chatID int64, name string) { repository.UpsertGroup(chatID, name) } // SendChatSpecificGroup _ func SendChatToSpecificGroup(args string) (string, string) { if...
/* Copyright 2022 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 controller import ( "net/http" "sample.com/book/util" ) func end(rw http.ResponseWriter, r *http.Request) { util.EndNormal(rw, http.StatusServiceUnavailable, nil) } func GetAllCustomers(rw http.ResponseWriter, r *http.Request) { end(rw, r) } func GetCustomer(rw http.ResponseWriter, r *http.Request) { ...
package protoform import ( "io/ioutil" "path/filepath" "testing" ) func Test_safe(t *testing.T) { src := Load(filepath.Join("testdata", "A.java")) expected := true _ = classExtracter.defaultFind(src) actual := classExtracter.safe() if expected != actual { t.Fail() } } func Test_defaultFind(t *testing.T) {...
package api import ( "encoding/json" "github.com/labstack/echo" "main/model" "net/http" "strconv" ) func GetAll() echo.HandlerFunc { return func(c echo.Context) error { tasks := model.Tasks{} tasks = model.TaskAll(model.CurrentUser.Id) resJson, err := json.Marshal(tasks) if err != nil { return c.S...
package security import ( "bufio" "fmt" "io/ioutil" "net/http" "os" "os/exec" "sort" "strings" "testing" "time" "github.com/google/uuid" "github.com/zaddok/log" ) // Fully replace contents of the destination array with the source array func TestSyncKeyValueList(t *testing.T) { src := []*KeyValue{ &Ke...
package main type Elems []Elem type PtrElems []*Elem type Elem struct { K string V int } type HugeElem [1024]byte type HugeElems []HugeElem type HugePtrElems []*HugeElem func newSlice() Elems { return Elems{ {"A", 1}, {"B", 2}, {"C", 3}, {"D", 4}, {"E", 5}, {"F", 6}, {"G", 7}, {"H", 8}, {"J"...
package main import ( "bufio" "encoding/json" "fmt" "log" "mime/multipart" "net/http" "strconv" ) type Day struct { Date string `json: "date"` ElevenAM float32 `json: "ElevenAM"` Noon float32 `json: "noon"` OnePM float32 `json: "onePM"` TwoPM float32 `json: "twoPM"` ThreePM float32 `json: "threePM"`...
package lib import "time" // The Game stores the game state so it can be easily passed around. type Game struct { Level *Map Player *Player UI *UI LastMove time.Time } // Render renders the game to termbox func (g *Game) Render() { g.Level.Render(2, 1) g.Player.Render(2, 1) g.UI.Render(100, 1) }
package main import ( "fmt" "os" "path/filepath" "strings" "github.com/raedahgroup/dcrcli/cli" "github.com/raedahgroup/dcrcli/walletrpcclient" "github.com/raedahgroup/dcrcli/web" ) type Version struct { Major, Minor, Patch int Label string Nick string } var Ver = Version{ Maj...
package main import ( "context" "encoding/json" "github.com/b2wdigital/goignite/pkg/config" "github.com/b2wdigital/goignite/pkg/health" "github.com/b2wdigital/goignite/pkg/log" "github.com/b2wdigital/goignite/pkg/log/logrus/v1" "github.com/b2wdigital/goignite/pkg/transport/client/gocql/v0" ) func main() { c...
package main import ( "fmt" "log" "strings" ) func itowords(n int) string { if n > 1000 { log.Fatal(n, "is larger than 1000") } table := map[int]string{ 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine", 10: "ten"...
/* Given a string, return a string where for every char in the original, there are two chars. */ package main import ( "fmt" ) func double_char(s string) string { t := make([]byte, len(s)*2) for i, y := 0, 0; i < len(s); i, y = i+1, y+2 { t[y] = s[i] t[y+1] = s[i] } return string(t) } func main(){ var stat...
package requests import "time" type CreateKeyEvent struct { EventDate time.Time } type UpdateKeyEvent struct { EventDate time.Time } func (c *CreateKeyEvent) Valid() error { return validate.Struct(c) } func (c *UpdateKeyEvent) Valid() error { return validate.Struct(c) }
package zedUpload_test import ( "crypto/md5" "encoding/hex" "fmt" "io" "io/ioutil" "math/rand" "net" "os" "strconv" "strings" "sync" "time" ) const ( // global parameters uploadDir = "./test/input/" uploadFile = "./test/input/zedupload_test.img" uploadFileSmall = "./test/input/zedupload_tes...
package regression import ( "math" ) type Linear struct { Slope float64 Intercept float64 R2 float64 } func LinearFit(x []float64, y []float64) *Linear { var sumX, sumY, sumXX, sumXY, sumYY float64 var aveX, aveY, nFlt float64 var Sxx, Syy, Sxy float64 var slope, intercept, r, r2 float64 var line...
package home import ( "html/template" "net/http" "appengine" "appengine/datastore" "appengine/user" ) type User struct { Email string LoggedIn bool } func init() { http.HandleFunc("/", root) } func root(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) u := user.Current(c) ud := ...
package slice import ( "bytes" "context" "errors" "fmt" "github.com/ns1/jsonschema2go/internal/validator" "github.com/ns1/jsonschema2go/pkg/gen" "net/url" "sort" "strconv" ) //go:generate go run ../cmd/embedtmpl/embedtmpl.go slice slice.tmpl tmpl.gen.go // Build attempts to generate the plan for a slice fro...
package cmd import ( "fmt" "io/ioutil" "os" "runtime" "strings" "github.com/zquestz/visago/util" "github.com/zquestz/visago/visagoapi" "github.com/asaskevich/govalidator" "github.com/spf13/cobra" ) const ( appName = "visago" version = "0.3.2" ) // Stores configuration data. var config Config // FilesCm...
package azure import ( "testing" "github.com/stretchr/testify/assert" "github.com/openshift/installer/pkg/types/azure" ) func TestCloudProviderConfig(t *testing.T) { config := CloudProviderConfig{ CloudName: azure.PublicCloud, ResourceGroupName: "clusterid-rg", GroupLocation: ...
// Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 package wasmlib type MapKey interface { KeyId() Key32 } type Key string func (key Key) KeyId() Key32 { return GetKeyIdFromString(string(key)) } type Key32 int32 func (key Key32) KeyId() Key32 { return key } // \\ // \\ // \\ // \\ // \\ //...
package main import ( "os/exec" "fmt" "bytes" "io/ioutil" "os" "encoding/base64" "github.com/davecgh/go-spew/spew" ) func main() { //r := gin.Default() // //routes.InitRoutes(r) // //r.Run(":9000") // listen and serve on 0.0.0.0:9000 pdfNames := "test.pdf" pdfSecoundsNames := "A" + pdfNames pdfPasswor...
package metrics import ( "plugins" ) // CPU Status for Linux based machines // // DESCRIPTION // This plugin gets the load average and reports it in graphite line format // // OUTPUT // Graphite plain-text format (name value timestamp\n) // // PLATFORMS // Linux type LoadStats struct{} func init() { plugins....
package helper import ( "io" "os" "path" ) // CreateFakeFile ... func CreateFakeFile(fileName string, fileType string) error { var fileExtension string var targetFileDirectory string switch fileType { case "pdf": fileExtension = "pdf" targetFileDirectory = "documents" case "image": fileExtension = "png"...
package generators import ( "github.com/almerlucke/kallos/generators/tools" "github.com/almerlucke/kallos" ) // Ramp generator wraps a ramp type Ramp struct { ramp *tools.Ramp isContinuous bool done bool } // NewRamp initializes a new ramp func NewRamp(ramp *tools.Ramp, isContinuous bool) *Ramp...
package reda import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document06100101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:reda.061.001.01 Document"` Message *NettingCutOffReferenceDataReportV01 `xml:"NetgCutOffRefDataRpt"` } f...
package store_test import ( "context" "io/ioutil" "os" "testing" "time" "github.com/stretchr/testify/require" "github.com/uw-labs/broximo/store" ) func TestBadgerStore_TopicStore(t *testing.T) { t.Parallel() dbPath, err := ioutil.TempDir("", "commission-test-badger") require.NoError(t, err) defer os.Remo...
package v1 import ( "bytes" "context" "fmt" "strings" "sync" "github.com/go-task/task/v2/internal/compiler" "github.com/go-task/task/v2/internal/execext" "github.com/go-task/task/v2/internal/logger" "github.com/go-task/task/v2/internal/taskfile" "github.com/go-task/task/v2/internal/templater" ) var _ compi...
package server import ( "github.com/rs/xid" "io" "net" "sync" ) type PublicConn struct { Id string Conn net.Conn ProxyConnChan chan net.Conn pubLock sync.RWMutex proxyLock sync.RWMutex } func (pubConn *PublicConn) Pipe(conn net.Conn) { defer conn.Close() defer pubConn.Conn.Close() var wait sync.WaitGro...
package main import ( "fmt" "net/http" "github.com/mitchellh/mapstructure" "time" ) type Message struct { Name string `json:"name"` Data interface{} `json:"data"` } type Channel struct { Id string `json:"id"` Name string `json:"name"` } func main() { router := NewRouter() router.Handle("channel add",...
package monitors import ( "log" "net/http" ) func httpMonitor(url string, expectation int) bool { resp, err := http.Get(url) if err != nil { log.Println(err) return false } if resp.StatusCode != expectation { return false } return true }
package main import ( "fmt" ) func main() { ch := make(chan string, 1) ch <- "world" mock := make(chan string, 1) mock <- "hello" var chp *chan string chp = &mock fmt.Printf("len: *chp=%v, ch=%v\n", len(*chp), len(ch)) for len(*chp)+len(ch) != 0 { select { case s := <-*chp: fmt.Println("pointa:", s)...
// Copyright (C) 2022 Cisco Systems 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 agr...
package handlers import ( "context" "io" "log" "net/http" "time" ) // MakeExternalAuthHandler make an authentication proxy handler func MakeExternalAuthHandler(next http.HandlerFunc, upstreamTimeout time.Duration, upstreamURL string, passBody bool) http.HandlerFunc { return func(w http.ResponseWriter, r *http.R...
// 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 controller import ( "fmt" "golang-distributed-parallel-image-processing/api/helpers" "golang-distributed-parallel-image-processing/models" "os" "strconv" "strings" "time" "go.nanomsg.org/mangos" // register transports "go.nanomsg.org/mangos/protocol/surveyor" _ "go.nanomsg.org/mangos/transport/all...
package posthttpport_test import ( "encoding/json" "net/http" "testing" "github.com/alejogs4/blog/src/post/domain/like" "github.com/alejogs4/blog/src/post/domain/post" ) func TestUnitCreatePostControllerUnit(t *testing.T) { t.Run("Should return a bad request code if there are missing field", func(t *testing.T...
package main import "strconv" /** 257. 二叉树的所有路径 给定一个二叉树,返回所有从根节点到叶子节点的路径。 说明: 叶子节点是指没有子节点的节点。 示例: ``` 输入: 1 / \ 2 3 \ 5 输出: ["1->2->5", "1->3"] 解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3 ``` */ /** Error */ /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeN...
package lambdacalculus import ( "testing" ) func TestFlip_with_Pow(t *testing.T) { res := Flip(Pow)(four)(three).(xl)(f)(x) if res != 64 { t.Errorf("Power of four to three should be 64 instead is %v", res) } } func TestConstant(t *testing.T) { c := Constant(1) res := c(Succ(Zero)) if res != 1 { t.Errorf("...