text
stringlengths
11
4.05M
package main import ( "fmt" xir "github.com/ceftb/xir/lang/go" "github.com/satori/go.uuid" ) func main() { tb := xir.NewNet() node := func(format string, args ...interface{}) *xir.Node { return tb.Node().Set(xir.Props{"name": fmt.Sprintf(format, args...)}) } // The Internet //internet := node("internet")...
package challenge_1 import "testing" func TestFirstChallenge(t *testing.T) { src := []byte("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d") outputStr := string(hexToBase64(src)) expectedStr := "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t" if ...
package structs type Session struct { User_ID string Session_ID string }
// SPDX-License-Identifier: ISC // Copyright (c) 2014-2020 Bitmark Inc. // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package payment import ( "testing" "github.com/btcsuite/btcd/peer" ) func TestPeerMapLen(t *testing.T) { address := "127.0.0.0:12345" m := N...
package proto import ( "packet" ) type ReqRoleRandName struct { } func (this *ReqRoleRandName) Encode() []byte { pack := packet.NewWriteBuff(64) return pack.Encode(P_REQ_ROLE_RAND_NAME) }
package main import ( "fmt" "net" "net/http" ) func main() { http.HandleFunc("/", HelloServer) http.ListenAndServe(":8088", nil) // set listen port } func HelloServer(rw http.ResponseWriter, req *http.Request) { fmt.Fprint(rw, "Hello World at IP " + GetLocalIP() ) } func GetLocalIP() string { addrs, err...
package handler import ( "net/http" "github.com/julienschmidt/httprouter" "google.golang.org/appengine/mail" "google.golang.org/appengine/log" "google.golang.org/appengine" ) func contactPage(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { tpl.ExecuteTemplate(w, "contact.html", nil) } func send...
package campain import ( "fmt" "github.com/tapvanvn/go-chain-wrapper/entity" "github.com/tapvanvn/go-chain-wrapper/repository" "github.com/tapvanvn/godashboard" ) type ReportEvent struct { track *entity.Track events []*entity.Event } //ReportLive get report meta for dashboard func ReportLive() map[string]god...
package nfs import ( storageosv1 "github.com/storageos/cluster-operator/pkg/apis/storageos/v1" "github.com/storageos/cluster-operator/pkg/util/k8s" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/rest" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/client" ) // Deployment manages the NF...
// Copyright © 2016 NAME HERE <EMAIL ADDRESS> // // 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 ...
package containerctlr import ( "os/exec" "strings" ) const dm = "docker-machine" // Returns docker-machine status, stripped of spaces func MachineStatus(vmName string) string { cmd := dm + " status " + vmName out, err := runcmd(cmd) if err != nil { return "Status failed" } status := string(out) return stri...
package config import ( "github.com/caarlos0/env" ) type config struct { ListenAddr string `env:"LEARNING_GO_LISTEN_ADDR"` DbURL string `env:"LEARNING_GO_DB_URL"` } var conf config func ParseEnv() error { err := env.Parse(&conf) return err } func ListenAddr() string { return conf.ListenAddr } func DbU...
// Copyright 2013 The 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 main import ( "errors" "fmt" "github.com/joshlf13/erreq" "github.com/joshlf13/errlist" ) type equalError struct { i int } func (e1 *equalError) Equ...
package mongodb import ( "context" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) var optUpset = options.Update().SetUpsert(true) var optFindOneOrCreate = options.FindOneAndUpdate().SetUpsert(true). SetReturnDocument(options.After) type Colle...
package liferay import ( "testing" internal "github.com/mdelapenya/lpn/internal" "github.com/stretchr/testify/assert" ) func init() { internal.CheckWorkspace() } func TestDeployFolderCommerce(t *testing.T) { commerce := Commerce{} assert := assert.New(t) assert.Equal("/opt/liferay/deploy", commerce.GetDepl...
package font import ( "image/color" "strings" "github.com/hajimehoshi/ebiten" "github.com/hajimehoshi/ebiten/text" "github.com/hajimehoshi/go-mplusbitmap" "golang.org/x/image/font" "golang.org/x/image/math/fixed" ) const LineHeight = 16 func tokens(str string) []string { tokens := []string{} for { var st...
package main import ( "database/sql" "encoding/json" "flag" "fmt" "os" "time" "github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/ethclient" "github.com/lib/pq" "gitlab.com/pschlump/PureImaginationServer/ReadConfig" ) type PgData struct { Cmd string `json:"Cmd"` Hash str...
// Copyright 2023 The gVisor 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 agree...
package util import ( "labix.org/v2/mgo" "labix.org/v2/mgo/bson" "time" ) func mainMongo() { //s := MongoInit() //query := bson.M{} //m, _ := Find(s, "weixin", "user", query) } //================================================================================ func MongoInit(host string) *mgo.Session { sessio...
package p2pv1 import "github.com/xuperchain/xupercore/kernel/network/def" // PeerFilter the interface for filter peers type PeerFilter interface { Filter() ([]string, error) } // StaticNodeStrategy a peer filter that contains strategy nodes type StaticNodeStrategy struct { srv *P2PServerV1 broadcast bool bcname...
package connhandler import ( "bufio" "bytes" "encoding/gob" "log" "net" "raft" "strconv" "strings" "time" "utils" ) /* *Helper function to read value or cause timeout after READ_TIMEOUT seconds *parameters: channel to read data from, threshold number of bytes to read, log pointer to write into *returns: ...
package plugin func GetPluginLink() string { return PathPrefix + "/" + Name } func GetEnviromentsLink() string { return GetPluginLink() + "/" + EnvironmentsPath } func GetHelmLink() string { return GetPluginLink() + "/" + HelmPath } func GetHelmReleaseLink(releaseName string) string { return GetHelmLink() + "/"...
package c169 //给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。 // // 你可以假设数组是非空的,并且给定的数组总是存在众数。 // // 示例 1: // // 输入: [3,2,3] //输出: 3 // // 示例 2: // // 输入: [2,2,1,1,1,2,2] //输出: 2 // // Related Topics 位运算 数组 分治算法 //leetcode submit region begin(Prohibit modification and deletion) /* 思路1:暴力--将每个元素出现的次数存入map、最后进行遍历...
package app import ( "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestDilbertDownloader_DownloadComic(t *testing.T) { d := time.Date(2018, 1, 6, 0, 0, 0, 0, time.Local) dl := &DilbertDownloader{} comic, err := dl.DownloadComic(d) require.NoError(t, err) ...
package schedulepayout import ( "errors" "reflect" "testing" "time" "github.com/NodeFactoryIo/vedran/internal/configuration" "github.com/NodeFactoryIo/vedran/internal/models" "github.com/NodeFactoryIo/vedran/internal/repositories" mocks "github.com/NodeFactoryIo/vedran/mocks/repositories" "github.com/stretch...
package main import ( "fmt" ) func main() { tb := new(TbTree) tb.Key = 61 for _, value := range []int{59, 87, 47, 60, 73, 98} { tb.Insert(value) } fmt.Printf("tb.key is %v\n", tb.Key) fmt.Printf("tb.LChild is %v\n", tb.LChild.Key) ptb, ntb, drt := tb.Search(60) if ptb != nil { fmt.Printf("parent of ntb...
package pcsconfig import ( "fmt" ) // SetBDUSS 设置百度 bduss 并保存 func (c *PCSConfig) SetBDUSS(bduss string) (username string, err error) { b, err := NewWithBDUSS(bduss) if err != nil { return "", err } if c.CheckUIDExist(b.UID) { return "", fmt.Errorf("登录失败, 用户 %s 已存在", b.Name) } c.BaiduUserList = append(c.Ba...
package main import ( "bufio" "fmt" "log" "os" "regexp" "strconv" "strings" "time" ) func main() { start := time.Now() fmt.Printf("Result is %v \n", run()) log.Printf("Code took %s", time.Since(start)) } func run() int { valid := 0 f, err := os.Open("input.txt") if err != nil { log.Fatal(err) } ...
package commands type UpdateOrgsMetadataCommand struct { BaseCFConfigCommand BasePeekCommand } //Execute - updates organizations metadata func (c *UpdateOrgsMetadataCommand) Execute([]string) error { var cfMgmt *CFMgmt var err error if cfMgmt, err = InitializePeekManagers(c.BaseCFConfigCommand, c.Peek); err == n...
// Copyright 2016 Amazon.com, Inc. or its affiliates. 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. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" fil...
package main func (___Vdm *_TdataMachine) _FdataMachin__rece__dataSpec(___Vdec *_Tdecode) { // _TdecodeX if ___Vdec.DEtype != LoadT__data_01_special { __FpfN(" 839291 01 : _TdataMachine : DEtype error : {%s}", ___Vdec.String()) return } if ___Vdec.DEdata.DtDDcmd == DDType__idle { // ignore , no more process is...
// Copyright 2015 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, ...
package main import ( "fmt" ) func toInt(s string) int { var out int for _, i := range s { switch i { case '0': out = out*10 + 0 case '1': out = out*10 + 1 case '2': out = out*10 + 2 case '3': out = out*10 + 3 case '4': out = out*10 + 4 case '5': out = out*10 + 5 case '6': out ...
// Copyright 2019 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, ...
package rds import ( "testing" "github.com/crossplane/provider-alibaba/apis/database/v1alpha1" ) func TestGenerateObservation(t *testing.T) { ob := GenerateObservation(&DBInstance{Status: v1alpha1.RDSInstanceStateRunning}) if ob.DBInstanceStatus != v1alpha1.RDSInstanceStateRunning { t.Errorf("DBInstanceStatus:...
// Package config implements the config for the fleet manager and agent package config import ( "context" "encoding/json" "sync" "github.com/rancher/fleet/pkg/version" corev1 "github.com/rancher/wrangler/pkg/generated/controllers/core/v1" v1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors"...
package main import ( "fmt" "sort" "strings" "testing" ) func TestSimpleSort(t *testing.T) { for k, v := range map[string]string{ "70.920 -38.797 14.354 99.323 90.374 7.581": "-38.797 7.581 14.354 70.920 90.374 99.323", "-37.507 -3.263 40.079 27.999 65.213 -55.552": "-55.552 -37.507 -3.263 27.999 40.079 65...
package main func init() { solutions[2] = euler2 } func euler2() { var total uint64 fibs := Fibs() for i := fibs.Next(); i < 4000000; i = fibs.Next() { if (i % 2) == 0 { total += i } } println(total) }
package models import ( u "../utils" "github.com/jinzhu/gorm" ) type CommentVotes struct { gorm.Model UserID uint `json:"user_id"` CommentID uint `json:"comment_id"` Score int `json:"score"` } func (commentVotes *CommentVotes) Validate() (map[string]interface{}, bool) { if commentVotes.CommentID <= 0...
package main import ( "github.com/robfig/cron" ) // Cron manage all cron jobs of this plugin // behind the scene it's a facade to github.com/robfig/cron type Cron struct { p *Plugin c *cron.Cron } // NewCron return a cron func NewCron(p *Plugin) (*Cron, error) { c := cron.New() if err := c.AddFunc("@every 1m",...
package pascal // func pascal(number int) [][]int triangle { // num := 2 // intArray := [num][num]int{} // for i:=1;i<num;i++ { // for n:=0;n<i;n++ { // temp := intArray[i-1][n] // if intArray[i-1][n+1] != nil { // temp2 := intArray[i-1][n+1] // }...
// 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 nearbyshare import ( "context" "encoding/json" "os" "path/filepath" "time" "github.com/golang/protobuf/ptypes/empty" "google.golang.org/grpc" nearbycommon ...
// Copyright (C) 2016-Present Pivotal Software, Inc. All rights reserved. // This program and the accompanying materials are made available under the terms of the 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 Licen...
package tools import ( "fmt" "io/ioutil" "net/http" ) func HttpRequest(r *http.Request) ([]byte, error) { client := &http.Client{} resp, err := client.Do(r) if err != nil { fmt.Println(err.Error()) return nil, err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt...
package access_token import ( "bookstore-ouath-api/src/utils" "strings" ) type Repository interface { GetById(id string) (*AccessToken, *utils.RestErr) CreateToken(token AccessToken) *utils.RestErr } type Service interface { GetById(string) (*AccessToken, *utils.RestErr) CreateToken(token AccessToken) *utils.R...
/** * Example of marshalling and unmarshalling JSON * Channel, complex, and function types cannot be encoded */ package main import ( "encoding/json" "fmt" ) type HttpRequest struct { Method string Body string } func main() { // Serialize in JSON originatedRequest := HttpRequest{"POST", "Here is my conte...
package routes import ( "net/http" "strings" "github.com/gorilla/mux" "github.com/xyingsoft/golang-react/controllers" "github.com/xyingsoft/golang-react/middleware" ) // Disable file list of directory func notFoundHandler(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *...
package registry import ( "testing" "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) func TestFindTags(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder("GET", "https://quay.io/v2/cidverse/base-dotnet-runtime/tags/list", httpmock.NewStringRes...
package main import ( "os" "os/signal" ) func init() { var sig = make(chan os.Signal) signal.Notify(sig, os.Interrupt, os.Kill) go func() { panicerr(<-sig) }() }
package chapters import "fmt" func pointers() { fmt.Print("\n---\n\n") var firstName *string = new(string) *firstName = "Arthur" fmt.Println(firstName) fmt.Println(*firstName) lastName := "Fleck" ptr := &lastName fmt.Println(ptr, *ptr) lastName = "Morgan" fmt.Println(ptr, *ptr) fmt.Print("\n---\n\n") }...
package gocosmos import ( "database/sql/driver" "fmt" "regexp" "strings" ) const ( field = `([\w\-]+)` ifNotExists = `(\s+IF\s+NOT\s+EXISTS)?` ifExists = `(\s+IF\s+EXISTS)?` with = `((\s+WITH\s+([\w-]+)\s*=\s*([\w/\.,;:'"-]+))*)` ) var ( reCreateDb = regexp.MustCompile(`(?is)^CREATE\s+DATABA...
package db import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" ) func New() *gorm.DB { db, err := gorm.Open("sqlite3", "students.db") if err != nil { fmt.Println("storage err: ", err) } db.DB().SetMaxIdleConns(3) db.LogMode(true) return db }
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "os" "github.com/Sigafoos/iv/model" ) const dataPath = "../data" type Gamemaster struct { Pokemon []Pokemon `json:"pokemon"` } func main() { log.Print("opening gamemaster...") fp, err := os.Open("gamemaster.json") if err != nil { fmt.Println...
package main import ( "fmt" "net/http" "strings" "github.com/PuerkitoBio/goquery" "github.com/l-dandelion/cwgo/data" "github.com/l-dandelion/cwgo/utils" ) // function for parsing response func parseATag(resp *data.Response) ([]data.Data, []error) { reqURL := resp.HTTPResp().Request.URL httpResp := resp.HTTP...
package sudo import potato "github.com/rise-worlds/potato-go" func init() { potato.RegisterAction(AN("poc.wrap"), ActN("exec"), Exec{}) } var AN = potato.AN var ActN = potato.ActN
// description : A minimal "echo" server // author : Tom Geudens (https://github.com/tomgeudens/) // modified : 2016/06/27 // package main import ( "fmt" "log" "net/http" ) func main() { http.HandleFunc("/", handler) // each request calls handler log.Fatal(http.ListenAndServe("localhost:8000", nil)) } f...
package models const ( MessageInfoTableName = "message_info" ) // 消息 type MessageInfo struct { BaseModel Icon string Title string Content string Time string UserId uint } type MessageSerializer struct { Icon string `json:"icon"` Title string `json:"title"` Content string `json:"content"` Tim...
package dao import ( "bytes" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" "log" configInfo "routerWeb/conf" ) var DBConnection *gorm.DB var conf configInfo.MySqlConfig var fdnDBUrl string func GetDB() *gorm.DB{ return DBConnection } func setDB(db *gorm.DB) { DBConnection = db } func...
package version import ( "strings" "github.com/prebid/openrtb/v19/openrtb2" "github.com/prebid/prebid-server/openrtb_ext" ) const xPrebidHeaderVersionPrefix = "pbs-go" func BuildXPrebidHeader(version string) string { sb := &strings.Builder{} writeNameVersionRecord(sb, xPrebidHeaderVersionPrefix, version) ret...
package main import ( "container/heap" "fmt" "sort" "strconv" "strings" ) /* # A video game has recorded the player name and score for each time the game has been played. # Create a high-score list of the top 50 Players and their best score, where each player only appears once on # the high score list # Input: ...
package main import ( "fmt" "aws_test/common" "time" "strconv" ) // MQTT stuff var updateInterval time.Duration = 30 * time.Second var publishTopic string = "sensors/temp/external" var subscribeTopic string = "sensors/setting/interval" // Handles all received messages func onMQTTMessageReceived(topic string, pay...
package book5 import ( "fmt" "golang.org/x/net/html" "strings" "testing" ) func add1(r rune) rune { return r + 1 } //// [pre][post]是可选的,遍历每个节点的前后都会调用[pre]和[post] //func forEachNode(n *html.Node, pre, post func(n *html.Node)) { // if pre != nil{ // pre(n) // } // for c := n.FirstChild; c != nil; c = c.NextSibli...
package main import ( "bufio" "fmt" "os" "strconv" ) type point struct { x, y float64 } type line struct { p1, p2 point } // https://en.wikipedia.org/wiki/Line–line_intersection#Given_two_points_on_each_line func (t line) intersects(o line) bool { x1, y1 := t.p1.x, t.p1.y x2, y2 := t.p2.x, t.p2.y x3, y3 :=...
// 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 netflix provides gmail instance for cuj tests on ChromeOS. package netflix
package pager import ( "fmt" "github.com/jinzhu/gorm" "reflect" "starter/pkg/database/orm" "strings" ) // Gorm 查询 type Gorm struct { conn *gorm.DB query string args []interface{} limit int skip int index string sorts string } // NewGormDriver gorm 分页实现 func NewGormDriver() *Gorm { return &Gorm{ con...
// Copyright (c) 2016-2019 Uber Technologies, 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...
package leetcode type ListNode struct { Val int Next *ListNode } func reversePrint(head *ListNode) []int { if head == nil { return nil } l := 0 s := head for s != nil { l++ s = s.Next } t := make([]int, l) s = head for s != nil { t[l-1] = s.Val l-- s = s.Next } return t }
package main import ( "bytes" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "strconv" "strings" "sync" "time" log "github.com/Sirupsen/logrus" "github.com/docker/go-plugins-helpers/volume" ) const ( PluginName = "gcsfs" BucketMount = "/mnt/buckets" KeyMount = "/mnt/keys" KeyStorage = "/tmp/ke...
package main import ( _ "todos/routers" "github.com/astaxie/beego" "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" ) func init() { orm.RegisterDriver("mysql", orm.DR_MySQL) orm.RegisterDataBase("default", "mysql", "root:pass4root@/test?charset=utf8") } func main() { beego.Run() }
package server import ( "context" "fmt" "net" "net/http" "github.com/pkg/errors" "github.com/wwq1988/leaf/pkg/conf" "github.com/wwq1988/leaf/pkg/service" ) type Server struct { server *http.Server service service.Service ln net.Listener } func New(service service.Service) *Server { return &Server{s...
// Copyright (c) KwanJunWen // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. package estemplate import "fmt" // DatatypePercolator Specialised Datatype that parses a JSON structure // into a native query and stores that query, so that the p...
package main import "fmt" func main() { //字符串定义 //var message string //message="hello world" //fmt.Println(message) ////打印结果 1 0 0 lktbz //var a ,b ,c int //a=1 //message="lktbz" //fmt.Println(a,b,c,message) //变量的连续定义 ,并且指定变量的类型 //var a,b,c int =1,2,4 //fmt.Println(a,b,c) //不指定变量的类型,会自己适应类型 //var a,b,c...
package util import ( "net" "os" "regexp" "runtime" "strconv" "time" ) // 处理相对的ip地址与端口 func ResolveAddress(host string, port string) string { if port == "0" { port = "8080" } if envPort := os.Getenv("PORT"); envPort != "" { port = ":" + envPort } return host + ":" + port } // 判断是否存在 func IsExist(pat...
// Copyright 2021 EricWinn // Author: Eric Winn // Email: eng.eric.winn@gmail.com // Time: 2021/10/13 13:28 // File: tools_test.py // Software: GoLand package tools import ( "log" "testing" ) func TestRandomString(t *testing.T) { pass := RandomString(12) log.Println(pass) }
package main import ( "fmt" "excelize" ) func init() func main() { data := readExcel("so") fmt.Printf("%T\n", data) for _, slice := range data { for _, v := range slice { fmt.Println(v) } } } func readExcelData(path string) interface{} { return } func readExcel(file string) [][]string { retu...
package files import ( "io" "os" "path/filepath" "golang.org/x/xerrors" ) type Local struct { maxFileSize int basePath string } func NewLocal(basePath string, maxFileSize int) (*Local, error) { path, err := filepath.Abs(basePath) if err != nil { return nil, err } return &Local{basePath: path}, nil }...
package main import ( "crypto/sha256" "bytes" "encoding/binary" "time" ) // 1.定义结构 type Block struct { Version uint64 //版本号 PrevHash []byte //前区块哈希 MerkelRoot []byte //Merkel根 TimeStamp uint64 // Difficulty uint64 //难度值 Nonce uint64 //随机数 Hash []byte //当前区块哈希,正常比特币区块中没有当前区块的哈希,此处为了方便 Data []by...
package main import ( "fmt" "testing" ) func Test_run(t *testing.T) { type args struct { a, b int } tests := []struct { args args want float64 }{ { args{45, 200}, 90, }, { args{37, 450}, 166.5, }, { args{50, 0}, 0, }, } for i, tt := range tests { t.Run(fmt.Sprintf("Test %d...
package main import( "net/http" "html/template" ) func handler(w http.ResponseWriter, r *http.Request){ t, _ := template.ParseFiles("view.html") t.Execute(w, "Hello World") } func main(){ http.HandleFunc("/view", handler) http.ListenAndServe(":9000", nil) }
package main import "fmt" /** * <p> * 数组变量 * Java,go,c等数组都是从0开始。 * </p> * @author: zhu.chen * @date: 2020/8/5 * @version: v1.0.0 */ func main() { var n [10]int var i, j int for i = 0; i < 10; i++ { n[i] = i + 100 } for j = 0; j < 10; j++ { fmt.Printf("Element[%d] = %d\n", j, n[j]) } fmt.Println("...
package file_test import ( "bytes" "encoding/binary" "io" "testing" . "github.com/matthew-burr/db/file" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestEncodeTo(t *testing.T) { buf := new(bytes.Buffer) entry := NewEntry("my_key", Value("my_value")) n, _ := EncodeTo(buf...
package _005_longest_palindromic_substring func longestPalindrome(s string) string { /* 动态规划分析: 如果s[i:j]是回文子串(这里是左闭右闭),则,s[i] == s[j], 且s[i+1,j-1]也一定是回文子串 所以s[i:j]的结果是依赖s[i+1,j-1]的,我们要提前得出s[i+1,j-1]的结果 对应二维数组,假设纵坐标为i,横坐标为j,由于i<j,所以需要计算的值都在左对角线的右上方, 由于s[i+1,j-1]是相对于s[i:j]的左下方,所以我们为了保证先得到s[i+1,j-1]值,考虑纵向自上而下的遍历, ...
/* Copyright 2021 The Pixiu 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 linqo import ( "bytes" ) type DeleteBuilder interface { Action Where(term SearchTerm) Action } type deleteBuilder struct { *bytes.Buffer } type deletePositioned string func Delete(table string) DeleteBuilder { d := deleteBuilder{bytes.NewBuffer(nil)} d.WriteString("DELETE FROM ") d.WriteString(table...
package restapi import ( "net/http" "github.com/cidverse/cidverseutils/pkg/cihelper" "github.com/cidverse/repoanalyzer/analyzerapi" "github.com/labstack/echo/v4" ) // projectInformation returns all available information about the current project func (hc *APIConfig) moduleList(c echo.Context) error { var module...
package main import "fmt" func main() { var n, cur, min, count int fmt.Scan(&n) for i := 0; i < n; i++ { fmt.Scan(&cur) if cur < min || i == 0 { count = 1 min = cur } else if cur == min { count++ } } fmt.Print(count) } // Найдите количество минимальных элементов в последовательности.
package Golang_Advanced_Camp_Language import ( "sync" "sync/atomic" "unsafe" ) // The linked list struct. type IntList struct { head *Node length int64 } // Each node in the linked list. type Node struct { value int next *Node mu sync.RWMutex marked uint32 } func newIntNode(value int) *Node { ret...
//go:build integration // +build integration package sqsx_test import ( "context" "testing" "github.com/aws/aws-sdk-go/service/sqs" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/socialpoint-labs/bsk/awsx/awstest" "github.com/socialpoint-labs/bsk/awsx/sqsx" ) const pa...
package main import ( "fmt" "net" "time" ) func test3() { timeout := time.Duration(10 * time.Second) conn, err := net.DialTimeout("tcp","180.76.76.76:80", timeout) if err != nil { fmt.Println("Site unreachable, error: ", err) } fmt.Println(conn.RemoteAddr().Network(),conn.RemoteAddr().String()) // conn...
package handlers import ( mdl "diaria/models" sec "diaria/security" "encoding/json" pq "github.com/lib/pq" // htemplate "html/template" route "diaria/routes" "log" "net/http" "strconv" "strings" ttemplate "text/template" "time" ) func CreateMealHandler(w http.ResponseWriter, r *http.Request) { log.Printl...
package balancer import ( "context" "errors" "math/rand" "myRPC/registry/register" ) //加权负载均衡 type WeightRandomBalance struct { Name string } func NewWeightRandomBalance() BalanceInterface { return &WeightRandomBalance{ Name:"weight_random", } } func (r *WeightRandomBalance)GetName()(name string) { return ...
package costs type FlyingCost struct { CityA int CityB int } // Function to find the minimum cost for an input array func GetMinimumCost(input []FlyingCost) int { // Loop over the input array and compare flying costs and get the lowest // and sum to the previous cost gathered before var finalResult int for _, f...
package endpoint import ( "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/sqs" "github.com/aws/aws-sdk-go/service/sqs/sqsiface" "github.com/skidder/streammarker-writer/config" "golang.org/x/net/context" ) // HealthCheckServicer provides function...
package core import ( "reflect" "testing" "time" ) func TestTrade_GetUTCTime(t *testing.T) { tests := []struct { name string Time uint64 want time.Time }{{ Time: 1585457915462000001, want: time.Date(2020, 3, 29, 4, 58, 35, 462000001, time.UTC), }} for _, tt := range tests { t.Run(tt.name, func(t *t...
package main import "fmt" //This function intSeq returns another function, //which we define anonymously in the body of intSeq. //The returned function closes over the variable //i to form a closure. func intSeq() func() int { i := 0 return func() int { i++ return i } } func main() { ...
package main import ( "encoding/json" "fmt" "github.com/astaxie/beego/logs" ) func main() { //初始化配置 config := make(map[string]interface{}) //配置参数 config["filename"] = "./testbeego.log" config["level"] = logs.LevelDebug //序列化config configStr, err := json.Marshal(config) if err != nil { fmt.Println("ma...
package minswaps // Used to record visitation of array elements type visit struct { val int seen bool } // Complete the minimumSwaps function below. func minimumSwaps(arr []int32) int32 { var trackArray []visit for _, v := range arr { trackArray = append(trackArray, visit{int(v), false}) } // traversing thr...
package keeper import ( "testing" "time" ) type TestRPCStruct struct { } type TestArg struct { } type TestReply struct { } func (t *TestRPCStruct) Test(arg TestArg, reply *TestReply) error { return nil } func (t *TestRPCStruct) TestTimeout(arg TestArg, reply *TestReply) error { time.Sleep(4 * time.Second) retu...
/* Copyright 2020 Docker Compose CLI 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 a...
package genfuncs import ( "math/rand" "time" ) func GenTen(seed int64) int { r := GetRandom(time.Now().UnixNano()) n := r.Intn(100) for n < 10 { n = r.Intn(100) } return n } func GenHundred(seed int64) int { r := GetRandom(time.Now().UnixNano()) n := r.Intn(1000) for n < 100 { n = r.Intn(1000) } ...