text
stringlengths
11
4.05M
package controllers import ( "github.com/w2hhda/candy/models" "github.com/astaxie/beego" "encoding/json" ) type CandyController struct { BaseController } func (c *CandyController) URLMapping() { c.Mapping("ListAllCandyCountAndGame", c.ListAllCandyCountAndGame) c.Mapping("ListCandyPage", c.ListCandyPage) } // ...
package life import ( "math/rand" ) func RandomValue(x, y int) int { return rand.Intn(2) }
package sandbox // @class Square // This is Square, it operates on int32 and can compute areas type Square struct { // Internal width value width int32 // Internal height value height int32 } // Constructor which creates a square by taking two values in // @param width The width value // @param height The height...
package 一维数组 import "fmt" // ------------------------------------------ 1. 滑动窗口(开始) ------------------------------------------ // INF 无穷大。 const INF = 10000000000 // minSubArrayLen 获取最短的子数组,满足数和大于 target。 func minSubArrayLen(target int, nums []int) int { // 1. 异常返回。 if len(nums) == 0 { panic("题目出错") } // 2. ...
package use import ( "github.com/devspace-cloud/devspace/cmd/flags" "github.com/devspace-cloud/devspace/pkg/devspace/config/loader" "github.com/devspace-cloud/devspace/pkg/util/factory" "github.com/devspace-cloud/devspace/pkg/util/survey" "github.com/mgutz/ansi" "github.com/pkg/errors" "github.com/spf13/cobra"...
package main import ( "fmt" "os" "strconv" "github.com/fjukstad/scratch" ) func main() { id := "86536890" p, err := scratch.GetProject(id) fmt.Println(p, err) tags := []string{"kodeklubbentromso", "tromso"} projects := []*scratch.Project{} for _, tag := range tags { ps, err := scratch.GetProjects(tag)...
package proto import ( "github.com/qianguozheng/goadmin/model" ) type ConfigRead struct { Cmd string `json:"cmd"` SeqId string `json:"seqId"` Code string `json:"code"` Data ConfigReadCore `json:"data"` } type ConfigReadCore struct { Mode int `json:"mode"` CC CloudConfig ...
package main import ( "encoding/json" "flag" "fmt" "io/ioutil" "net/http" "net/url" "os" "time" "github.com/mmcdole/gofeed" ) const pushoverURL = "https://api.pushover.net/1/messages.json" const envToken = "PUSHOVER_RSS_TOKEN" const envUser = "PUSHOVER_USER" const envData = "FEED_DATA" const defaultData =...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //451. Sort Characters By Frequency //Given a string, sort it in decreasing order based on the frequency of characters. //Example 1: //Input: //"tree" ...
package field import ( "encoding/binary" "fmt" "io" ) // Header is a data structure that contains details about the following field in // the ADAT chunk, in the Serato session file. type Header struct { Identifier uint32 Length uint32 } func (h *Header) String() string { return fmt.Sprintf("field (%d) leng...
package mergetwosortedlists import ( "testing" "github.com/stretchr/testify/assert" ) func TestMergeTwoLists(t *testing.T) { must := assert.New(t) cases := []struct { NumNode1 *ListNode NumNode2 *ListNode Expect *ListNode }{ { NumNode1: &ListNode{Val: 1, Next: &ListNode{Val: 2, Next: &ListNode{Val...
package blockchain import ( "github.com/stretchr/testify/assert" "golang-blockchain/testutils" "testing" ) func TestGenesisBlockHasHeightOfZero(t *testing.T) { cbtx := CoinbaseTx(testutils.RandomAddress(), genesisData) block := Genesis(cbtx) assert.Equal(t, block.Height, 0) } func TestGenesisBlockContainsNoPr...
package main import ( "github.com/FourLineCode/financer/internal/config" "github.com/FourLineCode/financer/pkg/server" ) func main() { config := config.GetConfig() server := server.New(config) server.Run(config.Port) }
package psql import "github.com/Mrcampbell/pgo2/protorepo/pokemon" func Filter(bm []*pokemon.BreedMove, f func(*pokemon.BreedMove) bool) []*pokemon.BreedMove { bmf := make([]*pokemon.BreedMove, 0) for _, m := range bm { if f(m) { bmf = append(bmf, m) } } return bmf }
package main import ( "fmt" ) func main() { chanDemo2() } type worker1 struct { in chan int done chan bool } func chanDemo2() { var workers [10]worker1 for i := 0; i < 10; i++ { workers[i] = createWorker1(i) } for i, worker := range workers { //workers[i].in <- i worker.in <- 'A' + i } for i, wo...
package main import "fmt" /* The obligatory Hello World example. run this with > go run 01_helloworld.go or, compile it and run the binary: >go build 01_helloworld.go > 01_helloword */ func main() { fmt.Println("Hello Gareth, you little 壹 壱") } /* the package main is special. It defines a stabdalone executabl...
package main import "fmt" func main() { for count := 10; count > 0; count-- { fmt.Println("T minus", count) } fmt.Println("Liftoff!") for count := 1; count <= 10; count++ { fmt.Println("T plus", count) } }
package main import ( "fmt" "github.com/astaxie/beego/config" ) func main(){ conf,err:=config.NewConfig("ini","./Web/logrecord/config/logagent.conf") if err!=nil{ fmt.Println("new config err",err) return } port,err:=conf.Int("server::listen_port") if err!=nil{ fmt.Println("conf int err",err) return } ...
// SPDX-License-Identifier: Apache-2.0 // Copyright (c) 2020 Intel Corporation package v1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. ty...
package common type InputMsg struct { EnterpriseCode string `json:"enterpriseCode"` }
// Fibonacci example to measure performance between different calls //go:generate dllcall -fast -keep fibon_if.go fibonlib/fibon_if.h package main import ( "errors" "flag" "fmt" "log" "os" "strconv" "strings" "time" ) var count int func main() { flag.IntVar(&count, "count", 1, "Number of iterations") flag...
package main import "fmt" func main() { count := 1 for ; count < 100; count++ { count++ } fmt.Println("count is", count) }
package main import ( "fmt" "github.com/gomodule/redigo/redis" "github.com/qingwenjie/goredis" ) func main() { options := &goredis.Options{ Protocol: "tcp", Addr: "127.0.0.1:6379", Password: "123456", Database: 1, } conn := goredis.Connect(options) reply, err := conn.Do("SELECT", 1) fmt.Println(re...
package http_handlers import ( "fmt" "github.com/go-martini/martini" "net/http" ) func GetCaches() func( martini.Context, martini.Params, http.ResponseWriter, *http.Request, ) { return HttpHandler( []string{ AUTH_REQUIRED, }, func(h *Http) { h.SetResponse( h.session.Caches, ) }, ) } fun...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //114. Flatten Binary Tree to Linked List //Given a binary tree, flatten it to a linked list in-place. //For example, given the following tree: // 1...
package memory import ( "github.com/DoraALin/go-config/source" "context" ) type dataKey struct{} // WithData allows the source data to be set func WithData(d []byte) source.Option { return func(o *source.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o....
package controllers import ( "encoding/json" "fmt" "github.com/astaxie/beego" "io/ioutil" "onework/models" ) type MainController struct { beego.Controller } func (c *MainController) Get() { //1.获取请求数据 name:=c.Ctx.Input.Query("name") //或者用c.GetString() age:=c.Ctx.Input.Query("age") //2.使用固定数据进行数据校验 if n...
package main import ( "flag" "fmt" "net/http" "os" "runtime" "file-upload-srv/config" "file-upload-srv/router" "github.com/facebookgo/grace/gracehttp" "github.com/gin-gonic/gin" "github.com/go-xweb/log" "github.com/spf13/viper" ) var ( c string ) func init() { flag.StringVar(&c, "c", "dev", "配置文件") r...
package main import ( "fmt" "log" "os" ) func main() { stat() fmt.Println("=======================") lstat() } func stat() { //fInfo, err := os.Stat("D:\\workspace\\备忘.txt") //原文件 fInfo, err := os.Stat("C:\\Users\\kc\\Desktop\\备忘.lnk") //快捷方式 if err != nil { log.Fatalln(err) } fmt.Printf("Name: %s\n", f...
package events import ( "context" "fmt" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNewReceiver(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) user, err := NewReceiver(ctx, "mock", "cloud") require.NoError(t, err) user.in...
package metadata import ( "strconv" "incognito-chain/common" ) // UnStakingMetadata : unstaking metadata type UnStakingMetadata struct { MetadataBaseWithSignature CommitteePublicKey string } func (meta *UnStakingMetadata) Hash() *common.Hash { record := strconv.Itoa(meta.Type) data := []byte(record) hash := ...
/* This is "programming" at its most fundamental. Build a diagram of (two-wire) NAND logic gates that will take the input wires A1, A2, A4, A8, B1, B2, B4, B8, representing two binary numbers A to B from 0 to 15, and return values on the output wires C1, C2, C4, and C8 representing C, which is the sum of A and B modu...
package main import ( "context" "fmt" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattrib...
package main import "fmt" func perbandingan(a, b int) string { if a < b { return "a lebih kecil dari b" } return "b lebih kecil dari a" } func main(){ fmt.Println(perbandingan(10,5)) }
package lambdacalculus import ( "testing" ) func TestIsEmptyWithEmpty(t *testing.T) { res := IsEmpty(EmptyList)(true)(false) if !res.(bool) { t.Errorf("The empty list should be empty instead is %v", res) } } func TestValueOfEmpty(t *testing.T) { val := ListElementVal(EmptyList) res := IsEmpty(val.(List))(true...
package main import ( "testing" ) func TestRandomBalancer(t *testing.T) { b1 := NewBackend("192.168.1.1:80", 5) b2 := NewBackend("192.168.1.2:80", 1) b3 := NewBackend("192.168.1.3:80", 1) // no backends balancer := NewRdm() _, found := balancer.Select() if found { t.Error("no backend should found!") } /...
package aiven import ( "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/terraform" "github.com/stretchr/testify/assert" "os" "reflect" "testing" "time" ) var ( testAccProviders map[string]terraform.ResourceProvider testAccProvider *schema.Provider ) func ...
package main import ( jwt "github.com/dgrijalva/jwt-go" "go.mongodb.org/mongo-driver/bson/primitive" ) type Assignment struct { Name string `bson:"name,omitempty"` Filename string `bson:"filename,omitempty"` Deadline string `bson:"deadline,omitempty"` } type Batch struct { ID primitive.ObjectID `b...
package decompress_run_length_encoded_list func decompressRLElist(nums []int) []int { var i, length = 0, len(nums) var values []int for i < length { for j := nums[i]; j > 0; j-- { values = append(values, nums[i+1]) } i += 2 } return values }
package bench import ( "database/sql" "log" _ "github.com/mattn/go-sqlite3" ) const Text = "N769r32BAkaQj6uzZQA6IsFICROqZEA3OOXFhn8" //rnhFluvqPAl4L7VHr0yFk0O3DWSY7k //4d7QwVbA8Sim6ZijqeEPdMr71XXRVpAi6amGvfT3HayxcZK UflRnZw1xShTJwyn395RU92dpgKO9Nl3IJCdpJogUww06j18QWeZJ8NmiSXxhMldc28mXjbx0TsL6agsfT4c0Fny6fEDwZMv38...
package server import ( "reflect" "testing" ) func TestRouteConfig(t *testing.T) { opts, err := ProcessConfigFile("./configs/cluster.conf") if err != nil { t.Fatalf("Received an error reading route config file: %v\n", err) } golden := &Options{ Host: "0.0.0.0", Port: 4222, U...
package main import ( "fmt" "github.com/YarkoL/GoTraining/04_scope/vis" ) var x int = 42 func main() { fmt.Println(x) foo() bar() bar() inc := wrapper() fmt.Println(inc()) fmt.Println(inc()) //fmt.Println(wrapper()) //prints the address //fmt.Println(inc) //same as above baz() } func foo() { fmt.Print...
package main import ( "fmt" "github.com/askovpen/goated/pkg/areasconfig" "github.com/askovpen/goated/pkg/config" "github.com/askovpen/goated/pkg/ui" "github.com/askovpen/gocui" "log" "os" "time" ) func main() { log.Printf("%s started", config.LongPID) if len(os.Args) == 1 { log.Printf("Usage: %s <config.y...
package client import ( "errors" "fmt" "github.com/slince/spike-go/event" "github.com/slince/spike-go/log" "github.com/slince/spike-go/protol" "github.com/slince/spike-go/tunnel" "net" "runtime" ) // 初始化常量 const ( Version = "0.0.1" EventClientInit = "init" EventClientStart = "start" EventMessage = "messag...
package plndrcp import ( "context" "fmt" "github.com/plunder-app/plndr-cloud-provider/pkg/ipam" v1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" cloudprovider "k8s.io/cloud-provider" "k8s.io/klog" ) type plndrServices struct { Services []services `json:"services"` } type services struct { Vip ...
package main import ( "html/template" "log" "net/http" ) var tmpl = template.Must(template.ParseFiles("templates/index.html")) func main() { http.HandleFunc("/", indexHandler) http.ListenAndServe(":8080", nil) } func indexHandler(w http.ResponseWriter, r *http.Request) { type Hoge struct { Name string Sc...
package main import ( "flag" "fmt" _ "image/jpeg" _ "image/png" "log" "github.com/sshsmz/grcode" ) //go build -ldflags "-linkmode external -extldflags -static" func main() { flag.Parse() //log.SetFlags(0) if len(flag.Args()) < 1 { log.Fatal("Need specify the image file") } filePath := flag.Arg(0) resu...
package main import ( "bufio" "fmt" "os" "strings" ) func main() { //bufioSplit() bufioWriter() } func bufioSplit() { const input = "feng chen ni hao a" scanner := bufio.NewScanner(strings.NewReader(input)) split := func(data []byte, atEOF bool) (addvace int, token []byte, err error) { addvace, token, err...
package request import ( "context" "net/http" "sync" ) type do func(r *http.Request) (*http.Response, error) type client struct { do do concurrencyLimit int } func NewClient( do do, concurrencyLimit int, ) *client { return &client{ do: do, concurrencyLimit: concurrencyLimit, ...
package keypair import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("keypair.FromAddress", func() { var subject KeyPair JustBeforeEach(func() { subject = &FromAddress{address} }) ItBehavesLikeAKP(&subject) Describe("Sign()", func() { It("fails", func() { _, err := subjec...
// Copyright 2023 SpotHero // // 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 wri...
package word import "sort" const ( Size = 64 //bit size Log2 = 6 //w >> Log2 == w/64 m1 uint64 = 0x5555555555555555 //binary: 0101... m2 uint64 = 0x3333333333333333 //binary: 00110011.. m4 uint64 = 0x0f0f0f0f0f0f0f0f //binary: 4 zeros, 4 ones ... h01 uint64 = 0x0101010101010101 //the sum of 256 to the powe...
package metre import ( "fmt" zmq "github.com/pebbe/zmq4" ) const queueFlag zmq.Flag = 0 type Queue struct { URI string PushSocket *zmq.Socket // Socket to push messages to PullSocket *zmq.Socket // SOcket to pull mesasges form } // BindPush binds to the socket to push func (q Queue) BindPush() e...
package leetcode /*Given an array of string words. Return all strings in words which is substring of another word in any order. String words[i] is substring of words[j], if can be obtained removing some characters to left and/or right side of words[j].*/ import "strings" func stringMatching(words []string) []string...
package goSolution func findMin(nums []int) int { var l = 0 var r = len(nums) - 1 var mid int for ; l != r; { mid = (l + r) >> 1 if nums[l] <= nums[r] { break } else { if nums[mid] >= nums[l] { l = mid + 1 } else { r = mid } } } return nums[l] }
package router import ( "reflect" "testing" ) func TestRouterSubscribeUnsubscribe(t *testing.T) { g := New(true) c := make(chan []byte) u, _, err := g.Subscribe(1, c) if err != nil { t.Errorf("First subscribe returned error %s", err.Error()) } if len(g.allConnected) != 1 { t.Error("Subscribe should add co...
package annotations import ( "github.com/haproxytech/kubernetes-ingress/controller/haproxy/api" "github.com/haproxytech/kubernetes-ingress/controller/store" ) func HandleGlobalAnnotations(k8sStore store.K8s, client api.HAProxyClient, forcePase bool, annotations store.MapStringW) (restart bool, reload bool) { annLi...
package _692_Top_K_Frequent_Words import ( "testing" "github.com/shadas/leetcode_notes/utils/array" ) func TestTopKFrequent(t *testing.T) { var ( words, ret []string k int ) words, k = []string{"i", "love", "leetcode", "i", "love", "coding"}, 2 ret = topKFrequent(words, k) if !array.IsStrArrayEqu...
package api import ( "github.com/golang/glog" ) // api服务结构体,必须实现了所有service ApiService中的方法 type ApiService struct { DeployAddress string middleWare []func() } func (this *ApiService) init() { this.middleWare = make([]func(), 0) this.SetMiddleWare(func() { if r := recover(); r != nil { glog.Errorln("panic...
// DO NOT EDIT. This file was generated by "github.com/frk/gosql". package testdata import ( "time" ) var _FilterBasicRecords_colmap = map[string]string{ "Id": `"id"`, "Email": `"email"`, "FullName": `"full_name"`, "CreatedAt": `"created_at"`, } func (f *FilterBasicRecords) Init() { f.Filter.Init(...
package message import ( "bufio" "crypto/sha256" "encoding/hex" "golang.org/x/crypto/ripemd160" "io" "os" ) // CalculateChecksums calculates a number of hashes for the given reader in one go. // Taken from http://marcio.io/2015/07/calculating-multiple-file-hashes-in-a-single-pass/ func CalculateChecksums(r io.R...
package main import ( "app/templates" "database/sql" "log" "sort" "strconv" "github.com/kataras/iris/context" ) func jsonHandler(ctx context.Context) { ctx.Header("Server", "Iris") ctx.JSON(context.Map{"message": "Hello, World!"}) } func plaintextHandler(ctx context.Context) { ctx.Header("Server", "Iris") ...
package envoyconfig import ( "fmt" "strconv" envoy_config_core_v3 "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" envoy_config_listener_v3 "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3" envoy_config_route_v3 "github.com/envoyproxy/go-control-plane/envoy/config/route/v3" envoy_ht...
package steps import ( "context" "fmt" componenttest "github.com/ONSdigital/dp-component-test" "github.com/chromedp/chromedp" "github.com/hashicorp/go-uuid" "github.com/stretchr/testify/assert" ) type Collection struct { componenttest.ErrorFeature api *FakeApi chromeCtx context.Context } func NewColle...
package chirp import ( "encoding/hex" "encoding/json" "errors" "fmt" "log" "net" "regexp" "time" "golang.org/x/net/ipv4" "golang.org/x/net/ipv6" ) // MaxPayloadBytes is the maximum allowed size of a payload when serialized into // JSON const MaxPayloadBytes = 32 * 1024 const maxMessageBytes = 33 * 1024 va...
package alicloud import ( "os" "path/filepath" ) var client = &Client{ AccessToken: GetAccessToken(), BaseApiURL: "http://api.yunpan.alibaba.com/api", LocalBaseDir: filepath.Join(os.Getenv("PWD"), "local_backup"), RemoteBaseDir: "raspberry_pi", }
// All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing...
// ViChart library for Go // Author: Tad Vizbaras // License: http://github.com/tadvi/vichart/blob/master/LICENSE // package vichart import ( "fmt" "github.com/ajstarks/svgo" ) const ( VBMultiLineXYStyle = "stroke:lightgray;stroke-width:2px;" VBMultiLineStyle = "fill:navy;stroke:navy;stroke-width:2px;" VBMul...
package editor import ( "github.com/gdamore/tcell" "github.com/rivo/tview" "strconv" ) type Footer struct { *tview.Box *Editor totalLines int language string cursorX, cursorY int } // NewView returns a new view view primitive. func (e *Editor) NewFooter() *Footer { return &Footer{ Box: tv...
// Copyright 2018 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 config import ( "github.com/HNB-ECO/HNB-Blockchain/HNB/util" "encoding/json" "fmt" "io/ioutil" "time" ) type ConsensusConfig struct { // 所有超时都是毫秒为单位 // Delta 超时增量 TimeoutNewRound int `json:"timeoutNewRound,omitempty"` TimeoutPropose int `json:"timeoutPropose,omitempty"` TimeoutProposeWai...
package main import ( "context" "fmt" "os" "github.com/go-redis/redis/v8" ) var ctx = context.Background() // redis-benchmark -h $CACHE_HOST.redis.cache.windows.net -p 6380 -a $CACHE_KEY func main() { rdb := redis.NewClient(&redis.Options{ Addr: "akscache.redis.cache.windows.net:6380", Password: os.Ge...
package Problem0443 import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) // tcs is testcase slice var tcs = []struct { chars []byte ans int ansInPlace []byte }{ { []byte("abaa2"), 5, []byte("aba22"), }, { []byte("a"), 1, []byte("a"), }, { []byte("abbbbbbbbbbbb"), ...
package data_test import ( . "github.com/DennisDenuto/property-price-collector/data" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "time" ) var _ = Describe("Postcode", func() { It("should generate postcode numbers for nsw", func() { postCodes := ListNswPostcodes() Eventually(postCodes, 1*time.Minu...
// Copyright 2019 Authors of Cilium // Copyright 2017 Lyft, 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...
package testFunctions import ( "bufio" "fmt" "net" "strings" "time" ) func sayHello() string { return "Hello from this another package" } func testSwitch() { t := time.Now() switch { case t.Hour() < 12: fmt.Println("It's before noon") default: fmt.Println("It's after noon") } } func testarray() { va...
package psql import ( "database/sql" "fmt" _ "github.com/lib/pq" "log" ) type ( PsqlContext interface { GetDb() *sql.DB Close() SchemeInit(scheme string) error } psqlContext struct { db *sql.DB } ) func (c *psqlContext) GetDb() *sql.DB { return c.db } func (c *psqlContext) Close() { c.db.Close() ...
package main import "lesson/myLesson/readAndWrite/read" // 入口函数 func main() { //read.TestReadFromCmd() //read.TestReadFromFile() read.TestGob1() }
package main type StageList struct { Stages []string CompoundStages map[string][]string } func parseStagesFromYaml(filename string) *StageList { stages := StageList{} parseFromYamlFile(filename, &stages) return &stages }
package sw import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "fmt" "github.com/HNB-ECO/HNB-Blockchain/HNB/bccsp" "github.com/HNB-ECO/HNB-Blockchain/HNB/bccsp/secp256k1" ) type ecdsa256K1KeyGenerator struct { curve elliptic.Curve } func (kg *ecdsa256K1KeyGenerator) KeyGen(opts bccsp.KeyGenOpts) (k bccsp...
package http import ( "github.com/heroku/cytokine/logging" gohttp "net/http" "time" ) type TimingTransport struct { Transport gohttp.RoundTripper } func (t TimingTransport) RoundTrip(request *gohttp.Request) (*gohttp.Response, error) { defer logging.Monitor("cytokine.http.request", time.Now()) return t.Transpo...
package cli import ( "github.com/HNB-ECO/HNB-Blockchain/HNB/access/rest" appComm "github.com/HNB-ECO/HNB-Blockchain/HNB/appMgr/common" "github.com/HNB-ECO/HNB-Blockchain/HNB/bccsp" "github.com/HNB-ECO/HNB-Blockchain/HNB/bccsp/secp256k1" "github.com/HNB-ECO/HNB-Blockchain/HNB/bccsp/sw" "github.com/HNB-ECO/HNB-Blo...
package main import ( "github.com/ant0ine/go-json-rest" "log" "net/http" "os" "runtime" // "runtime/pprof" // _ "net/http/pprof" // "flag" ) // var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file") func main() { // flag.Parse() // if *cpuprofile != "" { // f, err := os.Create(...
package config import ( "flag" "github.com/pkg/errors" "github.com/spf13/pflag" "github.com/spf13/viper" ) // DBConfig database config type DBConfig struct { Database string `mapstructure:"name"` Host string `mapstructure:"host"` MaxConn string `mapstructure:"max_connections"` MaxIdleConn strin...
package cmd import ( "encoding/json" "fmt" "log" "net/http" "time" "github.com/r3labs/sse" "github.com/spf13/cobra" ) type LogResponse struct { PageInfo struct { TotalCount int `json:"total"` Limit int `json:"limit"` Offset int `json:"offset"` } `json:"pageInfo"` Results []struct { T t...
package gallery type Image interface { GetId() string GetContent() string } type imageDto struct { Id string `json:"id"` Content string `json:"content"` } func CreateImage(id, content string) *imageDto { g := new(imageDto) g.Id = id g.Content = content return g } func (g *imageDto) GetId() string { re...
package example func main() { var i interface{} = "hello" f, ok = i.(float64) if !ok { // don't use f } }
package main import "fmt" func main() { a := []int{3, 2, 1, 0, 4} fmt.Println(canJump(a)) } func canJump(nums []int) bool { maxRearch := 0 for i := 0; i < len(nums); i++ { if maxRearch < i { return false } if maxRearch < nums[i]+i { maxRearch = nums[i] + i } } return true }
package routers import ( "WhereIsMyDriver/controllers" "github.com/kataras/iris" ) // IrisApp iris App is router func IrisApp() *iris.Application { app := iris.New() app.Get("/drivers", controllers.GetDrivers) app.Put("/drivers/:id/location", controllers.UpdateLocation) app.OnErrorCode(iris.StatusNotFound) re...
// Copyright 2019 The Grafeas Authors. 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 ap...
package main import "fmt" type Graph [][]string func NewGraph(sensors Sensors) *Graph { graph := Graph{} trim := sensors.Trim() max := sensors.Max() min := sensors.Min() fmt.Println(max + trim) fmt.Println(min) for y := min; y <= max+trim; y++ { row := []string{} for x := min; x <= max+trim; x++ { ro...
package admin import ( "fmt" "github.com/billyninja/pgtools/scanner" "html/template" "log" "time" ) type col2html func(cl *scanner.Column) template.HTML type val2html func(cl *scanner.Column, value interface{}) template.HTML func InputHTML(cl *scanner.Column, value interface{}) template.HTML { ...
package main import ( "log" "room" ) func main() { log.SetFlags(log.Llongfile) rpcListen := room.NewRpcListener() go func() { room.RpcWorker(rpcListen) }() go func() { debugRoom := room.NewDebugChatRoom() debugRoom.Start() rpcListen.Msg <- <-debugRoom.Msg }() for { <-rpcListen.CreateNewRoom g...
package migrations import ( "github.com/go-pg/migrations" log "github.com/sirupsen/logrus" ) func init() { migrations.Register(func(db migrations.DB) error { log.Info("migrate 20171010114357_create-locales") _, err := db.Exec(` CREATE TABLE locales ( id BIGSERIAL PRIMARY KEY, code VARCHAR(255) NOT NULL, ...
package facade import ( "github.com/stretchr/testify/assert" "testing" ) func Test(t *testing.T) { bidder := BidderImpl{bidOptimizer: &BidOptimizer{}, predictor: &Predictor{}, detargeter: &Detargeter{}} bidPrice := bidder.bid(&Request{}) assert.Equal(t, float32(50), bidPrice) }
package handshaketime import ( "net" "time" "sync" ) type SynPacket struct { ip net.IP timeReceived time.Time sequenceNumber uint32 } type HandshakeTime struct { ip net.IP time time.Duration } type DatabaseProxy interface { saveSynPacket(SynPacket) getSynPacket(uint32) (SynPacket, error) deleteSynPacket...
// Package bitvec is bit-vector with atomic access package bitvec import "sync/atomic" // ABitVec is a bitvector type ABitVec []uint64 // NewABitVec returns a new bitvector with the given size func NewABitVec(size int) ABitVec { return make(ABitVec, uint(size+63)/64) } // Get returns the given bit func (b ABitVec)...
package handlers import ( "net/http" "github.com/saurabmish/Coffee-Shop/data" ) func (p Products) Modify(w http.ResponseWriter, r *http.Request) { p.l.Println("[INFO] Endpoint for PUT request") w.Header().Add("Content-Type", "application/json") id := getProductID(r) p.l.Println("[DEBUG] Retrieved product ID f...
package request import ( "errors" "io/ioutil" "net/http" "net/url" ) type Request struct{} var ErrParseURL = errors.New("error to parse url string!") func (r *Request) Get(rawUrl string) ([]byte, error) { url, err := validateUrl(rawUrl) if err != nil { return nil, ErrParseURL } resp, err := http.Get(url) ...
package icarus import ( "sync" "github.com/luuphu25/data-sidecar/util" ) // IcarusStore holds sets of metrics and retires them as necessary. type IcarusStore struct { *sync.Mutex Keep int Index int Metrics []map[string]util.Metric } // Get back a new implementation of the rolling store func NewRollingSto...