text
stringlengths
11
4.05M
package utils import "fmt" type Field struct { dataType int32 filled bool value interface{} } func NewField(dataType int32, value interface{}) *Field { f := Field{} f.SetDataType(dataType) switch dataType { case TSDataType.BOOLEAN: if v, ok := value.(bool); ok { f.SetBooleanValue(v) } else { re...
package main import ( "fmt" "testing" "github.com/stretchr/testify/require" ) func TestHello(t *testing.T){ //given exp :="Hello World!" //when act := Hello() //then require.Equal(t, exp, act, "Messages don't match") } func TestPersonalHello(t *testing.T){ scenarios := []struct { name string }{ {nam...
package network import ( "bufio" "bytes" "errors" "fmt" "os/exec" "regexp" "strings" "github.com/quilt/quilt/db" "github.com/quilt/quilt/join" "github.com/quilt/quilt/stitch" log "github.com/Sirupsen/logrus" "github.com/vishvananda/netlink" ) // This represents a rule in the iptables type ipRule struct ...
package main import "fmt" func main(){ m:= make(map[string] int) fmt.Println(m) m["k1"] =7 m["k2"] = 10 fmt.Println(m) v1 :=m["k1"] fmt.Println("v1",v1) fmt.Println("length",len(m)) delete(m,"k2") fmt.Println("map",m) _, prs := m["k2"] fmt.Println("prs",prs) n := map[string]int{"foo":1,"bar":2} fmt...
package storage import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) func TestShouldReturnErrOnTargetSameAsCurrent(t *testing.T) { assert.EqualError(t, schemaMigrateChecks(providerSQLite, true, 1, 1), fmt.Sprintf(ErrFmtMigrateAlreadyOnTargetVersion, 1, 1)) assert.EqualError(t, schemaMigrateChe...
package main import ( "fmt" "wsr-reader/server" ) func main() { if err := server.Run(":8080"); err != nil { fmt.Println("server failed to start, error:", err) } // wsr, err := wsr.NewWsr() // if err != nil { // fmt.Println("init failed, error:", err) // return // } // defer func() { // fmt.Println("d...
/* Write a function that splits a string into substrings of size n, adding a specified delimiter between each of the pieces. */ package main import ( "bytes" "fmt" ) func main() { fmt.Println(splitdelim("bellow", 2, "&")) fmt.Println(splitdelim("magnify", 3, ":")) fmt.Println(splitdelim("poisonous", 2, "~")) ...
package main import ( "fmt" "strings" ) func maps() { stocks := map[string]float64{ "AMZN": 1699.8, "GOOG": 1129.19, "MSFT": 98.61, // must trailing comma } // len fmt.Println(len(stocks)) // get fmt.Println(stocks["MSFT"]) // zero val if not found fmt.Println(stocks["TSLA"]) // = 0 // two val fo...
package bridge import ( "encoding/json" "incognito-chain/common" metadataCommon "incognito-chain/metadata/common" "incognito-chain/privacy" ) type UnshieldRequestData struct { IncTokenID common.Hash `json:"IncTokenID"` BurningAmount uint64 `json:"BurningAmount"` MinExpectedAmount uint64 `...
package config import ( "io/ioutil" "log" "os" "regexp" "strconv" "strings" ) var regexpsForConfig map[string]string = make(map[string]string) func init() { // build regexps map for parse config file regexpsForConfig["interval"] = "interval=(\\d+)" regexpsForConfig["port"] = "port=([\\w-]+)" regexpsForConf...
package bufferpool import ( "bytes" "errors" "io" "sync" ) var ( ENOBUF = errors.New("no such buffer can be used") GlobalPool = NewBufferPool(32) pReadCloser = sync.Pool{ New: func() interface{} { return &readCloser{} }, } pLimitedReader = sync.Pool{ New: func() interface{} { return &io.Limite...
package igitt import "github.com/nkprince007/igitt-go/github" // Repository represents a repository on any Git hosting provider like GitHub, // GitLab, etc. type Repository interface { FullName() string ID() int Description() string WebURL() string APIURL() string Homepage() string HasIssues() bool IsPrivate(...
package analyzer import ( "github.com/stretchr/testify/assert" "testing" ) // TestCase when an empty string is passed to the frequency analyzer func TestEmptyInputString(t *testing.T) { emptyString := "" fa := NewFrequencyAnalyzer(emptyString) actualWords := fa.Search() assert.Nil(t, actualWords) } // TestCas...
package env type Env interface { GetEnvs(appMode string) map[string]string } type EnvVariables struct{} func NewEnvService() Env { return &EnvVariables{} } func (e *EnvVariables) GetEnvs(appMode string) map[string]string { if appMode == "prod" { return prodMap } return devMap }
package device import ( "fmt" "github.com/uhppoted/uhppoted-lib/uhppoted" "github.com/uhppoted/uhppoted-mqtt/common" ) func (d *Device) GetDevices(impl uhppoted.IUHPPOTED, request []byte) (interface{}, error) { rq := uhppoted.GetDevicesRequest{} response, err := impl.GetDevices(rq) if err != nil { return co...
package main import ( "bareksa-test/database" d "bareksa-test/delivery" r "bareksa-test/repository" u "bareksa-test/usecase" "log" "net/http" "github.com/gorilla/mux" ) func main() { route := mux.NewRouter() // news newsRepository := r.InitiateNewsRepository(database.Databases) newsUsecase := u.InitiateN...
package config import ( "fmt" "github.com/tkanos/gonfig" "os" "path" "path/filepath" "runtime" "strings" ) // Configuration struct for the scrapper type Configuration struct { ConnectionString string DatabaseName string ReviewsURLFirstPage string WebsiteVisitorPar...
package main import "fmt" func main() { // ch1 := make(chan int) //unbuffered channel ch1 := make(chan int, 1) go func(in chan int) { val := <- in fmt.Println("GO: received from channel 1", val) fmt.Println("GO: after receipt") }(ch1) ch1 <- 42 ch1 <- 47 fmt.Println("MAIN: after sending to channel 1"...
package main import "fmt" func main() { for i := 0; i < 10; i++ { fmt.Printf("Outer Loop :: %d\n", i) for j := 0; j < 3; j++ { fmt.Printf("\tInner Loop :: %d\n", j) } } }
package aws import ( "log" "github.com/b2wdigital/goignite/pkg/config" ) const ( Key = "aws.access.key.id" Secret = "aws.secret.access.key" Region = "aws.default.region" Session = "aws.session.token" CustomEndpoint = "aws.custom.endpoint" ) func init() { log.Println("...
package acl import ( "encoding/json" "fmt" "github.com/uhppoted/uhppote-core/types" api "github.com/uhppoted/uhppoted-lib/acl" "github.com/uhppoted/uhppoted-lib/uhppoted" "github.com/uhppoted/uhppoted-mqtt/common" ) func (a *ACL) Grant(impl uhppoted.IUHPPOTED, request []byte) (interface{}, error) { body := st...
package confutil import ( "io" "os" "path" "github.com/pelletier/go-toml" "github.com/pkg/errors" ) const ( // DefaultBuildKitStateDir and DefaultBuildKitConfigDir are the location // where buildkitd inside the container stores its state. Some drivers // create a Linux container, so this should match the loc...
package parcels import ( "context" "strings" "unicode/utf8" ) const ( AlphabetNum = "0123456789" AlphabetEn = "abcdefghijklmnopqrstuvwxyz" AlphabetRu = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя" AlphabetUa = "абвгдеєжзиіїйклмнопрстуфхцчшщьюя" AlphabetPunct = `~!@#$%^&*()_-+={}[];:'"|\<...
package main import ( "fmt" "math/rand" ) func main() { sl := New() sl.Add(1) sl.Add(2) sl.Add(3) //sl.Delete(1) //sl.Delete(2) //sl.Delete(3) sl.Add(4) sl.Add(5) sl.Add(6) sl.Add(7) fmt.Println(sl.Search(1)) fmt.Println(sl.Search(4)) } func main2() { sl := New() sl.Add(1) sl.Add(2) sl.Add(3) ...
package main import "fmt" func maxProfit(prices []int) int { n := len(prices) if n < 2 { return 0 } minValue := prices[0] maxValue := prices[0] maxProfit := 0 for _, v := range prices { if v < minValue { minValue = v maxValue = v } if v > maxValue { maxValue = v } else { continue } p...
package main import ( "fmt" "zeroChain/blc" ) func main() { //block := blc.NewZeroBlock() //fmt.Println("当前时间戳:", block.TimeStamp) //fmt.Printf("前一个区块哈希: %x \n", block.PrevBlockHash) //fmt.Println("当前交易数据:", string(block.Data)) //fmt.Printf("当前区块哈希: %x\n", block.Hash) //fmt.Println("-------------------------...
package server func RunApiServer(options *OptionsV1) error { return nil }
package scraper import ( "github.com/GoranMandic91/euroleague_web_server/model" "github.com/yhat/scrape" "golang.org/x/net/html" "golang.org/x/net/html/atom" "net/http" "strings" "sync" ) func GetAllTeams() []interface{} { var arrayOfTeamNodes []*html.Node var allTeams []interface{} var wg sync.WaitGroup ...
package main import ( "fmt" ) func main() { switch { case false: fmt.Println("Prints") case true: fmt.Println("Don't print") } }
package queries import ( "database/sql" "log" "gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/attributes/models" "gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/configuration" ) const ADD_ATTRIBUTE_TO_EXISTING_RESOURCE_SQL = ` INSERT INTO resources."ResourcesAttributes" ( "Reso...
package config import ( "net" "net/url" "strconv" ) // NetAddress. type NetAddress struct { Host string Port int } // Network returns "". func (a NetAddress) Network() string { return "" } // String combines host and port into a network address of the // form "host:port". If host contains a colon, as found in...
package safesql import ( "fmt" "strconv" ) var user = struct { ID int32 Username string Password string Email string FullName string }{} func InsertUser() error { q := fmt.Sprintf("INSERT INTO users (username, password, email, fullname) VALUES (%d, %q, %q, %q, %q) returning id", user.ID, user.Userna...
package pkg import ( "fmt" "os" "github.com/olekukonko/tablewriter" ) type FileStats struct { SuccessLinks SuccessLinks FailedLinks FailedLinks } type SuccessLinks struct { Count int Links []Link } type FailedLinks struct { Count int Links []Link } type FilesStats []*FileStats func NewFileStats(file *F...
//go:generate mockery -dir . -name Controller -output ./mocks -filename controller.go package subscription import ( "context" "github.com/imrenagi/go-payment" ) type gateway interface { Gateway() payment.Gateway } type creator interface { gateway Create(ctx context.Context, sub *Subscription) (*CreateResponse...
package datadog import ( "context" "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus/ctxlogrus" "github.com/sirupsen/logrus" "google.golang.org/grpc" "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer" ) // LogrusDDTraceContextInjector adds dd.trace_id, dd.span_id as logrus entry fields and puts new log...
package main import ( "encoding/hex" "encoding/json" "flag" "fmt" "log" "net/http" "time" "os" "github.com/eoscanada/eos-go" "github.com/eoscanada/eos-go/ecc" eosvault "github.com/eoscanada/eosc/vault" ) var keysFile = flag.String("keys-file", "", "keys file") var walletFile = flag.String("wallet-file", ...
package leetcode type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func isBalanced(root *TreeNode) bool { _, has := check(root) return !has } //[3,9,20,null,null,15,7] func check(node *TreeNode)(int, bool){ if node == nil{ return 0, false } left, leftHas := check(node.Left) right, rightHas :...
/* Description As the host of a popular daytime television talk show, you are working through the details of an upcoming episode on dieting. Your guest is the controversial Dr. Kevorkian, who has recently invented his own weight-loss plan, "Do You Want To Diet?" that guarantees to reduce your body weight by 1 pound e...
// Copyright 2023 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 ( "bytes" "flag" "fmt" "io/ioutil" "log" "net/http" "net/http/httputil" "net/url" ) type myTransport struct { } func (t *myTransport) RoundTrip(request *http.Request) (*http.Response, error) { buf, _ := ioutil.ReadAll(request.Body) // rdr1 := ioutil.NopCloser(bytes.NewBuffer(buf)) rdr...
package pie import "math" // SequenceUsing generates slice in range using creator function // // There are 3 variations to generate: // 1. [0, n). // 2. [min, max). // 3. [min, max) with step. // // if len(params) == 1 considered that will be returned slice between 0 and n, // where n is the first param, [0, n). ...
package main import ( "bytes" "encoding/json" "net/http" "net/http/httptest" "os" "strings" "testing" "time" mgo "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) var fichaTest = DatosBasicos{ bson.NewObjectId(), "Degue", "123", time.Now(), "Victor Samuel", "Mosquera Artamonov", "CedulaCiudadania", 108799800...
package client import ( "bufio" "log" "net" "github.com/VanBur/tcp-chat/internal/message" ) func New(connection net.Conn) *Client { client := &Client{ Register: make(chan string), Leave: make(chan string), Broadcast: make(chan *message.Message), Outgoing: make(chan *message.Message), reader: ...
package events import ( "encoding/json" "testing" "github.com/franela/goblin" . "github.com/onsi/gomega" ) func TestDeliveryEvents(t *testing.T) { g := goblin.Goblin(t) RegisterFailHandler(func(m string, _ ...int) { g.Fail(m) }) g.Describe("Delivery Events", func() { g.It("should unmarshal a delivery event...
package main import ( "encoding/json" "fmt" "io/ioutil" "os" "github.com/spf13/cobra" ) var ConfigCmd = &cobra.Command{ Use: "config", Short: "Manage customer's cards.", RunE: runConfig, } func init() { ConfigCmd.AddCommand(ConfigGetCmd, ConfigSetCmd) } var ConfigGetCmd = &cobra.Command{ Use: "get",...
package main import ( "fmt" "os" "time" ) type VMInstance struct { Path string `json:"path"` Type string Value string ID CloudInstance } type CloudInstance struct { CloudID int } var Student = map[string]string{"name": "zhang", "age": "16"} type VMObject struct { Datacenter []VMIn...
package main import ( "fmt" "log" "github.com/shanghuiyang/face-recognizer/face" "github.com/shanghuiyang/go-speech/oauth" "github.com/shanghuiyang/rpi-devices/dev" ) const ( groupID = "mygroup" // replace your_app_key and your_secret_key with yours appKey = "your_app_key" secretKey = "your_secret_key" ...
// Copyright © 2020 Attestant Limited. // 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 ...
package easy import ( "fmt" "strconv" "testing" ) func Test35(t *testing.T) { nums := []int{1,3,5,6,7,9} val := 4 b := searchInsert(nums,val) fmt.Println(b) fmt.Println(nums) } func searchInsert(nums []int, target int) int { index := 0 for k,v := range nums { if v == target { index =k break } ...
// Copyright 2020 Yaacov Zamir <kobi.zamir@gmail.com> // and other contributors. // // 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 // // U...
package practice func isValid(s string) bool { var stack []rune outer: for _, c := range s { for _, p := range [][2]rune{ {'(', ')'}, {'[', ']'}, {'{', '}'}, } { if c == p[1] { if len(stack) == 0 { return false } if stack[len(stack)-1] != p[0] { return false } stack =...
package common import ( "incognito-chain/privacy/coin" "incognito-chain/privacy" "incognito-chain/common" ) // Interface for all types of metadata in tx type Metadata interface { GetType() int Sign(*privacy.PrivateKey, MDContainer) error Hash() *common.Hash HashWithoutSig() *common.Hash IsMinerCreatedMetaTyp...
package log import ( "github.com/op/go-logging" "os" ) var logger *logging.Logger func Debug(args ...interface{}) { logger.Debug(args...) } func Info(args ...interface{}) { logger.Info(args...) } func Warning(args ...interface{}) { logger.Warning(args...) } func Error(args ...interface{}) { logger.Error(arg...
package skip_list import ( "fmt" "math/rand" "os" "strings" "testing" ) func printSkipList(skipList *SkipList) { println(skipList.keyword) head := skipList.head for head != nil { // fmt.Printf("%v ", head) println(head.toString()) println("=============================") if len(head.next) < 1 { br...
package xpost import ( // "log" ) // Master implement a Base class of Courier // All the user defined Couriers should have Master as an anonymous member type Master struct { id int wirecap int sender bool // a sender only produce message and never receive message from the wire name string xp *Xpost...
package minnow import ( "math/rand" "strings" "testing" "time" ) func randomString(length int) string { var builder strings.Builder chars := "abcdefghijklmnopqrstuvwxyz0123456789" rand.Seed(time.Now().UnixNano()) for i := 0; i < length; i++ { c := string(chars[rand.Intn(len(chars))]) builder.WriteString(...
package gluatemplate import ( "github.com/yuin/gopher-lua" "io/ioutil" "os" "testing" ) func TestDoString(t *testing.T) { L := lua.NewState() defer L.Close() L.PreloadModule("template", Loader) if err := L.DoString(` local template = require("template") local output = template.dostring([[ This is a text tem...
// Package dbg provided methods to write debug message to standard logger, // which can be disabled at runtime and build time. // +build !release package dbg import ( "fmt" "log" ) // Enabled reports whether debug output is enabled. const Enabled = true var prefix = `(D) ` func init() { log.SetFlags(log.Ltime ...
package convert import "fmt" // FixedXOR returns two equal-length byte arrays XORed with each other func FixedXOR(b1, b2 []byte) ([]byte, error) { if len(b1) != len(b2) { return nil, fmt.Errorf("FixedXOR needs equal length byte arrays") } res := make([]byte, len(b1)) for i, v1 := range b1 { res[i] = v1 ^ b2[i...
// pkg/go/parser/parseexprfrom. package main // TODO: fix import ( "go/ast" "go/format" "go/token" "os" ) func main() { ident := ast.NewIdent("AutoGenerated") ident.Obj = ast.NewObj(ast.Typ, "struct") ident.Obj.Decl = ast.Field{ Names: []*ast.Ident{ ast.NewIdent("hello"), }, } err := format.Node(os....
package leetcode // TODO func maxSlidingWindow(nums []int, k int) []int { return nums }
package main import ( //"context" "database/sql" "encoding/csv" "fmt" "io" "io/ioutil" "log" "os" "strings" "sync" //外部ファイル "github.com/gin-gonic/gin" _ "github.com/denisenkom/go-mssqldb" "github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions/cookie" ) type User struct...
package service import ( "errors" "math/rand" "../entity" "../repository" ) type service struct{} type Components struct { Components []Component `json:"types"` } type Component struct { ID string `json:"ID"` Name string `json:"Name"` Description string `json:"Description"` } var ( repo ...
package main import ( "crypto/ecdsa" "crypto/md5" "crypto/rand" "ecdsa/base58Encrypt" "ecdsa/genKey" "ecdsa/ripemdEncrypt" "ecdsa/shaEncrypt" "fmt" "hash" "io" "math/big" "os" ) type Node struct { pubKey []byte privateKey *ecdsa.PrivateKey bitcoinAddress string signHash []uint8 signature...
package regulation import ( "context" "net" "github.com/authelia/authelia/v4/internal/configuration/schema" "github.com/authelia/authelia/v4/internal/storage" "github.com/authelia/authelia/v4/internal/utils" ) // Regulator an authentication regulator preventing attackers to brute force the service. type Regulat...
package setr import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document01200103 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:setr.012.001.03 Document"` Message *SubscriptionOrderConfirmationV03 `xml:"SbcptOrdrConfV03"` } func (d *Do...
package proxy import ( "strconv" "sync" "github.com/colefan/gsgo/netio" ) //服务器节点 type ServerNode struct { NodeType uint16 //服务器类型 Ip string //连接的IP Port uint16 //连接的端口 key string //存储关键字 onlines int //在线用户数 GameId uint32 //游戏ID,为非游戏时填写0 GameAreaId ...
// DO NOT EDIT!!! package options type Option func(options *Embedded) func OptionEmbed(option struct { some int fields string in struct{} lined []uint8 }) Option { return func(options *Embedded) { options.Embed = option } }
package main import gc "github.com/rthornton128/goncurses" //TODO: 改行はできているが、そのあとの画面のリフレッシュがうまく行かない func (v *View) insertNewLine() { str_copy := []byte(v.file.buf[v.cursor.text_y]) oline := str_copy[0:v.cursor.x] nline := str_copy[v.cursor.x:] if len(nline) == 0 { nline = []byte(" ") } v.file.buf = append(v....
package main import ( "net/http" "universe/handler/db" "universe/handler/engine" "universe/handler/misc" "universe/spider" "github.com/andy-zhangtao/golog" "github.com/gorilla/mux" ) func main() { golog.Debug("universe") go spider.Start("") r := mux.NewRouter() r.HandleFunc("/db/metadata/add", db.Modify...
// Copyright alphaair 2016 // 这是一个数字矩阵藏宝游戏,来源来最强大脑节点,矩阵藏有五个质数,但是只有 package amusing import "math/rand" // MatrixConceal 矩阵藏地图 type MatrixConceal struct { Result [][]int } // newNum生成一个指定范围内的随机数 func (m *MatrixConceal) newNum(min int, max int) int { n := rand.Intn(max+1) for ; n < min; { ...
package leetcode func prefixesDivBy5(A []int) []bool { ans := make([]bool, len(A)) m := 0 t := [][]int{ []int{0, 1}, []int{2, 3}, []int{4, 0}, []int{1, 2}, []int{3, 4}, } for i, v := range A { m = t[m][v] ans[i] = m == 0 } return ans }
package main import ( "testing" ) func Test_CreateGrid(t *testing.T) { cases := []struct { name string actual string expected int }{ { name: "example", actual: "example.input", expected: 31, }, // { // name: "large example", // actual: "large.input", // expected: 617...
package controller import ( "encoding/json" "fmt" "github.com/gorilla/mux" "model" "net/http" "strconv" ) /* handler function for GET method */ var SelectProducts = func(w http.ResponseWriter, r *http.Request) { products := []model.Product{} err := GetDB().Table("products").Find(&products).Error if err != ni...
package http import ( "bytes" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "net/url" "strings" ) // post请求 json格式 func JsonPostRequest(url string, headerMap, params map[string]interface{}) string { bytesData, err := json.Marshal(params) if err != nil { fmt.Println(err.Error() ) } reader := bytes.N...
package main import ( "fmt" "github.com/tvacare/web-crawler/paper" "github.com/tvacare/web-crawler/website" ) func crawler() []paper.Paper { // Get all papers URL papersLinks := website.GetLinks(LINK, URLBASE) papers := make([]paper.Paper, 0) // cn := make(chan Paper) // Get slice of papers and remove pa...
package main import ( "container/list" "log" ) func braceMatching(l string) bool { stack := list.New() for _, v := range l { top := stack.Back() if top == nil { stack.PushBack(v) continue } switch top.Value { case '(': if v == ')' { stack.Remove(top) } else { stack.PushBack(v) ...
package optionsgen_test import ( "net" "net/http" "testing" testcase "github.com/kazhuravlev/options-gen/options-gen/testdata/case-05-generics-02" "github.com/stretchr/testify/assert" ) func TestGenericsOptions(t *testing.T) { t.Run("validation failed", func(t *testing.T) { opts := testcase.NewOptions[string...
package main import ( "bytes" "crypto/tls" "encoding/json" "errors" "fmt" "io/ioutil" "log" "net/http" ) // Icinga2 represents an icinga2 server type Icinga2 struct { Host string Username string Password string } type ObjectType string // Type of element to monitor in icinga const ( SERVICES = "serv...
// Copyright 2020 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 pie // Diff returns the elements that needs to be added or removed from the first // slice to have the same elements in the second slice. // // The order of elements is not taken into consideration, so the slices are // treated sets that allow duplicate items. // // The added and removed returned may be blank ...
package engine import ( "fmt" "re/dal" "github.com/pkg/errors" ) /* 根据 combination 遍历 rules 每个 rule 根据 path 找到 domain,如果未存在,执行构造函数脚本 得到 domain 后,获取 factor 如果缓存中未存在,执行factor的构造函数 获取 operation,将 factor 和 rule 的 args 传入 */ type domainStatus struct { id int bridgeCode string factorCache map[s...
package main import "fmt" func main() { cities := make(map[string]string) cities["no1"] = "北京" cities["no2"] = "上海" cities["no3"] = "深圳" //map的查找---------------------------------------- val, ok := cities["no4"] if ok { fmt.Println("根据key查找value,val=", val) } else { //找不到则无返回 fmt.Println("根据key查找value,找不...
package main import ( "bytes" "encoding/json" "fmt" "io" "log" "net" "net/http" "os" "sync/atomic" "time" pb "github.com/serhatcetinkaya/grpc-demo-app/proto/math" "google.golang.org/grpc" ) type server struct{} type Host struct { IP string `json:"ip_address"` Port int `json:"port"` Tags struct ...
func test(in *Value, param *Value) (*Value, *Error) { output := strings.Replace(in.String(), "\\", "\\\\", -1) output = strings.Replace(output, "\"", "\\\"", -1) output = strings.Replace(output, "'", "\\'", -1) return AsValue(output), nil }
package main import ( "database/sql" "errors" "fmt" _ "github.com/go-sql-driver/mysql" ) const ( mysqlUser = "videoservice" mysqlPassword = "1234" mysqlHost = "" ) // VideoRow - represents one `video` SQL table row. type VideoRow struct { key string title string url string duratio...
package main import ( "log" "strings" "github.com/go-rod/rod" "github.com/go-rod/rod/lib/input" ) //This example demonstrates how to fill out and submit a form. func main() { page := rod.New().Connect().Page("https://github.com/search") page.Element(`input[name=q]`).WaitVisible().Input("chromedp").Press(input...
package main import ( "fmt" "net/http" "log" "strconv" "strings" g "github.com/soniah/gosnmp" ) func main() { g.Default.Target = "127.0.0.1" err := g.Default.Connect() if err != nil { log.Fatalf("Connect() err: %v", err) } defer g.Default.Conn.Close() oids := []string{"1.3.6.1.2.1.1.4.0", "1.3.6.1.2....
package main import ( "bytes" "encoding/json" "errors" "io" "net/http/httptest" "testing" "time" "github.com/jonmorehouse/gatekeeper/gatekeeper" "github.com/jonmorehouse/gatekeeper/gatekeeper/test" "github.com/jonmorehouse/gatekeeper/gatekeeper/utils" ) func fixtureUpstream() *gatekeeper.Upstream { return...
package main import ( "github.com/jack0liu/vastflow" uuid "github.com/satori/go.uuid" "time" ) func main() { // headerwaters set vastflow.InitVastFlowDb("vastflow.json", "") hw := vastflow.NewHeadwaters(uuid.NewV4().String()) hw.Put("vmName", "my-vm") hw.Put("volName", "my-vol") // parallel river draw pr :...
package main import "testing" import "math/rand" import "time" func TestStart(t *testing.T) { rand.Seed(time.Now().UnixNano()) number := rand.Intn(10) c := AContext{ CurrentState: &FinishState{}, Number: number, } c.prntState() if c.CurrentState.Name() != "finish" { t.Error("At FinishState game s...
// Copyright 2015 Google Inc. All rights reserved. // Use of this source code is governed by the Apache 2.0 // license that can be found in the LICENSE file. package bookshelf import ( "errors" "fmt" "sort" "sync" ) // Ensure memoryDB conforms to the BookDatabase interface. var _ BookDatabase = &memoryDB{} // m...
package models import ( "github.com/jinzhu/gorm" ) // Person Model type Person struct { gorm.Model FirstName string `json:"fname" binding:"required"` LastName string `json:"lname" binding:"required"` Description string `json:"desc" gorm:"type:text"` }
package week21 import "fmt" func generateParenthesis(n int) []string { if n == 0 { return []string{""} } // 分组方法(a)b // generateSub(a), generateSub(b) var ans []string // 0的情况已经排除,从1开始遍历 // a始终少一个初始化的括号,所以 a -> k-1 // b的推导流程 //-> a + b + 1 = n a的括号数+b的括号数+初始化的1 = 总括号数量 //-> k - 1 + b + 1 = n 代入 a ...
package tracing import ( "time" "contrib.go.opencensus.io/exporter/jaeger" "contrib.go.opencensus.io/exporter/ocagent" "contrib.go.opencensus.io/exporter/zipkin" openzipkin "github.com/openzipkin/zipkin-go" zipkinhttp "github.com/openzipkin/zipkin-go/reporter/http" "github.com/owncloud/ocis-hello/pkg/config" ...
package game_map import ( "fmt" "github.com/faiface/pixel" "github.com/steelx/go-rpg-cgm/combat" "github.com/steelx/go-rpg-cgm/world" "reflect" ) type CESteal struct { mOwner *combat.Actor mName string mCountDown float64 mIsFinished, Success bool SpecialItem world...
package es import ( gj "github.com/kpawlik/geojson" ) const ( typeNameCircleQuery = "circle" typeNamePointQuery = "point" ) type ESCustomShapeQuery struct { GeoShape ESGeoShapeQuery `json:"geo_shape"` } type ESGeoShapeQuery struct { Location ESLocationQuery `json:"location"` } type ESLocationQuery struct { ...
package styles import ( "bytes" "encoding/json" "fmt" "github.com/google/go-querystring/query" "github.com/tumasgiu/go-mapbox/lib/base" "io/ioutil" "net/http" "net/url" ) // Styles api wrapper instance type Styles struct { base *base.Base } // NewStyles Create a new Styles API wrapper func NewStyles(base *b...
/* Copyright 2021 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, so...
package util import ( "testing" "github.com/stretchr/testify/assert" ) var origWF = ` apiVersion: argoproj.io/v1alpha1 kind: Workflow metadata: generateName: workflow-template-hello-world- spec: arguments: parameters: - name: message value: original entrypoint: start onExit: end serviceAcco...