text
stringlengths
11
4.05M
package adding // Post defines the storage form of a post type Post struct { ID string `json:"id"` Body string `json:"body"` }
package car import ( "errors" "fmt" "io/ioutil" "log" "strings" "sync" "time" "github.com/shanghuiyang/go-speech/oauth" "github.com/shanghuiyang/go-speech/speech" "github.com/shanghuiyang/image-recognizer/recognizer" "github.com/shanghuiyang/rpi-devices/dev" "github.com/shanghuiyang/rpi-devices/util" cv ...
package element type Message struct { ID int64 `json:"-" db:"id"` User string `json:"user" db:"user"` Body string `json:"body" db:"body"` }
package main import ( "fmt" "log" "net/http" "strconv" ) func bankInitial() int { errors := 0 for i := 1; i <= 100; i++ { _, err := master.Insert("accounts", []interface{}{i, 100000}) if err != nil { log.Println(err) errors++ } } return errors } func problemHandler(w http.ResponseWriter, r *http....
package main const esbuildVersion = "0.8.21"
// Copyright 2014 Marc-Antoine Ruel. All rights reserved. // Use of this source code is governed under the Apache License, Version 2.0 // that can be found in the LICENSE file. package main import ( "fmt" "github.com/maruel/subcommands" ) var cmdAsk = &subcommands.Command{ UsageLine: "ask <subcommand>", ShortDe...
package main /* @Time : 2020-04-04 16:50 @Author : audiRStony @File : 04_reflectElem.go @Software: GoLand */ import ( "fmt" "reflect" ) func modifyValue(x interface{}) { /*反射接收的是动态的类型以及类型的值 原始类型为int64,所以修改时,只能修改为同类型不同值,不可跨类型 */ v := reflect.ValueOf(x) fmt.Println(v.Kind()) if v.Kin...
package webapp import ( "gosearch/pkg/crawler" "gosearch/pkg/engine" "gosearch/pkg/index/fakeindex" "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" "time" ) var ( client = &http.Client{Timeout: time.Second} indx = fakeindex.New() data = []crawler.Document{ crawler.Document{ ID: ...
package commands import ( "os" "path/filepath" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/azure/auth" "github.com/pkg/errors" ini "gopkg.in/ini.v1" ) func getSubFromAzDir(root string) (string, error) { subConfig, err := ini.Loa...
/***************************************************************** * Copyright©,2020-2022, email: 279197148@qq.com * Version: 1.0.0 * @Author: yangtxiang * @Date: 2020-08-25 09:49 * Description: *****************************************************************/ package rpcPoint import ( "errors" "github.com/go-xe2/...
package db_query_loan import ( "bankBigData/BankServerJournal/entity" "bankBigData/BankServerJournal/table" "gitee.com/johng/gf/g" ) // 系统里的所有用户 func QueryPageUserInfo_Pt(start, limit int) (g.List, error) { db := g.DB(table.PSDBName) sql := db.Table(table.PtCustomerInfo).Limit(start, limit) sql.OrderBy("id asc"...
package testdata import ( "github.com/frk/gosql" ) type SelectCountWithFilterQuery struct { Count int `rel:"test_user:u"` gosql.Filter }
package rhythm import ( "github.com/almerlucke/kallos" "github.com/almerlucke/kallos/generators/tools" ) // Bouncer represents a bouncing ball like rhythm // duration ramp represents the hit the ground duration, // pause ramp is the mid air duration // wait ramp is the time between a new throw type Bouncer struct ...
package repository import "github.com/costap/healthcheckapp/model" type ServiceInfoRepository struct { services map[string]model.ServiceInfo } func NewServiceInfoRepository() *ServiceInfoRepository { return &ServiceInfoRepository{services: make(map[string]model.ServiceInfo)} } func (r *ServiceInfoRepository) Save...
// Package cmn provides common constants, types, and utilities for AIS clients // and AIStore. /* * Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. */ package cmn // used in multi-object (list|range) operations type ( // List of object names, or // Prefix, Regex, and Range for a Range Operation ...
package balaur import ( "fmt" "github.com/fatih/color" "github.com/golang/glog" "github.com/zenazn/goji/web" ) var neededConfigs = []string{"app", "route", "middleware"} func NewApp(dir string, configs map[string]string, rr RouteRegistrar, mr MiddlewareRegistrar) *App { app := &App{ appConfig: m...
package pie import ( "fmt" "time" ) type Tag struct { Name string `json:"name"` NumPosts int `json:"num_posts"` LastActivity time.Time `json:"last_activity"` } func buildAllTagsRequest(token string) *request{ return &request{ Url: "/tags", Token: token, } } func buildOwnTagsRequest(user_id int,...
package main import ( "context" "log" "time" pb "github.com/thanhftu/go-client/ecommerce" "google.golang.org/grpc" ) const ( address = "localhost:50051" ) func main() { conn, err := grpc.Dial(address, grpc.WithInsecure()) if err != nil { log.Fatalf("did not connected %v", err) } defer conn.Close() c :=...
package middleware import ( "fmt" "github.com/gin-gonic/gin" "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/ext" "github.com/uber/jaeger-client-go" "github.com/uber/jaeger-client-go/config" "io" ) func initTraceConfig() (opentracing.Tracer, io.Closer) { cfg:= &config.Configurat...
package tax import ( "fmt" "strings" "github.com/Knetic/govaluate" taxmodel "github.com/syariatifaris/shopeetax/app/model/tax" ) //CalculateTax calculates tax based on product input and its rule func CalculateTax(input *TaxableProductInput, taxes map[int64]*taxmodel.Tax) (*taxmodel.TaxableProduct, error) { rule...
package main import ( "flag" "github.com/BurntSushi/toml" "log" "simple_websocket/internal/chat" ) var configPath string func init() { flag.StringVar(&configPath, "path", "configs/conf.toml", "provide path to config file") } func main() { flag.Parse() config := chat.NewConfig() _, err := toml.DecodeFile...
package main import ( "testing" ) func TestOpenAndCloseQueue(t *testing.T) { q := OpenQueue() q.Close() } func TestCreateTask(t *testing.T) { q := OpenQueue() q.NewTask(0, "") q.Close() } func ReadTask(t *testing.T) { q := OpenQueue() task := q.NewTask(0, "") q.readTask(task.ID) q.Close() }
package configuration import ( "encoding/json" "flag" "fmt" "os" ) type Config struct { Host string `json:"Host,required"` Port uint `json:"Port,required"` Database string `json:"Database,required"` DBHost string `json:"DBHost,required"` DBPort uint `json:"DBPort,required"` User string `...
package game import ( "math" "math/rand" "github.com/grahamjenson/asteroids/vector2d" ) /// // Asteroid /// type Asteroid struct { template *vector2d.Polygon Projection *vector2d.Polygon x, y float64 velocityX, velocityY, rotationD, rotation float64 width, height int...
package client import ( "crypto/rand" "encoding/base64" "fmt" "log" "net/http" "os" "strings" "golang.org/x/oauth2" ) const ( cKeyState = "staffio_state" cKeyToken = "staffio_token" cKeyUser = "staffio_user" ) var ( conf *oauth2.Config oAuth2Endpoint oauth2.Endpoint infoUrl string ) ...
// // 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 ( "encoding/json" "flag" "fmt" "io" "log" "os" "path/filepath" "github.com/mcandre/stank" ) var flagPrettyPrint = flag.Bool("pp", false, "Prettyprint smell records") var flagEOL = flag.Bool("eol", false, "Report presence/absence of final end of line sequence") var flagCR = flag.Bool("cr",...
type LRUCache struct { Capacity int Size int Pairs map[int]*Node Head *Node Tail *Node } type Node struct{ Val int Key int Pre *Node Next *Node } func Constructor(capacity int) LRUCache { head:= &Node{} tail:=&Node{Pre:head} head.Next = tail return LRUCache{ ...
package main import ( "bufio" "fmt" "encoding/hex" "github.com/lt/go-cryptopals/cryptopals" "os" ) func main() { if len(os.Args) < 2 { fmt.Println("Usage: go run challenge4.go <path to 4.txt>") os.Exit(1) } file, err := os.Open(os.Args[1]) if err != nil { fmt.Println(err) os.Exit(1) } defer file.C...
package waktu // fmtInt formats v into the tail of buf. // It returns the index where the output begins. func fmtInt(buf []byte, v uint64) int { w := len(buf) if v == 0 { w-- buf[w] = '0' } else { for v > 0 { w-- const ten = 10 buf[w] = byte(v%ten) + '0' v /= 10 } } return w }
package config import ( "os" "time" "github.com/garyburd/redigo/redis" "github.com/iris-contrib/logger" "github.com/iris-contrib/middleware/cors" "github.com/iris-contrib/middleware/i18n" "github.com/iris-contrib/middleware/recovery" "github.com/kataras/iris" "gopkg.in/pg.v4" mLogger "github.com/iris-contr...
// Copyright 2021 Google LLC // // 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 main import "testing" /** * author: will fan * created: 2020/1/13 21:04 * description: */ func TestNames(t *testing.T) { name := getName() if name != "Hello" { t.Error("Response from getName is unexpected value") } }
package shuffle import ( "crypto/rand" "crypto/sha256" "fmt" "math/big" ) type KCO struct { C_array []ECPoint c0 ECPoint e *big.Int z_array []*big.Int s *big.Int } func ComMul(com Common, x_array []*big.Int, r0 *big.Int) ECPoint { res := com.g2.Mult(r...
package replaytutorial import ( "context" "database/sql" "flag" "io" "math/rand" "os" "os/signal" "syscall" "time" "github.com/corverroos/replay" replay_server "github.com/corverroos/replay/server" "github.com/corverroos/truss" "github.com/luno/jettison/errors" "github.com/luno/jettison/log" "github.co...
package dcode type JSONValue struct { data []byte } func NewJSONValue(b []byte) JSONValue { return JSONValue{data: b} } type Decoder func(JSONValue) (interface{}, error) // func Field(name string, decoder Decoder) Decoder { // } func DecodeString(d Decoder, s string) (interface{}, error) { return DecodeBytes(d...
package basicauth import ( "encoding/base64" "net/http" "strings" ) type Config struct { UserName string Password string } type AuthFunc func(r *http.Request) bool func New(cfg Config) AuthFunc { return cfg.Auth } func (d *Config) Auth(r *http.Request) bool { aHeader := r.Header.Get("Authorization") if aH...
package main import ( "time" "fmt" ) func main() { t := time.Now() fmt.Println(t.Format("2006-01-02 15:04:05")) //OUTPUT: //2018-09-05 11:37:53 }
package lease import ( "context" "github.com/gookit/gcli/v3" "github.com/ovrclk/akash/x/market/types" "github.com/ovrclk/akcmd/client" "github.com/ovrclk/akcmd/flags" ) func QueryCmd() *gcli.Command { cmd := &gcli.Command{ Name: "lease", Desc: "Market lease query commands", Func: func(cmd *gcli.Command, ...
package test import ( "errors" "github.com/agiledragon/trans-dsl" "github.com/agiledragon/trans-dsl/test/context" "github.com/agiledragon/trans-dsl/test/context/action" . "github.com/smartystreets/goconvey/convey" "testing" ) func newRetryTrans() *transdsl.Transaction { trans := &transdsl.Transaction{ Fragme...
//Package reader provides reading and parsing of the .csv files for database fields package reader import ( "bufio" "encoding/csv" "io" "os" "github.com/paulidealiste/ErroneusDilletante/models" ) //Reader implements .csv reading methods and data aggregation type Reader struct { Primbuck models.PrimaryBucket } ...
package types import "encoding/json" type BaseResponse struct { Status string `json:"status"` ResponseData json.RawMessage `json:"responseData"` Exception *Exception `json:"exception"` } type Exception struct { Text string `json:"text"` SQLCode string `json:"sqlCode"` } type AuthRespo...
package sudokuhistory import ( "github.com/jkomoros/sudoku" "github.com/jkomoros/sudoku/sdkconverter" "reflect" "testing" ) func TestReset(t *testing.T) { model := &Model{} grid := sudoku.NewGrid() grid.MutableCell(3, 3).SetNumber(5) grid.LockFilledCells() converter := sdkconverter.Converters["doku"] if...
package main import ( "log" brokerImpl "test/broker-impl" "test/cli" "test/geo" "time" ) func main() { broker := brokerImpl.NewBrokerImpl() broker.Start() geos := make([]*geo.GeoService, 5) for i := 0; i < 5; i++ { geos[i] = geo.NewGeoService() ch, err := broker.Register(geos[i].GetName()) if err != n...
package fuzz import ( "bytes" "errors" "fmt" "io/ioutil" "os" "path/filepath" "regexp" "strings" "text/template" ) // ErrGoTestFailed indicates that a 'go test' invocation failed, // most likely because the test had a legitimate failure. var ErrGoTestFailed = errors.New("go test failed") // VerifyCorpus run...
package auto import ( "../api/models" ) var users = []models.User{ { Nickname: "Jhon Doe", Email: "jhondoe@email.com", Password: "123456", }, { Nickname: "Chi Thien", Email: "chithien@gmail.com", Password: "123456", }, } var posts = []models.Post{ { Title: "Title post 01", Content: "Post ...
package cdn import ( "fmt" "time" "github.com/empirefox/esecend/config" "qiniupkg.com/api.v7/kodo" ) type Qiniu struct { conf *config.Qiniu Client *kodo.Client } func NewQiniu(c *config.Config) *Qiniu { conf := &c.Qiniu kodoConfig := &kodo.Config{ AccessKey: conf.Ak, SecretKey: conf.Sk, } return &Qi...
package introspection import ( "encoding/json" "errors" "fmt" "github.com/jclem/graphsh/graphql" "github.com/jclem/graphsh/querybuilder" ) var schema *Schema // GetFields gets the fields for a given query func GetFields(q graphql.Querier, query *querybuilder.Query) ([]Field, error) { typ, ok := schema.GetQuer...
package models import ( "encoding/json" "io" "time" //_ "url_shortener/controllers" ) // Direction es la entidad de una direccion a redirigir type Direction struct { ID uint64 `json:"id"` URL string `json:"url"` ShortURL string `json:"short_url"` CreateAt time.Time `-` UpdateAt time.Time ...
package main import ( "bytes" "fmt" "github.com/vidmed/request" "time" "github.com/BurntSushi/toml" ) var configInstance *TomlConfig // TomlConfig represents a config type TomlConfig struct { Main Main } // Main represent a main section of the TomlConfig type Main struct { LogLevel uint8 ListenAddr strin...
package builder import ( "bufio" "encoding/json" "fmt" "io" "os" "path/filepath" "sort" "strings" "syscall" "time" "github.com/Cloud-Foundations/Dominator/imageserver/client" "github.com/Cloud-Foundations/Dominator/lib/configwatch" "github.com/Cloud-Foundations/Dominator/lib/filter" "github.com/Cloud-Fo...
package response type RestartPodResponse struct { Success bool `json:"success"` }
package main import ( "crypto/subtle" "encoding/base64" "encoding/json" "errors" "fmt" "hipeople.api/internal" "io/ioutil" "log" "net/http" "strconv" "strings" ) type Api struct { config *internal.Config imageService *internal.ImageService user string } func NewApi(config *internal.Config...
package main import ( "fmt" "github.com/fogleman/gg" "image/color" "math" ) type canvas struct { *gg.Context radiusX float64 radiusY float64 top float64 left float64 } func New(width, height int) *canvas { c := &canvas{ Context: gg.NewContext(width, height), radiusX: 100.0, radiusY: 20.0, to...
package main import "fmt" func main() { //var a int =0 //fmt.Scanf("%d",&a) for i:=0 ; i<11;i++{ fmt.Println(fib(i)) } //fib(13) } func fib(a int) int{ //var t int if a==0{ //fmt.Println(a) return 0 } else if a==1{ //fmt.Println(a) return 1 } else{ return fib(a-1)+fib(a-2) } }
/* RZFeeser | Alta3 Research Writing out to a YAML file */ package main import ( "fmt" "io/ioutil" "log" "gopkg.in/yaml.v3" ) type Record struct { Item string `yaml:"item"` Col string `yaml:"color"` Size string `yaml:"postage"` } type Config struct { Record Record `yaml:...
// Copyright 2020, Jeff Alder // // 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 openinstrument import ( "code.google.com/p/goprotobuf/proto" openinstrument_proto "code.google.com/p/open-instrument/proto" "encoding/binary" "errors" "fmt" "github.com/joaojeronimo/go-crc16" "io" "log" "os" ) var PROTO_MAGIC uint16 = 0xDEAD type ProtoFileReader struct { filename string ...
package test import ( "database/sql" "encoding/json" "io/ioutil" "log" "net/http" "net/url" "os" "sort" "strings" "testing" _ "github.com/lib/pq" ) var ( baseAPI = "http://localhost:3000/api" ) type testStruct struct { arrayRequestBody url.Values stringRequestBody string expectedResult } type expec...
package filters import ( "net" ) type CidrFilter struct { cidrFilters []*net.IPNet } func NewCidrFilter(filters []string) (*CidrFilter, error) { cidrFilters := []*net.IPNet{} for _, filter := range filters { _, net, err := net.ParseCIDR(filter) if err != nil { return nil, err } cidrFilters = append(c...
package logfmt import ( "io" "io/ioutil" "os" "runtime" "time" "github.com/bingoohuang/golog/pkg/rotate" "github.com/sirupsen/logrus" ) type LogrusEntry struct { *logrus.Entry EntryTraceID string } func (e LogrusEntry) Time() time.Time { return e.Entry.Time } func (e LogrusEntry) Level() string ...
package lib import ( util "github.com/eagle7410/go_util/libs" "github.com/gorilla/mux" "net/http" ) func GetRouter() *mux.Router { r := mux.NewRouter() //TODO: clear Do somethining ... //r.PathPrefix("/static/").Handler( // staticAccess( // http.StripPrefix( // "/static/", // http.FileServer(http.Dir(...
package multiLanguageString type MultiLanguageString struct { Ja string `json:"ja"` En string `json:"en"` Fr string `json:"fr"` Ru string `json:"ru"` Zh string `json:"zh"` Ko string `json:"ko"` } func NewMultiLanguageString(japanese string) *MultiLanguageString { return &MultiLanguageString{Ja: japanese} }
/* Package create2 is a Golang library implementing serial commands for the iRobot Create2 robot. Basics The iRobot Create2 is a low cost mobile robot based on the Roomba 600 series robot repurposed for education and hacking. iRobot provides a well documented serial interface for controlling the Create2. */ package ...
package factory import ( "database/sql" "fmt" "log" "otoboni.com.br/customer-webservice/model" ) func GetCustomerById(id string) (model.Customer, error) { db := ConnectToDb() var cust model.Customer row := db.QueryRow("SELECT customerid, code, customername, email, address, phone, city, country FROM custome...
package tests import ( "github.com/unio-framework/go" "testing" ) func TestJsonSearchQuery(t *testing.T) { stringQuery := "{\"filter\":{\"packageName\":{\"in\":[\"com.unio.test\"]}}}" query, _ := unio.Utils.JSONParse(stringQuery) want := unio.JSONObject{ "filter": map[string]interface{}{ "packageName": map[...
package main import ( "fmt" . "leetcode" ) func main() { fmt.Println(pairSum(NewListNode(1, 2, 3, 4))) } func pairSum(head *ListNode) int { var reverse func(head *ListNode) *ListNode reverse = func(head *ListNode) *ListNode { if head == nil || head.Next == nil { return head } newHead := reverse(head...
// 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 p2p import ( "bufio" "github.com/reed/errors" "github.com/reed/log" "github.com/reed/p2p/discover" "github.com/sirupsen/logrus" ...
package partyrobot import ( "fmt" ) // Welcome greets a person by name. func Welcome(name string) string { return "Welcome to my party, " + name + "!" } // HappyBirthday wishes happy birthday to the birthday person and stands out their age. func HappyBirthday(name string, age int) string { return fmt.Sprintf("Hap...
package v1beta8 import ( "github.com/devspace-cloud/devspace/pkg/devspace/config/versions/config" ) // Version is the current api version const Version string = "v1beta8" // GetVersion returns the version func (c *Config) GetVersion() string { return Version } // New creates a new config object func New() config....
//go:build !(linux || windows) // +build !linux,!windows package main // This file is a stub for unsupported platforms to make IDEs happy. // unhandledArgHandler is a handler for unsupported arguments. func unhandledArgHandler(arg string) (string, []cleanupFunc, error) { panic("Platform is unsupported") } // argHa...
//go:build !windows && !freebsd // +build !windows,!freebsd package osutil import ( "fmt" "syscall" ) // RaiseOpenFileLimit tries to maximize the limit of open file descriptors, limited by max or the OS's hard limit func RaiseOpenFileLimit(max uint64) error { var limit syscall.Rlimit if err := syscall.Getrlimit(...
// Copyright © 2019 IBM Corporation and others. // // 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 la...
package types import ( "flag" "testing" "time" ) const errMsg = "Expected `%v`, got `%v`." func TestSetString(t *testing.T) { for _, v := range []struct { v flag.Value fn func(v flag.Value) exp string }{ { &Strings{Value: []string{"a", "b", "c"}}, func(v flag.Value) { v.Set("x") v.Set("...
package main import ( "fmt" "github.com/wagoodman/jotframe/pkg/frame" "io" "math/rand" "time" ) func renderLine(idx int, line *frame.Line) { minMs := 10 maxMs := 50 message := fmt.Sprintf("%s %s INITIALIZED", line, time.Now()) io.WriteString(line, message) for idx := 100; idx > 0; idx-- { // sleep for a ...
//+build linux,arm package bus import ( "errors" "os" "runtime" "syscall" "unsafe" "github.com/zyxar/berry/sys" ) var ( errInvalidBaud = errors.New("invalid baud") ) type serial struct { fd uintptr } func OpenSerial(device string, baud uint) (s *serial, err error) { myBaud := getBaud(baud) if myBaud == ...
package main import ( "log" "web/lib" ) func main() { log.Println("Weclome to Avalon") lib.LogInit(true) lib.Web() }
package main import "fmt" func main() { funcExe(multiplication); funcExe(addition); } func funcExe(handle func()){ handle(); } func addition(){ for i:=1; i<=9 ;i++ { for j:=1;j<=i ;j++ { fmt.Print(i,"+",j,"=",i+j," "); } fmt.Println(""); } } func multiplication(){ for i:=1; i<=9 ;i++ { for j:=...
package mock import ( "net/http" ) // Handler is a mock http.Handler. type Handler struct { serveHTTP func(writer http.ResponseWriter, request *http.Request) } // NewHandler creates a new mock handler. func NewHandler(serveHTTP func(writer http.ResponseWriter, request *http.Request)) *Handler { return &Handler{ ...
package main import ( "testing" // "context" "fmt" "time" ) func TestFuncs(t *testing.T){ //firebase testing // ctx := context.Background() // firebase, err := newFirebase(&ctx) // if err!=nil{ // logger.Printf(err.Error()) // return // } // start := time.Now() // resToken, err := firebase.getToken.fro...
// TOML Parser. package toml import ( "fmt" "reflect" "strconv" "strings" "time" ) type parser struct { flow chan token tree *TomlTree tokensBuffer []token currentGroup []string seenGroupKeys []string } type parserStateFn func(*parser) parserStateFn func (p *parser) run() { for state...
package main import ( "fmt" "math/rand" "ms/sun/shared/helper" "ms/sun_old/base" //"ms/sun/shared/x" "ms/sun/shared/x" "time" ) var write = 0 var read = 0 func main() { base.DefultConnectToMysql() fn := func() { x, err := x.NewHomeFanout_Selector().ForUserId_Eq(rand.Intn(10000)).GetRows(base.DB) read++...
package main import ( "log" "os" "github.com/urfave/cli/v2" ) func main() { app := &cli.App{ Name: "AppStore Review Dumper", Usage: "Dumps recent AppStore reviews of given app", Commands: []*cli.Command{ { Name: "dump", Aliases: []string{"d"}, Usage: "dump dump dumper", Action: fun...
package main import ( "fmt" ) type Node struct { preNodeName string name string weight int } func BellmanFord(relation map[string][]Node, startName string, searchName string) (int, []string) { searchQueue := make([]string, 0) searchQueue = append(searchQueue, startName) searchedMap := make(map[str...
package api import ( "net/http" "github.com/gorilla/mux" log "github.com/sirupsen/logrus" "github.com/rs/cors" ) type Rest struct { router *mux.Router bind string } func CreateAPI(bind string) *Rest { return &Rest{ router: mux.NewRouter(), bind: bind, } } func (a *Rest) Start() error { handler := cors....
package models import ( "awesome_gin/pkg/setting" "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" "log" "time" ) type Model struct { ID int `gorm:"primary_key" json:"id"` Created int `json:"created" gorm:"column:created"` Updated int `json:"updated" gorm:"column:updated"` } var...
package sqlc import ( // "bytes" // "compress/gzip" "fmt" // "io" "io/ioutil" "strings" ) func bindata_read(data []byte, name string) ([]byte, error) { b, err := ioutil.ReadFile(name) if err != nil { return nil, fmt.Errorf("Read: %q: %v", name, err) } return b, nil // gz, err := gzip.NewReader(bytes.NewBuf...
package g import ( "fmt" //引入 mysql 驱动 _ "github.com/go-sql-driver/mysql" "github.com/jinzhu/gorm" //引入 sqlite 驱动 _ "github.com/mattn/go-sqlite3" ) var dbp *gorm.DB //Conn 给其他模块调用的连接池获取方法 func ConnectDB() *gorm.DB { return dbp } //InitDB 初始化数据库连接池 func InitDB(loggerlevel bool) error { if Config().DB.Sqlite...
package rest_test import ( "net/http" "path/filepath" "testing" "github.com/iris-contrib/httpexpect" r "github.com/jinmukeji/jiujiantang-services/api-v2/rest" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) // AnalysisMonthlyReportTestSuite 是AnalysisMonthlyReport的单元测试的 Test Suite ty...
package main import ("fmt" "os" "bufio" "time" ) func main() { var myname string now := time.Now() str1 := "Please enter your WVNCC username:" fmt.Println(str1) fmt.Scanf("%s", &myname) //user enters username fmt.Println("User clock-in: ", myname) fmt.Println("Clock in: ",now.Format(time.ANSIC)) //curren...
// +build js,wasm package main import ( "app/server" wasmhttp "github.com/nlepage/go-wasm-http-server" ) func main() { e := server.New() wasmhttp.Serve(e.Server.Handler) select {} }
package main import ( "fmt" "os" "sort" ) func main() { // Get Number N of horses var N int fmt.Scan(&N) // Collect all strenght of horses strengthsOfHorses := make([]int, N) for i := 0; i < N; i++ { var Pi int fmt.Scan(&Pi) strengthsOfHorses[i] = Pi ...
package e2e import ( "testing" . "github.com/onsi/gomega" ) func TestSimplePublish(t *testing.T) { RegisterTestingT(t) target := getRegistry() + "/publish/simple" Expect(spectrum("build", "-b", "adoptopenjdk/openjdk8:slim", "-t", target, "--push-insecure="+getRegistryInsecure(), "./files/01-simple:/app")...
package schema_test import ( "path/filepath" "runtime" ) func getPath() string { _, filename, _, _ := runtime.Caller(0) return filepath.Dir(filename) }
// Copyright (c) 2015-2017 Marcus Rohrmoser, http://purl.mro.name/recorder // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and // associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights t...
package main import ( "fmt" "github.com/slowteetoe/algorithms/unionfind" "log" "math/rand" "time" ) type grid struct { n int uf unionfind.UnionFind backwash unionfind.UnionFind cells []byte top, bot int } func (g *grid) Display() { for i, val := range g.cells { if i%g.n == 0 && i != 0 { ...
package models import ( "time" ) type Header struct { Vendor string `json:"vendor"` Product string `json:"product"` Type string `json:"type"` Subtype string `json:"subtype"` Version string `json:"template_version"` Date s...
package spellcorrect import ( "fmt" "strings" "testing" "github.com/eskriett/spell" ) func getSpellCorrector() *SpellCorrector { tokenizer := NewSimpleTokenizer() freq := NewFrequencies(0, 0) sc := NewSpellCorrector(tokenizer, freq, []float64{100, 15, 5}) return sc } func TestTrain(t *testing.T) { trainwor...
package main import "fmt" //import "sort" func main() { strings := []string{"syf", "syf", "oxerkx", "oxerkx", "syf", "xgwatff", "pmnfaw", "t", "ajyvgwd", "xmhb", "ajg", "syf", "syf", "wjddgkopae", "fgrpstxd", "t", "i", "psw", "wjddgkopae", "wjddgkopae", "oxerkx", "zf", "...
// // main.go // Copyright (C) 2019 Grigorii Sokolik <g.sokol99@g-sokol.info> // // Distributed under terms of the MIT license. // package main import ( "log" "net/http" _ "net/http/pprof" "os" "os/signal" configUtil "github.com/GSokol/go-aviasales-task/internal/config/util" "github.com/GSokol/go-aviasales-ta...