text
stringlengths
11
4.05M
package fimap import ( "testing" "github.com/valyala/fastrand" ) var smallSet, mediumSet, largeSet []keyType func initializeSet(size int) []keyType { v := make([]keyType, size) for i := range v { v[i] = 1 + keyType(fastrand.Uint32n(2000000000)) } return v } func init() { smallSet = initializeSet(1024) me...
//************************************************************************// // rsc - RightScale API command line tool // // Generated with: // $ praxisgen -metadata=ss/ssd/restful_doc -output=ss/ssd -pkg=ssd -target=1.0 -client=API // // The content of this file is auto-generated, DO NOT MODIFY //*...
package main import "testing" func TestCountTheWays_String(t *testing.T) { var c = CountTheWays([]int{1, 2}) tests := []struct { name string c *CountTheWays want string }{ {"base-case", &c, "1 ... 2"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := tt.c.String(); got !...
package piscine import "github.com/01-edu/z01" //import "fmt" func IsNegative(nb int) { if nb < 0 { z01.PrintRune(84) } else { z01.PrintRune(70) } z01.PrintRune(10) } func PrintComb(){ for i:='0'; i <= '9'; i++{ for j:='0'; j <= '9'; j++{ for k:='0'; k <= '9'; k++{ if i < j && j < k { z01.P...
package main import ( "bytes" "crypto/tls" "crypto/x509" "encoding/base64" "encoding/json" "flag" "fmt" "html/template" "image/png" "io/ioutil" "mime" "net/http" "os" "path" "strings" "time" "bitbucket.org/cicadaDev/utils" log "github.com/Sirupsen/logrus" "github.com/dgrijalva/jwt-go" "github.com/...
package myeth import ( "bytes" "encoding/json" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" "github.com/golang/glog" "golang.org/x/net/context" "google.golang.org/grpc/naming" "math/big" "sync" "time" ) const REFLAS...
// 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 core func NewBoolean(value bool) *Type { return &Type{Boolean: &value} } func (node *Type) IsBoolean() bool { return node.Boolean != nil } func (node *Type) AsBoolean() bool { if node.IsBoolean() { return *node.Boolean } return false } func (node *Type) CompareBoolean(value bool) bool { if node.IsBo...
package main import ( "net" "time" ) // Notifier stores and notifies client connections about stuff type Notifier interface { AddClient(UserClient) Notify(string, Message) } // TCPConnectionNotifier handles TCP connections type TCPConnectionNotifier struct { clients map[string][]chan string } // NewTCPNotifier...
package main import ( "fmt" "webapp/persistence/dao" "webapp/persistence/bolt" "webapp/entities" ) func main() { fmt.Println("DAO testing ") fmt.Println("In memory DAO testing ") dao.SetDAOImplementation(dao.MEMORY) testDao(dao.GetStudentDAO()) fmt.Println("Bolt DAO testing ") bolt.BoltStart("boltdb.data...
package main import ( "flag" "fmt" "io/ioutil" "log" "net/http" "time" "github.com/gin-gonic/gin" "github.com/polarismesh/polaris-go" "github.com/polarismesh/polaris-go/pkg/model" ) var ( namespace string service string port int64 ) func initArgs() { flag.StringVar(&namespace, "namespace", "def...
package ascii import ( "bufio" "fmt" "io" "net/http" "strings" ) func check(e error) { if e != nil { panic(e) } } func Art(input string, template string, w http.ResponseWriter) { lines, err := UrlToLines("https://git.01.kood.tech/root/public/raw/branch/master/subjects/ascii-art/" + template + ".txt") chec...
package encode import ( "strconv" "strings" "unicode" ) // RunLengthEncode compresses a string using run-length encoding. func RunLengthEncode(s string) string { b := &strings.Builder{} var prev rune var count int for _, r := range s { if r == prev { count++ } else { writeRune(b, count, prev) prev...
package dcp // At a popular bar, each customer has a set of favorite drinks, and will happily accept any drink among this set. For example, in the following situation, customer 0 will be satisfied with drinks 0, 1, 3, or 6. // preferences = { // 0: [0, 1, 3, 6], // 1: [1, 4, 7], // 2: [2, 4, 7, 5], // ...
package cmd import ( "github.com/oberd/ecsy/ecs" "github.com/spf13/cobra" ) //var taskArn string // deployNewestTaskCmd represents the updateServiceTask command var deployNewestTaskCmd = &cobra.Command{ Use: "deploy-newest-task [cluster] [service]", Short: "deploy newest task definition to a service", ...
package dict import "context" type Dictionary interface { Search(ctx context.Context, word string) (*Word, error) } type Pronunciation struct { US string `json:"us"` US_MP3URL string `json:"us_mp3url"` UK string `json:"uk"` UK_MP3URL string `json:"uk_mp3url"` } type Def struct { PartOfSpeech str...
package main import ( "fmt" ) /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ type ListNode struct { Val int Next *ListNode } func isPalindrome(head *ListNode) bool { if head == nil { return false } // 申请一个slice,将链表的所有值放入slice中,然后再对map做比较 ...
package RateLimiter import ( "encoding/json" "fmt" "strings" "testing" "time" ) //Lol more like testing then actual test func init() { gl := NewLimiterGroupAnd(NewLimiter(time.Second, 3), NewLimiterGroupOr(NewLimiter(time.Second, 2), NewLimiter(time.Second*5, 4))) for i := 0; i < 5; i++ { fmt.Printf("rem:%d,%...
package factories import ( "errors" "fmt" "github.com/barrydev/api-3h-shop/src/constants" "github.com/barrydev/api-3h-shop/src/helpers" "github.com/barrydev/api-3h-shop/src/model" "github.com/dgrijalva/jwt-go" "github.com/gin-gonic/gin" ) type AccessTokenClaims struct { Id int64 `json:"_id"` Role int64 `j...
package main import ( "fmt" ) // https://leetcode-cn.com/problems/word-ladder/ func ladderLength(beginWord string, endWord string, wordList []string) int { n := len(wordList) if n == 0 { return 0 } isOK := func(a, b string) bool { diff := 0 for i := 0; i < len(a) && diff < 2; i++ { if a[i] != b[i] { ...
package model import ( "time" ) type File struct { Name string `json:"name"` FullPath string `json:"fullPath"` IsDir bool `json:"isDir"` Size int64 `json:"size"` FileType string `json:"fileType"` Created time.Time `json:"created"` Modified time.Time `json:"modified"` Accessed time....
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-07-27 09:53 # @File : lt_142_Linked_List_Cycle_II.go # @Description : 如果有环,返回入环节点 # @Attention : 如果碰撞了,则fast 到head 处步调一致移动 错误点: 当碰撞之后,slow 要移动到slow的下一个节点 既slow=slow.next */ package v0 func detectCycle(head *ListNode) *ListNode { if head == nil || hea...
package repository import ( "arep/config" "arep/model" "context" "encoding/json" "github.com/olivere/elastic" "log" "strconv" ) type ElasticRepository struct { client *elastic.Client } var ElasticStoresIndex = config.ElasticStoresIndex func NewElasticRepository(config *config.ElasticConfiguration) (*Elastic...
// // riak-statsd // Sends Riak stats to statsd every 60s. // // Usage: // -nodename="riak": Riak node name // -riak_host="127.0.0.1": Riak host // -riak_http_port=8098: Riak HTTP port // -statsd_host="127.0.0.1": Statsd host // -statsd_port=8125: Statsd host package main import ( "encoding/json" "errors...
package main import ( "../" "fmt" "io" "log" "net/http" "time" "github.com/gin-gonic/gin" _ "github.com/go-sql-driver/mysql" "github.com/itsjamie/gin-cors" "github.com/jinzhu/gorm" ) func initDatabase(db *gorm.DB) { var err error *db, err = gorm.Open("mysql", "brave:brave@/brave?charset=utf8&parseTime=Tr...
package main import ( "context" "net/http" "os" "os/signal" "time" "go.uber.org/zap" "prometheus-alertmanager-dingtalk/config" "prometheus-alertmanager-dingtalk/dingtalk" "prometheus-alertmanager-dingtalk/zaplog" ) func init() { config.SetupInit() zaplog.SetupInit() dingtalk.SetupInit() http.HandleFun...
package socket import ( "jmcs/core/utils/net/port" "jmcs/core/utils" "strings" "github.com/goinggo/mapstructure" "net" "fmt" "errors" "bytes" "sync" ) type socket struct { Enable bool Port port.Port HeartEnable bool } var conf socket const ( CONF_NAME = "net.socket" //配置名称,靠这个解析出该应用具体配置 ) ...
package blockchain import ( "log" "time" "bytes" "encoding/gob" "crypto/sha256" "encoding/binary" ) // 区块结构 type Block struct { Version uint64 // 版本号 PrevHash []byte // 前区块哈希 MerkleRoot []byte // 梅克尔根 TimeStamp uint64 // 时间戳 Difficulty uint64 // 难度值 Nonce uint64 // 随机数 Hash []byte...
// Jamar Flowers // golang simple server 1 // Project: create simple go server to send response as hello world to browser // 5/27/18 package main import ( "io" "net/http" ) // the function // Hello is a response function to be called by our handler func hello(w http.ResponseWriter, r *http.Request) { io.WriteStr...
package routes import ( "fmt" "io" "github.com/complyue/ddgo/pkg/dbc" "github.com/complyue/ddgo/pkg/livecoll" "github.com/complyue/hbigo/pkg/errors" "github.com/globalsign/mgo" "github.com/globalsign/mgo/bson" "github.com/golang/glog" ) func coll() *mgo.Collection { return dbc.DB().C("waypoint") } // in-me...
package leetcode import "testing" func TestPivotIndex(t *testing.T) { if pivotIndex([]int{1, 7, 3, 6, 5, 6}) != 3 { t.Fatal() } if pivotIndex([]int{1, 2, 3}) != -1 { t.Fatal() } }
package feed type Feeds struct { Id int `json:"id"` Txt string `json:"txt"` }
package spider import ( "context" "errors" "io/ioutil" "net/http" "net/url" "strconv" "go.uber.org/zap" ) type httpResponseError struct { statusCode int } func (e httpResponseError) Error() string { return "http response error: " + strconv.Itoa(e.statusCode) } // Requester is something that can make a req...
package aoc2016 import ( "testing" aoc "github.com/janreggie/aoc/internal" "github.com/stretchr/testify/assert" ) func Test_newIpv7Address(t *testing.T) { assert := assert.New(t) testCases := []struct { input string want ipv7Address }{ {input: "abba[mnop]qrst", want: []struct { raw string ...
package application import ( "net/http" md "github.com/ebikode/eLearning-core/model" tr "github.com/ebikode/eLearning-core/translation" ut "github.com/ebikode/eLearning-core/utils" validation "github.com/go-ozzo/ozzo-validation" ) // ApplicationService provides application operations type ApplicationService in...
package converters import ( "encoding/json" "errors" "github.com/fintechstudios/ververica-platform-k8s-operator/api/v1beta1" vpAPI "github.com/fintechstudios/ververica-platform-k8s-operator/appmanager-api-client" ) // DeploymentMetadataToNative converts a Ververica Platform deployment into its native K8s represe...
package config import ( "io/ioutil" ) type Config struct { Docker_Host struct { Ssh_Config string Host string } Docker_Container struct { Image string Mount string Before_All string Command string Filter string } Cargo struct { Debug bool GroupBy string Concu...
package instrumented import ( "context" "github.com/prometheus/client_golang/prometheus" pubsub "github.com/utilitywarehouse/go-pubsub" ) // ConcurrentMessageSource is an an Instrumented pubsub MessageSource // The counter vector will have the labels "status" and "topic" type ConcurrentMessageSource struct { imp...
package main import ( "fmt" "os" ) var ( version string buildTime string ) type app struct { config struct { ConfigPath string Token string } opts struct { Version bool `short:"v" long:"version" description:"Displays version and build info"` Credit bool `short:"c" long:"credit" des...
package omsi import ( "fmt" "testing" ) func Test_New(t *testing.T) { om := New() if om.Map == nil { t.Error("map failed to initialize after calling New.") } } func Test_Set(t *testing.T) { om := New() om.Set("cat", "funny") link := om.Map["cat"] if link.value != "funny" { t.Error("Set failed to set ...
package model import ( "errors" ) // 房间管理着一局棋局和玩家 type Room struct { Id int64 `json:"id" xorm:"pk autoincr int(11)"` PlayerId int64 `json:"player_id" xorm:"int(11)"` // 房主 PlayerStatus PlayerStatus `json:"player_status" xorm:"json"` TimeToPlayerId int64 `json:"timeto_play...
package contextio import ( "fmt" "io" "io/ioutil" "net/http" "net/url" "github.com/garyburd/go-oauth/oauth" ) const ( GetUsersEndPoint = "https://api.context.io/lite/users" GetAttachmentsEndPoint = "https://api.context.io/lite/users/%s/email_accounts/%s/folders/%s/messages/%s/attachments/%s" ) type Us...
package controllers import ( "errors" "fmt" "io/ioutil" "net" "reflect" "strconv" "strings" "sync" "syscall" "time" "github.com/cloudnativelabs/kube-router/app/options" "github.com/cloudnativelabs/kube-router/app/watchers" "github.com/cloudnativelabs/kube-router/utils" "github.com/coreos/go-iptables/ipt...
package qdn import ( "bytes" "errors" "reflect" "strconv" "strings" ) // Format returns the raw byte data in a more readable state for use in a text editor. // Keep in mind that this uses considerable amounts of system resources, // so its not adviseable for plain network transmissions func Format(r []byte) ([]b...
/* * Copyright 2017 StreamSets 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...
// problem 9.9 package chapter9 func consumePreorder(vs []string, st int) (*TreeNode, int) { if vs[st] == "null" { return nil, 1 } else { elem := &TreeNode{Value: vs[st]} left, lc := consumePreorder(vs, st+1) elem.Left = left right, rc := consumePreorder(vs, st+1+lc) elem.Right = right return elem, lc...
package turnstile import ( "bytes" "encoding/json" "io" "io/ioutil" "log" "net/http" "sync" "time" "github.com/caddyserver/caddy" "github.com/caddyserver/caddy/caddyhttp/httpserver" ) // Turnstile is a Caddy middleware which records incoming traffic to a // downstream Telegram bot. type Turnstile struct { ...
package flags type Uint64 uint64 func (f Uint64) Add(b ...Uint64) Uint64 { for i := 0; i < len(b); i++ { f = f | b[i] } return f } func (f Uint64) Remove(b ...Uint64) Uint64 { for i := 0; i < len(b); i++ { f = f ^ b[i] } return f } func (f Uint64) Intersect(b ...Uint64) Uint64 { s := Uint64(0).Add(b...) ...
package store import ( "fmt" "time" ) type GetResult struct { Err error Value string } type Store interface { // Get gets a value by key // If the key is not found in the store, the Err is nil and Value is empty Get(key string) GetResult // MultiGet is a batch version of Get MultiGet(keys []string) map[s...
package model import ( "github.com/graphql-go/graphql" "go.mongodb.org/mongo-driver/bson/primitive" ) // Position represents a F1 Position type Position struct { ID primitive.ObjectID `json:"id" bson:"_id"` DriverID string `json:"-" bson:"driverId"` Driver Driver `json:"driver" bs...
/////////////////////////////////////////////////////// // 리플렉션 사용하기 /////////////////////////////////////////////////////// //리플렉션은 실행 시점(Runtime, 런타임)에 인터페이스나 구조체 등의 타입 정보를 얻어내거나 결정하는 기능입니다. /* //간단하게 변수와 구조체의 타입을 표시해보겠습니다. package main import ( "fmt" "reflect" ) type Data struct { // 구조체 정의 a, b int } func m...
package zfs import ( "testing" ) func TestDestroySnapshot(t *testing.T) { err := DestroySnapshot(*testPool+"/tank2/tank1@zfs-auto-snap_daily-2019-06-05-1707") if err != nil { t.Log(err) } }
package order type CreateOrderReq struct { Quantity int `json:"quantity"` ProductId int64 `json:"productId"` UserId int64 `json:"userId"` Fare float64 `json:"fare"` DiscountAmt float64 `json:"discountAmt"` }
package osinserver import ( "github.com/RangelReale/osin" mgostore "github.com/nguyenxuantuong/osin-mongo-storage" "github.com/byrnedo/apibase/db/mongo/defaultmongo" ) var Server *osin.Server func init() { config := osin.NewServerConfig() sstorage := mgostore.NewOAuthStorage(defaultmongo.Conn(), "oauth_osin") ...
package web_service import ( "2021/yunsongcailu/yunsong_server/web/web_dao" "2021/yunsongcailu/yunsong_server/web/web_model" ) type WebsiteServer interface { GetWebsiteInfo() (websiteInfo web_model.WebsiteModel,err error) } type websiteServer struct {} func NewWebsiteServer() WebsiteServer { return &websiteServ...
package main import ( "fmt" "strconv" ) func part1(add int) string { scoreboard := []int{3, 7} elf1, elf2 := 0, 1 for len(scoreboard) < 10+add { newScores := scoreboard[elf1] + scoreboard[elf2] if newScores > 9 { scoreboard = append(scoreboard, 1) } scoreboard = append(scoreboard, newScores%10) elf...
/* Write a program that takes in a string and spells that word out using the NATO Phonetic Alphabet. The mapping is as follows: 'A' -> 'Alfa' 'B' -> 'Bravo' 'C' -> 'Charlie' 'D' -> 'Delta' 'E' -> 'Echo' 'F' -> 'Foxtrot' 'G' -> 'Golf' 'H' -> 'Hotel' 'I' -> 'India' 'J' -> 'Juliett' 'K' -> 'Kilo' 'L' -> 'Lima' 'M' -> '...
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package util import ( "crypto/tls" "fmt" "net/http" "time" "github.com/vespa-engine/vespa/client/go/build" ) type HTTPClient interface { Do(request *http.Request, timeout time.Duration) (response *http.Resp...
package entity import "time" type Company struct { ID int Name string `gorm:"not null"` BranchName string `gorm:"not null"` PassWord string Address string Phone string Describe string `gorm:"type:text"` ThirdTradeNoPrefix string AppId string `gorm:"type:varchar(64);unique;not...
package main import "strings" // 判断两个字符串排序之后是否相等 func isRegroup(s1, s2 string) bool { sl1 :=len([]rune(s1)) sl2 :=len([]rune(s2)) if sl1 >5000 ||sl2 >5000 || sl1 !=sl2 { return false } for _, v := range s1 { if strings.Count(s1,string(v)) !=strings.Count(s2,string(v)) { return false } } return true ...
package application import ( "github.com/crossplane/crossplane-runtime/apis/core/v1alpha1" "k8s.io/apimachinery/pkg/runtime" "github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha2" "github.com/oam-dev/kubevela/pkg/appfile/config" "github.com/oam-dev/kubevela/pkg/dsl/process" "github.com/oam-dev/kubevela/pkg/oa...
//go:generate mockgen -destination=./mock/timer_mock.go github.com/nomkhonwaan/myblog/pkg/log Timer package log import "time" // Timer is a compatible interface for retrieving current system date-time type Timer interface { // Return current system date-time Now() time.Time } // DefaultTimer implements Timer inte...
package dushengchen type SliceStack struct { top int raw []int } func NewSliceStack(cap int) *SliceStack { if cap <= 0 { cap = 10 } return &SliceStack{top: -1, raw: make([]int, 0, cap)} } func (s *SliceStack) Push(element int) { s.top++ if s.top < len(s.raw) { s.raw[s.top] = element } else { s.raw = a...
package main import ( "encoding/json" "flag" "fmt" "io/ioutil" "log" "os" "path" "runtime" "testing" "github.com/mrled/caryatid/internal/util" "github.com/mrled/caryatid/pkg/caryatid" ) const integrationTestDirName = "integration_tests" var ( _, thisfile, _, runtimeCallerOk = runtime.Caller(0) thisdir,...
package graph import ( "bufio" "errors" "os" "strconv" "strings" ) func LoadGraphFromFile(graphtype, filename string) interface{} { // ioutil.ReadFile() O_RDONLY path := "G:\\Code\\goAlgorithms\\src\\algorithms\\graph\\" + filename file, err := os.OpenFile(path, os.O_RDWR|os.O_APPEND, 0666) if err != nil { ...
/* You have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height...
// +build appengine package tokbox import ( "golang.org/x/net/context" "google.golang.org/appengine/urlfetch" "net/http" ) func client(ctx context.Context) *http.Client { if ctx == nil { return &http.Client{} } else { return urlfetch.Client(ctx) } }
package requests import ( "bytes" "encoding/json" "fmt" "net/http" "github.com/iamtraining/go-github-issue-tool/editor" "github.com/iamtraining/go-github-issue-tool/entity" ) const ( repoUser = "https://api.github.com/repos/%s/%s/issues" issueNum = repoUser + "/%s" ) func sendRequest(oauth, method, url stri...
package main func isSamePosition(head *Coordinates, tail *Coordinates) bool { return head.X == tail.X && head.Y == tail.Y } func isSameRow(head *Coordinates, tail *Coordinates) bool { return head.Y == tail.Y } func isRightEdge(grid *[][]int, head *Coordinates) bool { return head.X >= len(*grid)-1 } func isLeftEd...
package main import ( "demo/grpc_test/cmd/server/service" "demo/grpc_test/proto/chat" "demo/grpc_test/proto/helloworld" "google.golang.org/grpc" "google.golang.org/grpc/reflection" "log" "net" ) const ( port = ":50051" ) func main() { listen, err := net.Listen("tcp", port) if err != nil { log.Panic(err) ...
package 字符串 func firstUniqChar(s string) byte { charStorage := NewCharStorage() return byte(charStorage.GetFirstUniqueChar(s)) } // --------- CharStorage --------- type CharStorage struct { charAppearingTimes map[rune]int returnCharWhenUniqueCharDoesExist rune sample string } func NewCharStorag...
// Copyright 2021 PingCAP, Inc. Licensed under Apache-2.0. package export import ( "fmt" "testing" "github.com/pingcap/tidb/br/pkg/version" "github.com/stretchr/testify/require" ) func TestRepeatableRead(t *testing.T) { data := [][]interface{}{ {version.ServerTypeUnknown, ConsistencyTypeNone, true}, {versi...
// We often want to execute Go code at some point in the // future, or repeatedly at some interval. Go's built-in // _timer_ and _ticker_ features make both of these tasks // easy. We'll look first at timers and then // at [tickers](tickers). package main import "time" import "fmt" func main() { timerExist := false...
package aggregate import ( "time" "github.com/XiaoMi/pegasus-go-client/idl/admin" "github.com/XiaoMi/pegasus-go-client/idl/base" ) // PartitionStats is a set of metrics retrieved from this partition. type PartitionStats struct { Gpid base.Gpid // Address of the replica node where this partition locates. Addr ...
package conn import ( "errors" "fmt" "github.com/ClarityServices/skynet2" "github.com/ClarityServices/skynet2/log" "github.com/ClarityServices/skynet2/rpc/bsonrpc" "labix.org/v2/mgo/bson" "net" "net/rpc" "time" ) // TODO: Abstract out BSON logic into an interface that can be proviced for Encoding/Decoding da...
package main import ( "fmt" "time" ) func main(){ f := fmt.Println now := time.Now() f(now) then := time.Date( 2009, 11, 17, 20, 34, 58, 651387237, time.UTC) f(then) f(then.Year()) f(then.Month()) f(then.Day()) f(then.Hour()) f(then.Minute()) f(then.Second()) f(then.Nanosecond()) f(then.Unix()) f(...
package main import ( "strconv" "strings" ) // Action is a game action that can be triggered in various ways. type Action interface { Start() } type ChainAction struct { chain []Action } func (act *ChainAction) Start() { for _, action := range act.chain { action.Start() } } type NullAction struct { } func...
package listen type CmdHander interface { CmdParseMsg() string CmdParse(cmd string) bool Start() }
package model type Datum struct { T int `json:"t"` D []interface{} `json:"d"` }
package notification import ( "encoding/json" "net/http" ) type User struct { NetId string Area string } type Response struct { Status string `json:status` Data interface{} `json:data` } func write(code int, res Response, w http.ResponseWriter) { b, err := json.Marshal(res) if err != nil { w.Write...
package main import ( "fmt" "io/ioutil" "log" validator "gopkg.in/go-playground/validator.v9" yaml "gopkg.in/yaml.v2" ) // Use a single instance of Validate, it will cache struct info. var validate *validator.Validate func main() { var pc PublicCode // Read data from file. data, err := ioutil.ReadFile("pub...
package consensus import ( "fmt" "log" "net" "net/http" "net/rpc" "reflect" "sync" "time" ) type Peer struct { ip string port string } func NewPeer(ip string, port string) *Peer { peer := new(Peer) peer.ip = ip peer.port = port return peer } type State int const ( FOLLOWER = iota CANDIDATE = iot...
package utils const AppName = "Gnemes"
package node import ( "github.com/sherifabdlnaby/prism/app/component" "github.com/sherifabdlnaby/prism/pkg/job" "github.com/sherifabdlnaby/prism/pkg/response" ) //output Wraps an output core type output struct { output *component.Output *Node } //process output process will send the process to output plugin and...
package main import "fmt" type myFuncType func(int, int) int //自定义数据类型 type myInt int //自定义数据类型,虽然都是int类型,go实际上认为这不是同一个类型,所以如果有一个类型为int的,一个是myInt的,实际上他们是不能相互赋值的 func main() { var num myInt = 666 fmt.Printf("res=%v\n", num) res := myFun(getSum, 100, 120) fmt.Printf("res=%v\n", res) } func getS...
package bosh import ( "errors" "log" "time" "github.com/skriptble/nine/element" "github.com/skriptble/nine/stream" ) // ErrSessionClosed is the error returned when a session has been closed and a // call to Element is made. var ErrSessionClosed = errors.New("Session is closed") type Session struct { processor...
package 二叉树 func leafSimilar(root1 *TreeNode, root2 *TreeNode) bool { return areArraysSame(getLeafSequence(root1), getLeafSequence(root2)) } func getLeafSequence(root *TreeNode) []int { if root == nil { return []int{} } if root.Left == nil && root.Right == nil { return []int{root.Val} } leafSequence := make...
package models import ( "fmt" "time" "github.com/jinzhu/gorm" ) // ===== BEGIN of all query sets // ===== BEGIN of query set ProjectQuerySet // ProjectQuerySet is an queryset type for Project type ProjectQuerySet struct { db *gorm.DB } // NewProjectQuerySet constructs new ProjectQuerySet func NewProjectQueryS...
/* init 函数可用于执行初始化任务,也可用于在执行开始之前验证程序的正确性。 一个包的初始化顺序如下: 包级别的变量首先被初始化 接着 init 函数被调用。一个包可以有多个 init 函数(在一个或多个文件中),它们的调用顺序为编译器解析它们的顺序。 如果一个包导入了另一个包,被导入的包先初始化。 尽管一个包可能被包含多次,但是它只被初始化一次。 下面让我们对我们的程序做一些修改来理解 init 函数。 首先在 rectprops.go 中添加一个 init 函数: */ // --------------- /* 使用空指示符 在 Go 中只导入包却不在代码中使用它是非法的。如果你这么做了,编译器会报错。 这样做...
package example import ( "context" "fmt" "github.com/opentracing/opentracing-go" "log" "net/http" "net/url" "sourcegraph.com/sourcegraph/appdash" appdashtracer "sourcegraph.com/sourcegraph/appdash/opentracing" "sourcegraph.com/sourcegraph/appdash/traceapp" "testing" "time" ) var tapp *traceapp.App var ctx ...
package x0 import ( "encoding/json" "fmt" "github.com/x0tf/x0go/schema" ) // ElementsClient is used to execute API requests directed to the element-related scopes type ElementsClient struct { http *httpClient } // GetList requests a paginated list of existent elements func (client *ElementsClient) GetList(limit...
package auth import ( "net/http" "github.com/gorilla/mux" "gitlab.com/NagByte/Palette/db/wrapper" "gitlab.com/NagByte/Palette/service/common" "gitlab.com/NagByte/Palette/service/smsVerification" ) type Auth interface { TouchDevice(map[string]interface{}) (string, bool, string, error) Signup(string, string, s...
package main import ( "bufio" "fmt" "strings" ) type space struct { r, c int length int direction int occupied bool } func main() { s := bufio.NewScanner(os.Stdint) board := make([]string, 10) for i := 0; i < 10; i++ { s.Scan() board[i] = s.Text() } s.Scan() words := strings.Split(s.Text(),...
package middleware import ( "fmt" "net/http" "net/http/httptest" "net/url" "testing" "github.com/google/go-cmp/cmp" "github.com/pomerium/pomerium/internal/urlutil" ) func TestSetHeaders(t *testing.T) { tests := []struct { name string securityHeaders map[string]string }{ {"one option", map[...
package extract import ( "code.sajari.com/docconv" "log" ) func ExtractTextFromPdf(path string)string{ res, err := docconv.ConvertPath(path) if err != nil { log.Println(err) return "" } return res.Body }
package mcservice import ( "errors" "bytes" "encoding/json" "log" "net/http" "strconv" "sync" ) // JSONRequest ... type JSONRequest struct { Method string `json:"method"` Params []interface{} `json:"params"` ID interface{} `json:"id"` } // JSONResponse ... type JSONResponse struct { Result in...
package main import ( "bytes" "flag" "fmt" "net" "os" "time" "github.com/nkbai/goice/stun" "github.com/nkbai/goice/turn" "github.com/nkbai/goice/utils" "github.com/nkbai/log" ) var ( server = flag.String("server", fmt.Sprintf("193.112.248.133:3478"), "turn server address", ) peer = flag.String("peer...
/* * @Author: geoferry * @Date: 2016-09-01 14:49:00 * @Last Modified by: geoferry * @Last Modified time: 2016-09-02 09:15:35 */ package main import ( "bufio" "fmt" log "github.com/Sirupsen/logrus" "io" "os" "strconv" "strings" ) func main() { file, err := os.OpenFile("1.txt", os.O_RDONLY, 0666) if err ...
/**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | ...
//+build wireinject package main import ( "go_restful/user" "github.com/google/wire" "github.com/jinzhu/gorm" ) func InitUserApi(db *gorm.DB) user.UserApi { wire.Build(user.ProvideUserRepository, user.ProvideUserService, user.ProvideUserAPI) return user.UserApi{} }