text
stringlengths
11
4.05M
package omokServer import ( "scommon" "smallNet" "time" ) func (svr *Server) Process_goroutine() { scommon.LogInfo("[Process_goroutine] Start") timeTicker := time.NewTicker(time.Millisecond * 100) defer timeTicker.Stop() defer svr._serverNet.Stop() LOOP: for { select { case _ = <-timeTicker.C: svr._...
package home import ( "github.com/gin-gonic/gin" "github.com/spf13/viper" "net/http" ) func Index(c *gin.Context) { data := gin.H{ "title": "首页", "httpUrl": viper.GetString("app.httpUrl"), "webSocketUrl": viper.GetString("app.webSocketUrl"), } c.HTML(http.StatusOK, "index.html", data) }
package main import ( "encoding/json" "fmt" "net/http" "strconv" "time" "github.com/gorilla/mux" "github.com/jinzhu/gorm" ) type Article struct { ID int ArticleWriter string PostedAt time.Time UpdatedAt time.Time ArticleWriterEmail string } const dbPath string = "...
package main import ( "fmt" "log" "net/http" "strings" "time" "github.com/gorilla/websocket" "github.com/westphae/magkal/pkg/kalman" ) type source int // Source is where the measurements come from const ( manual source = iota // User sends measurements through websocket random // Measurements...
// DO NOT EDIT. This file was generated by "github.com/frk/gosql". package testdata import ( "github.com/frk/gosql" ) func (q *InsertDefaultAllSingleQuery) Exec(c gosql.Conn) error { const queryString = `INSERT INTO "test_user_with_defaults" AS u ( "email" , "full_name" , "is_active" , "created_at" , "up...
package cmd import ( "00-newapp-template/internal/app/cmd/client" "00-newapp-template/internal/pkg" "00-newapp-template/internal/pkg/adapter" "00-newapp-template/internal/pkg/ui" "fmt" "github.com/spf13/cobra" ) // Client is the dispactcher from Cobra to Config type Client struct { Config *pkg.Config Adapter...
package machines import ( "testing" "github.com/stretchr/testify/assert" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/utils/pointer" "github.com/openshift/installer/pkg/asset" "github.com/openshift/installer/pkg/asset/ignition/machine" "github.com/openshift/installer/pkg/asset/installconfig" "github...
// Copyright Jetstack Ltd. See LICENSE for details. package cmd import ( "fmt" "os" "path/filepath" "github.com/hashicorp/go-multierror" vault "github.com/hashicorp/vault/api" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/jetstack/vault-helper/pkg/instanceToken" ) // RootCmd represents t...
package mock import chat "github.com/greatchat/gochat/transport" // Client is a mock implementation chat Client type Client struct { ReceiveFunc func(src string) (chat.Message, error) SendFunc func(dest string, msg chat.Message) error ConsumerFunc func(src string) (chan chat.Message, error) ProducerFunc func...
/** * (C) Copyright IBM Corp. 2021. * * 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 nats import ( "context" "fmt" "log" "github.com/batchcorp/plumber-schemas/build/go/protos/encoding" cenats "github.com/cloudevents/sdk-go/protocol/nats/v2" cloudevents "github.com/cloudevents/sdk-go/v2" "github.com/pkg/errors" "github.com/batchcorp/plumber-schemas/build/go/protos/opts" "github.com/...
package models import ( "errors" "go-admin/global" "go-admin/utils" ) type Login struct { Username string `form:"UserName" json:"username" binding:"required"` Password string `form:"Password" json:"password" binding:"required"` } func (l *Login) GetUser() (user SysUser, role SysRole, err error) { err = global....
package main import "fmt" type Vehicle interface { Move() } type Car struct { MovementAction string } func (c Car) Move() { fmt.Println(c.MovementAction) } type Plane struct { MovementAction string } func (p *Plane) Move() { fmt.Println(p.MovementAction) } func main() { var v Vehicle = Car{"Drive"} v.Move...
// Copyright 2022 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 batcher import ( "encoding/json" "github.com/dkrieger/redistream" "github.com/go-redis/redis" "log" "os" "time" ) // SendBatch aggregates up to BatchConfig.MaxSize entries into one entry, // adding to Batcher.batchDest() stream func (b *Batcher) SendBatch(name string) error { batches := b.getBatches() ...
package main import ( "fmt" "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" "time" ) type User struct { Id int `PK` Name string `orm:"size(100)"` Profile *Profile `orm:"rel(one)"` // OneToOne relation Post []*Post `orm:"reverse(many)"` // 设置一对多的反向关系 } type Userinfo struct { Id int `PK`...
package linkedlist import ( "errors" ) // ErrEmptyList is self explanitory var ErrEmptyList = errors.New("Cannot Pop on an empty linked list") // Node is a node element in our doubly linked list type Node struct { prevPtr *Node Val interface{} nextPtr *Node } // List is a doubly linked list type List struct...
package leetcode type WordDictionary struct { t []*WordDictionary e bool p bool } /** Initialize your data structure here. */ func Constructor() WordDictionary { var dic = WordDictionary{t: make([]*WordDictionary, 26), e: false, p: false} return dic } /** Inserts a word into the dict. */ func (this *WordDicti...
// Copyright (c) 2015-2016 The btcsuite developers // // Permission to use, copy, modify, and distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUT...
package transformer import ( "testing" rpb "github.com/ampproject/amppackager/transformer/request" ) func TestValidateRequest(t *testing.T) { tests := []struct { rs []*rpb.VersionRange expectedError bool }{ { rs: nil, expectedError: false, }, { rs: []*rpb.VersionRa...
package composite import ( "github.com/stretchr/testify/assert" "testing" ) func Test(t *testing.T) { directory := directory{path: "directoryPath"} var file1 file = &concreteFile{path: "path1", size: 20.5} var file2 file = &concreteFile{path: "path2", size: 10.425} var file3 file = &concreteFile{path: "path3", ...
package main import ( "encoding/json" "io/ioutil" "log" ) type Perms map[string]bool type user struct { // export your fields to encode them FirstName string `json:"first_name"` Password string `json:"-"` Perms `json:"perms,omitempty"` } func main() { users := []user{ { FirstName: "Diwakar", P...
package remotev import ( "fmt" "golang.org/x/crypto/ssh" "log" "net" // "os" "strings" "time" ) func connect(user, password, host string, port int) (*ssh.Session, error) { var ( auth []ssh.AuthMethod addr string clientConfig *ssh.ClientConfig client *ssh.Client session *ss...
package medasync func (c *Config) CopyFrom(other *Config) { c.SynchronisationChunkSize = other.SynchronisationChunkSize c.Inserter.CopyFrom(&other.Inserter) c.Subpath = other.Subpath c.TemporaryDirectory = other.TemporaryDirectory c.GlobalWorkDirectory = other.GlobalWorkDirectory c.NodeList = other.NodeList c....
package main import ( "encoding/csv" "flag" "fmt" "io" "net/url" "os" "strconv" "strings" "time" "github.com/ChimeraCoder/anaconda" ) var ( consumerKey = flag.String("consumer_key", "", "Issued from Twitter. ") consumerSecret = flag.String("consumer_secret", "", "Issued from Twitter. ") accessT...
package security import ( "encoding/json" "time" ) type KeyValue struct { Key string Value string } type ConnectorFunction func(AccessManager, *ScheduledConnector, Session) error type ConnectorInfo struct { SystemType string // Moodle, GoogleSheets, Formsite SystemIcon string DataType ...
package handler import ( "net/url" "testing" "github.com/stretchr/testify/assert" ) func TestSanitizeQueryParamOf(t *testing.T) { tcs := []struct{ qps url.Values key string defVal string expected string }{ {url.Values{}, "key", "3", "3"}, {url.Values{"key":[]string{}}, "key", "3", "3"}, {url.Value...
/* Copyright 2019 IBM Corporation 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, software dis...
// Copyright 2020 The Reed Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. package discover import ( "net" ) type udpListener struct { conn *net.UDPConn } func NewUDPListener(ip net.IP, port uint16) (*udpListener...
package annotation_test import ( "bytes" "errors" "fmt" "net/http" "net/http/httptest" "reflect" "strings" "testing" "time" "github.com/m-lab/etl/annotation" ) var epoch time.Time = time.Unix(0, 0) func TestFetchGeoAnnotations(t *testing.T) { tests := []struct { ips []string timestamp time.Time...
/* * nighthawk.config.env * */ package config import ( "database/sql" "fmt" "os" "path/filepath" "runtime" ) // Global Environmental Variables // Directory Setup var ( BASEDIR = "/opt/nighthawk" CONFDIR = "" STATEDIR = "" DBDIR = "" MEDIA = "" TMP = "" RUNDIR = "" ...
// ticker project doc.go /* ticker document */ package main
package main import ( "fmt" "os" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" ) var db *gorm.DB func DB_Init() { var err error dbHost := os.Getenv("DB_HOST") dbPort := os.Getenv("DB_PORT") dbName := os.Getenv("DB_NAME") dbUser := os.Getenv("DB_USER") dbPass := os.Getenv("DB_PASS"...
package lintcode /** * @param a: A 32bit integer * @param b: A 32bit integer * @param n: A 32bit integer * @return: An integer */ func fastPower(a int, b int, n int) int { // (a*b)%n=((a%n)*(b%n))%n // a^n=(a^(n/2))*(a^(n/2))=... if n == 0 { return 1 % b } if n == 1 { return a % b } halfPower := fastPo...
package main func foo() { bar() } func bar() { } func main() { foo() }
package binary_search import ( "fmt" "testing" ) var arr = []int{1, 3, 3, 5, 7, 8, 12, 13} var arr2 = []int{1, 2, 2, 2, 3} func TestFindIndex(t *testing.T) { // 返回5 fmt.Println(FindIndex(arr, 8)) // 返回2,实际上返回1、2、3都对应target=2 // 无法处理边界问题 fmt.Println(FindIndex(arr2, 2)) } func TestFindLef...
package controllers import ( "encoding/json" "net/http" "github.com/adjust/rmq/v3" "github.com/jinzhu/gorm" "github.com/kazetora/evermos-assignment/problem_1_ecommerce/helpers" "github.com/kazetora/evermos-assignment/problem_1_ecommerce/models" "github.com/kazetora/evermos-assignment/problem_1_ecommerce/reques...
package main import ( "codewizards/runner" ) func main() { runner.Start(New) }
// // Copyright 2019 Chef Software, Inc. // Author: Salim Afiune <afiune@chef.io> // // 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 // /...
package parsing import ( "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/wish/ctl/pkg/client" "github.com/wish/ctl/pkg/client/filter" v1 "k8s.io/api/core/v1" "regexp" "strings" ) // LabelMatchFromCmd automatically parses the "label" flag from a command // and returns the filtering.LabelMatch spec...
package writer_test import ( "bytes" "github.com/saschagrunert/go-docgen/internal/writer" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/urfave/cli" ) // The actual test suite var _ = t.Describe("Writer", func() { t.Describe("New", func() { It("should succeed", func() { // Given app...
package main import ( "context" "fmt" "github.com/yxxyun/ripple/crypto" "github.com/yxxyun/ripple/data" rpc "github.com/yxxyun/ripple/rpc/v1" "google.golang.org/grpc" ) func main() { seed, _ := crypto.NewRippleHashCheck("sapqGRrejEA8Z3mbAGqiuBNak4HHs", crypto.RIPPLE_FAMILY_SEED) key, _ := crypto.NewECDSAKey...
package nimbus import ( "sort" "strings" ) // a singular portion of the entire word cloud type nimbus struct { Word string Count int } type ByCount []nimbus // sorting functions func (a ByCount) Len() int { return len(a) } func (a ByCount) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByCou...
package el // Handle ElPacket's fragmentation import ( "sync" "time" ) const ( // Fragment Threshold FRG_THRES = 32 // Max Fragments MAX_FRAGS = 8 ) // var elFrager *ElFragmenter type elSequencer interface { Seq() uint32 } type elFragCacheRecord struct { ts int64 p *ElPacket } type elFragCache struct {...
/* 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, softw...
package nats_streaming import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/batchcorp/plumber-schemas/build/go/protos/args" "github.com/batchcorp/plumber-schemas/build/go/protos/opts" "github.com/batchcorp/plumber/backends/nats-streaming/stanfakes" "github.com/batchcorp/plumber/types" "g...
package main const ( qPrefix = ` select history_items.id, title, url from history_items inner join history_visits on history_visits.history_item = history_items.id where ` qPostfix = ` group by url order by visit_time desc limit 40 ` dbFilePath = "./History.db" )
package iirepo_contents_test import ( "github.com/reiver/go-iirepo/contents" "fmt" ) func ExamplePath() { var parent string = "/home/joeblow/workspaces/myproject" repoContentsPath := iirepo_contents.Path(parent) fmt.Printf("The repo's contents directory's path is: %s\n", repoContentsPath) // Output: // Th...
package main import ( "fmt" ) const ( a = iota b = iota c = iota d = iota e = iota f = iota ) // Reset and start new //const ( // d = iota // e = iota // f = iota //) func main() { fmt.Println(a) fmt.Println(b) fmt.Println(c) fmt.Println(d) fmt.Println(e) fmt.Println(f) fmt.Printf("%T %T %T %T %T %T",...
// // Copyright 2020 The AVFS 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 ag...
package main import ( "context" "fmt" "log" "os" "strconv" "strings" "time" "gopkg.in/olivere/elastic.v5" ) type arr [][]int64 var umap = make(map[string]arr) func getID(l string) string { i := strings.Index(l, ":") id := l[i+1:] return id } func getSeq(l string) int64 { i := strings.Index(l, ":") s ...
package main import ( "fmt" "strconv" "math/rand" "time" ) type card struct { mark string num int } func NumToCard(num int) string { switch num { case 1: return "A" case 11: return "J" case 12: return "Q" case 13: return "K" default: return strconv.Itoa(num) } } func NumToPoint(num int) int ...
/* * OpenAPI Petstore * * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * API version: 1.0.0 * Generated by: OpenAPI Generator (https://openapi-generator.tech) */ package petstoreserver import ( "os" ) type InlineObject1 s...
package goexpr import ( "bytes" "fmt" lls "github.com/emirpasic/gods/stacks/linkedliststack" "regexp" "sort" "strconv" "strings" "unicode" ) type Token struct { Value string Type string } type Engine struct { priority map[string]int32 prefixSet map[string]PrefixOp infixSet map[string]InfixOp f...
package session import ( "crypto/sha256" "fmt" "github.com/fasthttp/session/v2" "github.com/authelia/authelia/v4/internal/utils" ) // Serializer is a function that can serialize session information. type Serializer interface { Encode(src session.Dict) (data []byte, err error) Decode(dst *session.Dict, src []b...
package verifier import ( "github.com/lf-edge/eve/pkg/pillar/types" ) // wrappers to add objType for create. The Delete wrappers are merely // for function name consistency func handleAppImgModify(ctxArg interface{}, key string, configArg interface{}) { vHandler.modify(ctxArg, types.AppImgObj, key, configArg) } fu...
/* * @lc app=leetcode.cn id=121 lang=golang * * [121] 买卖股票的最佳时机 */ // @lc code=start package main import "math" import "fmt" func maxProfit(prices []int) int { minPrice := math.MaxInt64 maxProfit := 0 for i := 0 ; i < len(prices) ; i++ { if prices[i] < minPrice { minPrice = prices[i] } if prices[i]...
package main import "fmt" func main() { //缓冲信道的长度是指信道中当前排队的元素个数。 //ch := make(chan string, 2) // 2 是指通道中元素的个数 //ch <- "naveen" //ch <- "paul" //ch <- "steve" //fatal error: all goroutines are asleep - deadlock! //fmt.Println(<-ch) //fmt.Println(<-ch) //fmt.Println(<-ch) //close(ch) ch := make(chan string, ...
package main import ( "fmt" "log" "flag" "os" "github.com/kylelemons/go-gypsy/yaml" "io/ioutil" "github.com/ziutek/mymysql/mysql" //_ "github.com/ziutek/mymysql/native" _ "github.com/ziutek/mymysql/godrv" "playGo/funDb" ) var ( config *yaml.File config_file = flag.String("conf", "./conf/data...
package session import ( "fmt" "time" "strconv" "strings" "regexp" "github.com/deepdeeppink/tgbot/state" "github.com/deepdeeppink/tgbot/spells" "github.com/deepdeeppink/tgbot/words" "github.com/deepdeeppink/tgbot/bot" "github.com/deepdeeppink/tgbot/cfg" "github.com/deepdeeppink/tgbot/errs" "github.com/deep...
package main import ( "github.com/blablacar/attributes-merger/attributes" "io/ioutil" ) // TODO - lire fichier de conf // trapper la variable d'environnement func main() { // Get Option Flags fgs := newFlags() in := attributes.NewInputs(fgs.input_dir) // initialize input files list err...
/* You are given a list of 999,998 integers, which include all the integers between 1 and 1,000,000 (inclusive on both ends) in some unknown order, with the exception of two numbers which have been removed. By making only one pass through the data and using only a constant amount of memory (i.e. O(1) memory usage), ca...
package main import ( _ "encoding/json" "fmt" "strings" "time" "github.com/pquerna/ffjson/ffjson" ) type Report struct { ProjectName string `json: "ProjectName"` ProjectNo string `json: "ProjectNo"` Name string `json: "Name"` Description string `json: "Description"` Issue string `json: "Issu...
// Copyright 2016 CoreOS, 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 in...
package response import( "github.com/shrikar007/customer-rest-api/structs" "net/http" ) type Getallstruct struct { *structs.Customers } func (Getallstruct) Render(w http.ResponseWriter, r *http.Request) error { return nil } func Getallresponse(customers *structs.Customers) *Getallstruct{ return &Getallstruct{...
package pov import ( "time" "github.com/qlcchain/go-qlc/common" "github.com/qlcchain/go-qlc/common/types" "github.com/qlcchain/go-qlc/p2p" "github.com/qlcchain/go-qlc/p2p/protos" ) const ( maxSyncBlockInQue = 500 ) type PovSyncBlock struct { PeerID string Height uint64 Block *types.PovBlock TxExist...
package main import ( "fmt" "github.com/gtfierro/xboswave/ingester/types" xbospb "github.com/gtfierro/xboswave/proto" ) func has_device(msg xbospb.XBOS) bool { return msg.XBOSIoTDeviceState.WeatherStation != nil } var device_units = map[string]string{ "time": "seconds", "icon": ...
package solve import lane "gopkg.in/oleiade/lane.v1" func findShortestPath(start string, end string, graph map[string][]string) []string { dq := lane.NewDeque() visited := make(map[string]bool) dq.Append([]string{start}) for { if dq.Empty() { break } else { path := dq.Shift() if p, ok := path.([]s...
package shared import ( "testing" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/prompt" "github.com/stretchr/testify/assert" ) type metadataFetcher struct { metadataResult *api.RepoMetadataResult } func (mf *metadataFetche...
package controller import ( "encoding/json" "log" "net/http" "strings" "github.com/galenguyer/retina/storage" ) func StartServer() { fileServer := http.FileServer(http.Dir("./web/app/build/")) http.HandleFunc("/api/v1/hour", GetLastHour) http.Handle("/", http.StripPrefix(strings.TrimRight("/", "/"), fileServ...
package openstack import ( "errors" "fmt" "regexp" "strings" "time" "github.com/gophercloud/gophercloud" "github.com/gophercloud/gophercloud/openstack/blockstorage/v3/snapshots" "github.com/gophercloud/gophercloud/openstack/blockstorage/v3/volumes" "github.com/gophercloud/gophercloud/openstack/compute/v2/ext...
package controllers import ( "log" "github.com/messagedb/messagedb/meta" "github.com/messagedb/messagedb/services/httpd/helpers" "github.com/gin-gonic/gin" ) // DeviceController handles RESTful API requests for an Device resources type DevicesController struct { Engine *gin.Engine MetaStore interface { Dat...
package quic import ( "gx/ipfs/QmU44KWVkSHno7sNDTeUcL4FBgxgoidkFuTUyTXWJPXXFJ/quic-go/internal/protocol" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Crypto Stream", func() { var ( str *cryptoStreamImpl mockSender *MockStreamSender ) BeforeEach(func() { mockSender = N...
/** * Copyright (c) 2018 ZTE Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and the Apache License 2.0 which both accompany this distribution, * and are available at http://www.eclipse.org/legal/epl-v10.html ...
package admin import ( "context" "tpay_backend/adminapi/internal/common" "tpay_backend/model" "tpay_backend/adminapi/internal/svc" "tpay_backend/adminapi/internal/types" "github.com/tal-tech/go-zero/core/logx" ) type EnableAdminLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } ...
// +build linux package nio import ( "fmt" "syscall" ) func newPoller() poller { return &epoll{} } // https://medium.com/@copyconstruct/the-method-to-epolls-madness-d9d2d6378642 type epoll struct { efd int // epoll fd wfd int // wakeup fd events []syscall.EpollEvent } func epoll_create() (int, error) {...
package main import ( "flag" "fmt" "os" "mys3/src" ) func usage() { fmt.Fprintf(os.Stderr, "usage: mys3 (ls|...) [bucketname] [path]\n") flag.PrintDefaults() os.Exit(2) } func main() { a := &mys3.S3Account{} a.Load(os.Getenv("HOME") + "/.s3cfg") flag.Usage = usage flag.Parse() subcmd := flag.Arg(...
package utils import ( "bufio" "os" "regexp" "strconv" "strings" ) func ParseGoSolution() []Result { // List all java source code file filesPath := make([]string, 0) entries, err := os.ReadDir("golang/solutions") if err != nil { panic(err) } for _, entry := range entries { if entry.IsDir() { files, ...
package database import ( "context" "github.com/anshap1719/authentication/models" "github.com/gofrs/uuid" "github.com/pkg/errors" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "time" ) var ErrMergeTokenNotFound = errors.New("No MergeToken f...
package main import ( "fmt" ) func main() { a := 10 fmt.Println("Value of 'a' \t ::", a) fmt.Printf("Type of 'a' \t :: %T\n", a) fmt.Println("Address of 'a' \t ::", &a) // '&' gives the address fmt.Printf("Type of Address of 'a' :: %T\n", &a) b := &a fmt.Println("Value of 'b' \t ::", ...
package util // link variable var ( Version string DateTime string )
package main import ( tl "github.com/JoelOtter/termloop" ) // hudOffset is the number of units that the HUD takes up at the top of the screen const hudOffset = 2 // BaseLevel is the canvas that all level objects are written to type BaseLevel struct { *tl.BaseLevel Ship *Ship stageNum int stage *Stage } ...
package main import ( "log" "net/http" ) func logout(res http.ResponseWriter, req *http.Request) { session, err := SessionStore.Get(req, "first_app-session") if err != nil { log.Println("error while getting session: ", err.Error()) return } session.Values["user_id"] = "" if err := session.Save(req, res);...
package main import ( "encoding/csv" "io" "log" "strconv" ) func scanFile(updfile io.Reader) (map[string][]map[int][]string, int, error) { data := make(map[string][]map[int][]string) var code int csvr := csv.NewReader(updfile) // skip header: first file line _, err := csvr.Read() if err != nil { log.Pr...
package fullrt import ( "strconv" "testing" "github.com/libp2p/go-libp2p/core/peer" ) func TestDivideByChunkSize(t *testing.T) { var keys []peer.ID for i := 0; i < 10; i++ { keys = append(keys, peer.ID(strconv.Itoa(i))) } convertToStrings := func(peers []peer.ID) []string { var out []string for _, p :=...
package importer import ( "fmt" "strconv" "sync" "github.com/DexterLB/mvm/library" "github.com/DexterLB/mvm/types" "github.com/DexterLB/osdb" ) // OsdbClient returns a logged in Osdb client func (c *Context) OsdbClient() (*osdb.Client, error) { c.osdbLock.Lock() defer c.osdbLock.Unlock() if c.osdbClient !=...
package msgQ import ( "fmt" "github.com/garyburd/redigo/redis" "runtime/debug" "TskSch/mailer" ) //INITIALIZER FOR MSG QUEUE func RedisInit(host string ,port string) redis.Conn { network := "tcp" address := host + ":" + port Conn, err := redis.Dial(network, address) if err !=...
package main import ( "errors" "fmt" "net" "golangPractice/chat_room/protocol" "encoding/json" "encoding/binary" ) //注册功能 func register(conn net.Conn, userId int, password string) (err error) { var msg protocol.Message msg.Cmd = protocol.UserRegister var registerCmd protocol.RegisterCmd registerCmd.User.Us...
package model import "github.com/jinzhu/gorm" type Book struct { gorm.Model Name string Cover string History []*History `gorm:"foreignkey:BookId"` Page []Page `gorm:"foreignkey:BookId"` Tags []*Tag `gorm:"many2many:book_tags;"` Path string LibraryId uint }
package validation import ( "testing" "github.com/stretchr/testify/assert" "k8s.io/apimachinery/pkg/util/validation/field" "github.com/openshift/installer/pkg/types/ibmcloud" ) var ( validRegion = "us-south" ) func validMinimalPlatform() *ibmcloud.Platform { return &ibmcloud.Platform{ Region: validRegion, ...
package rigis import ( "net/http" "github.com/rocinax/rigis/pkg/rule" ) type node struct { rule rule.Rule filter filter balanceType string backendHosts []backendHost backendHostWeightIndex int backendHostIndex int } func newNode( nrule rule.Rule,...
package cmd type devTestCase struct{} /*func TestDev(t *testing.T) { dir, err := ioutil.TempDir("", "test") if err != nil { t.Fatalf("Error creating temporary directory: %v", err) } dir, err = filepath.EvalSymlinks(dir) if err != nil { t.Fatal(err) } wdBackup, err := os.Getwd() if err != nil { t.Fatalf("Error get...
/* Copyright 2021 CodeNotary, Inc. 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 i...
package endpoint import ( "context" "github.com/go-kit/kit/endpoint" "github.com/l-vitaly/golang-test-task/pkg/crawl" "github.com/l-vitaly/golang-test-task/pkg/service" ) // Set collects all of the endpoints that compose an crawl service. type Set struct { PostURLsEndpoint endpoint.Endpoint } // New returns a ...
package main import ( "bot" "log" ) func main() { log.Println("Start bot") config, err := bot.ReadConfigFromEnv() if err != nil { log.Fatal(err) } err = bot.RunBot(config) if err != nil { log.Fatal(err) } log.Println("Stop bot") }
package util import "math" type Vec2 struct { X float64 Y float64 } func (v1 *Vec2) ToInts() (X, Y int) { return int(v1.X), int(v1.Y) } func (v1 *Vec2) ToVals() (X, Y float64) { return v1.X, v1.Y } func (v1 *Vec2) Add(v2 *Vec2) *Vec2 { return &Vec2{v1.X + v2.X, v1.Y + v2.Y} } func (v1 *Vec2) Sub(v2 *Vec2) *V...
package pgsql import ( "testing" ) func TestInt4Range(t *testing.T) { testlist2{{ valuer: Int4RangeFromIntArray2, scanner: Int4RangeToIntArray2, data: []testdata{ { input: [2]int{-2147483648, 2147483647}, output: [2]int{-2147483648, 2147483647}}, }, }, { valuer: Int4RangeFromInt8Array2, s...
package models import ( "database/sql/driver" "encoding/json" "errors" ) type StringMap map[string]string func (s StringMap) Value() (driver.Value, error) { j, err := json.Marshal(s) return j, err } func (s *StringMap) Scan(src interface{}) error { source, ok := src.([]byte) if !ok { return errors.New("typ...
package httpclient import ( "fmt" "io/ioutil" "net/http" "github.com/go-chi/render" ) func DoRequest(httpClient *http.Client, req *http.Request, resultTemplate interface{}) error { res, err := httpClient.Do(req) if err != nil { return err } defer res.Body.Close() if res.StatusCode < 200 || res.StatusCode...
package controller import ( "encoding/json" "fmt" "io/ioutil" "net/http" "strconv" "github.com/GoGroup/Movie-and-events/model" ) const base = "https://api.themoviedb.org/3/movie/" const upcomingQuery = "upcoming?" const apiKey = "f4b8e415cb9ab402e5c1d72176cab35b" //const videoBase = "http://api.themoviedb.org...