text
stringlengths
11
4.05M
package logger import ( "fmt" "go.uber.org/zap" ) // Logger zap log type Logger struct { Log *zap.Logger } // ZapLogger alias type ZapLogger = Logger // InitZapLogger initial func InitZapLogger(log *zap.Logger) *Logger { return &Logger{ log, } } // Debug logs a message at level Debug on the ZapLogger. func...
package gnet import ( exp "github.com/jholowczak/guacamole_client_go" "github.com/jholowczak/guacamole_client_go/gio" guid "github.com/satori/go.uuid" ) //InternalDataOpcode const Globle value // * The Guacamole protocol instruction opcode reserved for arbitrary // * internal use by tunnel implementations. The v...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package camera import ( "context" "math/rand" "regexp" "strconv" "strings" "time" "chromiumos/tast/common/media/caps" "chromiumos/tast/ctxutil" "chromiumos/tast/er...
package bill import ( "github.com/life-assistant-go/base" ) // Bill table struct type Bill struct { base.Database billNo string } // TableName set the database table name func (Bill) TableName() string { return "bills" }
package martinier import ( "github.com/go-martini/martini" "github.com/martini-contrib/binding" "github.com/martini-contrib/render" "gopkg.in/mgo.v2" "net/http" ) func NewServer(db *DatabaseConnection) *martini.Martini { engine := martini.New() engine.Use(render.Renderer(render.Options{IndentJSON: true})) eng...
package menu //前端权限菜单节点 var ManageMenus = []map[string]string{ { "key":"index.index.get", "value":"IndexController.Index", }, { "key":"index.index.post", "value":"IndexController.Index1", }, { "key":"common.get_role",//获取所有权限 "value":"CommonController.GetRole", }, { "key":"package.levels.get",//获取行...
/* Copyright 2018 The Chronologist 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, ...
// This Source Code Form is subject to the terms of the MIT License. // If a copy of the MIT License was not distributed with this // file, you can obtain one at https://opensource.org/licenses/MIT. // // Copyright (c) DUSK NETWORK. All rights reserved. package wallet import ( "bytes" "context" "crypto/rand" "os"...
package log4g_test import ( "github.com/kcmvp/log4g" "log" "testing" ) func TestLogToFile(t *testing.T) { rf := log4g.NewRollingFile("hello.log", "", &log4g.TimeRollingPolicy{ Pattern: log4g.Hourly, BasicPolicy: log4g.BasicPolicy{ Backups: 24, Compress: true, }, }) logger := log4g.NewLogger(rf, l...
package air import ( "bufio" "bytes" "compress/gzip" "crypto/tls" "encoding/base64" "encoding/binary" "encoding/json" "encoding/xml" "errors" "fmt" "html/template" "io" "io/ioutil" "mime" "net" "net/http" "net/http/httputil" "net/url" "os" "path" "path/filepath" "strconv" "strings" "sync" "tim...
package controller import ( "bookkeeping/config" "bookkeeping/logic" "net/http" "github.com/gin-gonic/gin" ) func Auth(c *gin.Context) { authCookie, err := c.Cookie(config.AuthCookieName) if err != nil { c.JSON(http.StatusUnauthorized, nil) c.Abort() return } mc, err := logic.ParseToken(authCookie) if...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package wilco import ( "context" "encoding/json" "chromiumos/tast/local/bundles/cros/wilco/wilcoextension" "chromiumos/tast/local/policyutil/fixtures" "chromiumos/tast...
package atgo import ( "context" ) type ( Bank interface { // Collect money into your payment wallet. BankCheckout(ctx context.Context, p *BankCheckoutPayload) (res *BankCheckoutResponse, err error) // Validate a bank checkout charge request BankCheckoutValidate(ctx context.Context, p *BankCheckoutValidate...
package infrastructure import ( "context" "fmt" apihttp "github.com/denis-sukhoverkhov/calendar/internal/infrastructure/api/http" "github.com/denis-sukhoverkhov/calendar/internal/interfaces" "github.com/denis-sukhoverkhov/calendar/internal/interfaces/repositories" "github.com/go-chi/chi" "github.com/go-chi/chi/...
package main import ( "fmt" ) type gridgame struct{ grid grid } func (game gridgame) nextTile(t tile, x, y int64) tile { nextTile := t eachBit(func(b bit) { neighbors := game.grid.countLivingNeighbors(b, x, y) alive := t.bitAlive(b) if alive && (neighbors < 2 || neighbors > 3) || !alive && neighbors == 3 {...
package handlers import ( "net/http" "github.com/kiali/kiali/log" "github.com/kiali/kiali/prometheus" ) // aladdin // InfraDashboard is the API handler to fetch Istio dashboard, related to a single service func InfraDashboard(w http.ResponseWriter, r *http.Request) { // prometheus에 client 등록 prom, err := defaul...
package handlers import ( "html/template" "net/http" ) func ViewHandle(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { t, _ := template.ParseFiles("./views/error.gohtml") myvar := map[string]interface{}{"MyVar": "404 Page was not found"} t.Execute(w, myvar) } else { t, _ := template.Parse...
package diagnostics import "net/http" func setEncodedHeader(req *http.Request) { if req.Method == "GET" { req.Header.Set("Content-Type", "application/x-www-form-urlencoded") } return }
package odoo import ( "fmt" ) // UtmMedium represents utm.medium model. type UtmMedium struct { LastUpdate *Time `xmlrpc:"__last_update,omptempty"` Active *Bool `xmlrpc:"active,omptempty"` CreateDate *Time `xmlrpc:"create_date,omptempty"` CreateUid *Many2One `xmlrpc:"create_uid,omptempty"` ...
package service import ( "context" "errors" "jxc/models" "go.mongodb.org/mongo-driver/bson" ) // 用户验证器 type UserRules struct { UserName string `form:"username" json:"username" binding:"required,min=5,max=20"` Password string `form:"password" json:"password" binding:"required,min=8,max=20"` Phone string `f...
package main import "fmt" type configModel struct { mongoUri string mongoDb string tokenSecret string tokenExp string serveUri string } var config = configModel{ mongoUri: fmt.Sprintf("mongodb://%v:27017/eks", "localhost"), // mongodb://mongodb:27017/eks mongoDb: "eks", ...
package main // Leetcode 5404. (easy) func buildArray(target []int, n int) []string { strs := []string{"Push", "Pop"} res := []string{} idx := 0 for i := 1; i <= n; i++ { if i == target[idx] { res = append(res, strs[0]) idx++ if idx == len(target) { break } } else { res = append(res, strs......
// Package main (02_access_token_auth) demonstrates how to make authenticated // requests to Mondo. To follow this example: // // 1. Log into https://developers.getmondo.co.uk/api/playground; // 2. Copy the "Access token" shown on; // 3. Run the this program with: // MONDO_ACCESS_TOKEN=<paste> go run main.go // // (...
package http import ( "fmt" "net/http" "github.com/gorilla/mux" ) type userHandler struct { } func NewUserHandler(r *mux.Router) { handler := &userHandler{} v1 := r.PathPrefix("/v1").Subrouter() v1.HandleFunc("/test", handler.Test).Methods(http.MethodGet) } func (h *userHandler) Test(w http.ResponseWriter, ...
package lib_gc_cache_source import ( "errors" "sync" LOG "github.com/theskyinflames/go-misc/com.theskyinflames.go.misc/lib_gc_log" ) var mutex *sync.Mutex = &sync.Mutex{} var dmutex *sync.Mutex = &sync.Mutex{} func init() { ICacheMap = &MapCache{make(map[string][]byte)} // Register the cache source CacheSour...
package routers import ( "beego.demo/controllers" "github.com/astaxie/beego" ) func init() { beego.Router("/", &controllers.MainController{}) v1ns := beego.NewNamespace("/v1", beego.NSRouter("/login", &controllers.AdminController{}, "*:Login"), beego.NSRouter("/home", &controllers.HomeController{}, "*:Index"...
package main import "fmt" func main() { for x := 0; x < 1000; x++ { fmt.Println("Hello World") } }
package host import ( "crypto/sha1" "encoding/json" "fmt" "github.com/infraboard/mcube/types/ftime" ) const ( ProvateIDC Vendor = iota Tencent Aliyun HuaWei ) //用int做枚举 type Vendor int func NewDefaultHost() *Host { return &Host{ &Base{}, &Resource{}, &Describe{}, } } type Host struct { *Base *Res...
package pkgset import ( "sync" "golang.org/x/tools/go/packages" ) var stdpkgs Set var stdonce sync.Once // LoadStd preloads the std package list. func LoadStd() { stdonce.Do(func() { standard, err := packages.Load(&packages.Config{ Mode: packages.NeedName | packages.NeedFiles | packages.NeedImports | packa...
package git import ( "testing" "github.com/stretchr/testify/assert" "go.starlark.net/starlark" "github.com/tilt-dev/tilt/internal/tiltfile/starkit" ) func TestGitRepoPath(t *testing.T) { f := NewFixture(t) f.UseRealFS() f.File("Tiltfile", ` print(local_git_repo('.').paths('.git/index')) `) f.File(".git/ind...
package main import "fmt" func main() { half := func(n int) (int, bool) { return n /2, n%2 == 0 } fmt.Println(half(5)) } //package main // //import "fmt" // //func half(x int) (int, bool) { // // div := x / 2 // // if x%2 == 0 { // return div, true // } else { // return div, false // } // //} // //func main(...
/* * * Copyright 2020 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agree...
package review type CreateReviewInput struct { UserID uint MovieID string `json:"movie_id" binding:"required"` Review string `json:"review" binding:"required"` Rate string `json:"rate" binding:"required"` } type UpdateReviewInput struct { MovieID string `json:"movie_id" binding:"required"` Review string `...
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package brightness import ( "context" "fmt" "strconv" "strings" "chromiumos/tast/common/testexec" "chromiumos/tast/errors" ) // Percent gets the current brightness o...
package ymdRedisServer import ( "testing" "sort" "github.com/orestonce/ymd/ymdAssert" "github.com/orestonce/ymd/ymdRedis/ymdRedisProtocol" ) func TestRedisCore_SAdd(t *testing.T) { core := newDebugRedisCore() add, errMsg := core.SAdd(`k`, `m1`, `m2`, `m3`) ymdAssert.True(errMsg == `` && add == 3) add, errMsg ...
package metal import ( "github.com/ionous/sashimi/util/ident" ) type CallbackList struct { callbacks []ident.Id } func (cl CallbackList) NumCallback() int { return len(cl.callbacks) } func (cl CallbackList) CallbackNum(i int) ident.Id { p := cl.callbacks[i] return p // CallbackWrapper(p) }
package strategy import ( "github.com/joshprzybyszewski/cribbage/logic/pegging" "github.com/joshprzybyszewski/cribbage/model" ) func PegHighestCardNow(hand []model.Card, prevPegs []model.PeggedCard, curPeg int) (model.Card, bool) { bestCard := model.Card{} bestPoints := -1 cardsOverMax := 0 for _, c := range h...
package entity import "sync" type UserInfo struct { Id uint64 `json:"id"` Username string `json:"username"` SayHello string `json:"sayHello"` Password string `json:"password"` CreatedAt string `json:"createdAt"` UpdatedAt string `json:"updatedAt"` } type UserList struct { Lock *sync.Mutex IdMap ma...
package repository import ( "../entity" ) type repo struct{} //NewFirestoreRepository func NewFirestoreRepository() PostRepository { return &repo{} } func (*repo) Save(post *entity.Post) (*entity.Post, error) { // implement save method for Firestore return &entity.Post{}, nil } func (*repo) FindAll() ([]entity...
/* Copyright 2014 Huawei Technologies Co., Ltd. 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 la...
package main import ( "fmt" ) func main() { salir := make(chan int) c := gen(salir) recibir(c, salir) fmt.Println("A punto de finalizar.") } func recibir(c, c2 <-chan int) { for { select { case message1 := <-c: fmt.Println("received message1 ", message1) case <-c2: fmt.Println("received exit") ...
package health import ( "net/url" "github.com/cerana/cerana/acomm" "github.com/cerana/cerana/pkg/errors" "github.com/cerana/cerana/provider" ) // Mock is a mock Health provider. type Mock struct { Data MockData } // MockData is mock data for the Mock provider. type MockData struct { Uptime bool File ...
package component import ( "github.com/maxence-charriere/go-app/v7/pkg/app" "github.com/pelly-ryu/minim/app/internal" ) type NoteList struct { app.Compo opened bool } func NewNoteList() *NoteList { return &NoteList{ opened: false, } } func (l *NoteList) Render() app.UI { if !l.opened { return app.Aside(...
package api import ( "encoding/json" "net/http" "github.com/jacexh/golang-ddd-template/internal/application" "github.com/jacexh/golang-ddd-template/internal/transport/dto" ) func CreateUser(w http.ResponseWriter, r *http.Request) { u := new(dto.User) _ = json.NewDecoder(r.Body).Decode(u) _ = application.User....
package stapi // RESTURL of Stapi.co const RESTURL = "http://stapi.co/api/v1/rest" // If the result is bigger than tolerance, return ErrorTooManyResults const maxToleranceResult = 10
package v2 import ( "errors" "fmt" "log" "net/http" "net/url" "github.com/google/uuid" "github.com/labstack/echo/v4" "github.com/traPtitech/trap-collection-server/pkg/types" "github.com/traPtitech/trap-collection-server/src/domain" "github.com/traPtitech/trap-collection-server/src/domain/values" "github.co...
package main import "fmt" // 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 // //你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍 /* 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/two-sum 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ ...
package code import ( "math/rand" "github.com/telecoda/pico-go/console" ) // Code must implement console.Cartridge interface type cartridge struct { *console.BaseCartridge } // NewCart - initialise a struct implementing Cartridge interface func NewCart() console.Cartridge { return &cartridge{ BaseCartridge: ...
package main import ( "github.com/globalsign/mgo" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/go-chi/render" "github.com/thimalw/note-ninja-api/user" ) func routes(db *mgo.Database) *chi.Mux { r := chi.NewRouter() r.Use( render.SetContentType(render.ContentTypeJSON), middleware.L...
package model import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" help "../helper" config "../config" ) var Bdd *sql.DB func TestSql() { fmt.Println("test sql") } func InitBdd() { var err error Bdd, err = sql.Open("mysql", config.DSN()) help.CheckErr(err) } /** Liste des requêtes : Récupér...
package config import ( "fmt" "io/ioutil" "log" "regexp" "sort" "strings" "github.com/openshift-scale/perf-analyzer/pkg/result" "github.com/openshift-scale/perf-analyzer/pkg/utils" "github.com/openshift/origin/test/extended/cluster/metrics" ) type ScrapeConfig struct { EnablePrometheusFlag bool EnablePben...
/** * @Author: lzw5399 * @Date: 2021/1/14 22:13 * @Desc: 流程的定义 */ package model // 流程定义表 type Process struct { EntityBase Code string `json:"code" gorm:"uniqueIndex"` Name string `json:"name"` // 流程名字 Catego...
package dsky import ( "fmt" "strings" "testing" "github.com/spf13/cobra" ) func fakeCLI() *CLI { root := &cobra.Command{ Short: "root short", Use: "root", Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, } cli := New(root) cmd1 := &cobra.Command{ Use: "cmd1", Short: "cmd1-sho...
package main import ( "fmt" "os" "path" "strings" "github.com/golang/glog" "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" clientset "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/scheme" ref "k8s.io/client-go/tools/reference" ) const finalizerName = "nect.com/rook-cephfs-p...
package action import ( "context" "strings" "github.com/hidayatullahap/go-monorepo-example/cmd/auth_service/entity" "github.com/hidayatullahap/go-monorepo-example/pkg" "github.com/hidayatullahap/go-monorepo-example/pkg/errors" "github.com/hidayatullahap/go-monorepo-example/pkg/grpc/codes" "google.golang.org/gr...
package level_ip import ( "io" "log" "os" "os/exec" "strings" "syscall" "unsafe" ) const ( cIFF_TUN = 0x0001 cIFF_TAP = 0x0002 cIFF_NOPI = 0x1000 cIFF_MULTI_QUEUE = 0x0100 ) type TunTap struct { Dev *os.File } type ifReq struct { Name [0x10]byte Flags uint16 pad [0x28 - 0x10...
package main import ( "flag" "log" "os" "strconv" "github.com/hattorious/echoserver/http" "github.com/hattorious/echoserver/tcp" "github.com/hattorious/echoserver/udp" "github.com/hattorious/echoserver/version" ) var ( verbose bool ports struct { http1 string http2 string tcp int udp int } )...
package types import ( "gopkg.in/mgo.v2/bson" ) type Item struct { ID bson.ObjectId `bson:"_id,omitempty" json:"id,omitempty"` Name string `bson:"name" json:"name,omitempty"` Price int `bson:"price" json:"price,omitempty"` Quantity int `bson:"quantity" json:"quantity,omitempty"` } type I...
package parser import ( "unicode" "unicode/utf8" ) func isLetter(ch rune) bool { return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= utf8.RuneSelf && unicode.IsLetter(ch) } func isDigit(ch rune) bool { return '0' <= ch && ch <= '9' || ch >= utf8.RuneSelf && unicode.IsDigit(ch) } co...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package accountmanager import ( "context" "time" "chromiumos/tast/ctxutil" "chromiumos/tast/errors" "chromiumos/tast/local/accountmanager" "chromiumos/tast/local/chro...
package cert import v1 "k8s.io/api/core/v1" func IsValidTLSSecret(secret *v1.Secret) bool { if secret == nil { return false } if _, ok := secret.Data[v1.TLSCertKey]; !ok { return false } if _, ok := secret.Data[v1.TLSPrivateKeyKey]; !ok { return false } return true }
package webui import ( "encoding/json" "io" "net/http" "github.com/dkotik/cuebook" ) // CRUDQ provides a create, retrieve, update, and delete HTTP interfaces with a search and list Query capability. func CRUDQ(b *cuebook.Book) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var err er...
package main import ( "github.com/davecgh/go-spew/spew" ) func main() { var primeTable [100]int primeTable[0] = 2 primeSize := 1 for n := 3; n <= len(primeTable); n += 2 { // n は素数か判定していく。 isPrime := true // 3 は素数ですし。 for i := 1; i < primeSize; i++ { // なんかここが素数判定ロジックっぽいな。奇数をそれまでに見つけた素数で割っ...
package queryparams import ( "bytes" "fmt" "reflect" "github.com/k81/kate/utils" ) // QueryParams for pagination type QueryParams struct { filters map[string]interface{} orderBy []string page int perPage int } var queryRequiredFields = map[string]reflect.Type{ "Page": reflect.TypeOf(int(0)), "PerPag...
package main import ( "ekfet-golang/gorm/dao" "github.com/jinzhu/gorm" ) type Product struct { gorm.Model Code string Price uint } type SysCountry struct { //gorm.Model Id uint `gorm:"column:id"` Cn string `gorm:"column:cn"` En string `gorm:"column:en"` Code string `gorm:"column:code"` } func (Sy...
package main import ( "flag" "fmt" "io" "log" "os" "sort" "strings" ) var ( path = flag.String("p", ".", "the path for the program") printFiles = flag.Bool("f", true, "do you need to print files?") ) var interfaceElements = map[string]string{ "Т": "├───", "Г": "└───", "-": "│", } func dirTree(out ...
package core import "fmt" func ErrorHandler(code int) { errMap := map[int]string{ 40001: "app_key或app_secret不合法", 40002: "access_token过期", 40003: "wxcode不合法", 40005: "access_token无效", 40006: "school_code不存在", 40007: "电子卡号不存在", 40008: "权限不足", 40009: "参数缺失", 40010: "参数错误", 40018: "该主体没有开启应用", } f...
package get import ( "encoding/json" "net/http" "github.com/ocoscope/face/db" "github.com/ocoscope/face/utils" "github.com/ocoscope/face/utils/answer" ) func Lunch(w http.ResponseWriter, r *http.Request) { type tbody struct { CompanyID, UserID uint AccessToken string } var body tbody err := jso...
package handler import ( "movie-app/helper" "movie-app/movie" "github.com/gin-gonic/gin" ) type MovieHandler interface { GetAllMovie(c *gin.Context) CreateMovie(c *gin.Context) } type movieHandler struct { movieService movie.Service } func NewMovieHandler(movieService movie.Service) *movieHandler { return &...
package requests import ( "net/url" "github.com/google/go-querystring/query" "github.com/atomicjolt/canvasapi" ) // SearchAccountDomains Returns a list of up to 5 matching account domains // // Partial match on name / domain are supported // https://canvas.instructure.com/doc/api/account_domain_lookups.html // /...
package user import ( "fmt" log "github.com/sirupsen/logrus" "github.com/opsbot/cli-go/utils" "github.com/opsbot/zerotier/api" "github.com/spf13/cobra" ) // GetCommand returns a cobra command func GetCommand() *cobra.Command { var outputDocument string cmd := &cobra.Command{ Use: "get", Short: "get us...
package main import "fmt" func main() { mySlice := []string{"Monday", "Tuesday"} myOtherSlice := []string{"Wednesday", "Thursday", "Friday"} mySlice = append(mySlice, myOtherSlice...) fmt.Println(mySlice) mySlice = append(mySlice[:2], mySlice[3:]...) //enganacao, só tira a posicao que vc nao quer //no caso t...
package bitwarden import ( "bytes" "encoding/base64" "encoding/json" "errors" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "sync" "github.com/sirupsen/logrus" ) type cliClient struct { username string password string sync.Mutex session string savedItems []Item run func(args ...string) ...
package wxapi //授权方授权信息 type APPAuthInfoResp struct { AuthorizationInfo struct{ AuthorizerAppid string `json:"authorizer_appid"`//授权方appid AuthorizerAccessToken string `json:"authorizer_access_token"`//授权方接口调用凭据 ExpiresIn string `json:"expires_in"`//有效期 AuthorizerRefreshToken stri...
package db import ( "github.com/chadweimer/gomp/models" "github.com/jmoiron/sqlx" ) type sqlAppConfigurationDriver struct { Db *sqlx.DB } func (d *sqlAppConfigurationDriver) Read() (*models.AppConfiguration, error) { return get(d.Db, func(db sqlx.Queryer) (*models.AppConfiguration, error) { cfg := new(models.A...
/* Copyright 2021 The Skaffold 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, sof...
// Copyright 2019 Contentsquare // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agre...
package requirements import "testing" type TestStruct struct { lengths []int res float64 } var toTest = []TestStruct{ { lengths: []int{3, 4, 5}, res: 6.0, }, } var panicTest1 = []int{3, 4, 7} var panicTest2 = []int{-3, 4, 5} func TestGetTriangleArea(t *testing.T) { var area float64 for i := range...
package main import "fmt" func main() { // output // 1 // 2 // 3 i := 1 for i <= 3 { fmt.Println(i) i = i + 1 // `i += 1` is also valid } // output // 7 // 8 // 9 for j := 7; j <= 9; j++ { fmt.Println(j) } // output // loop for { fmt.Println("loop") break } // output // 1 // 3 // 5 ...
package client import ( "bufio" "context" "encoding/json" "errors" "fmt" "io" "log" "net" "net/http" "strings" "sync" "time" "gorpc/codec" "gorpc/option" "gorpc/server" ) // Call 承载一次 rpc 调用 type Call struct { Seq uint64 // 请求编号 ServiceMethod string // 格式 <service>.<method> Args...
package book import ( "fmt" "github.com/gorilla/mux" "net/http" ) func LoadRoutes(prefix string, router *mux.Router) { router.HandleFunc(prefix, index) router.HandleFunc(prefix+ "/{id}", show) } func index(writer http.ResponseWriter, request *http.Request) { fmt.Println("Book index") } func show(writer http.Re...
package supervisor_test import ( "fmt" "net/http" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" // sql drivers _ "github.com/mattn/go-sqlite3" "github.com/starkandwayne/shield/db" . "github.com/starkandwayne/shield/supervisor" ) var _ = Describe("/v1/stores API", func() { var API http.Handler var...
package main import ( "net/http" "os" api "github.com/Financial-Times/api-endpoint" "github.com/Financial-Times/http-handlers-go/httphandlers" "github.com/Financial-Times/photo-tron/annotations" "github.com/Financial-Times/photo-tron/fotoware" "github.com/Financial-Times/photo-tron/health" "github.com/Financi...
// Copyright (c) KwanJunWen // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. package estemplate import "fmt" // DatatypeInteger Core Datatype for numeric value. // A signed 32-bit integer with a minimum value of -2³¹ and a maximum value of ...
// https://leetcode.com/problems/leaf-similar-trees/ package leetcode_go /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func leafSimilar(root1 *TreeNode, root2 *TreeNode) bool { l1, l2 := []int{}, []int{} helperP872(root1, &l1...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package vkb contains shared code to interact with the virtual keyboard. package vkb import ( "context" "fmt" "regexp" "strconv" "strings" "time" "github.com/mafre...
package 前缀和 func numberOfSubarrays(nums []int, k int) int { if len(nums)==0{ return 0 } m:=make(map[int]int,len(nums)+1) oddnum :=0 count:=0 m[0]=1 for _,v:=range nums{ oddnum+=v&1 if v,ok:=m[oddnum-k];ok{ count+=v } m[oddnum]++ } return count }
package nanoid import gonanoid "github.com/matoous/go-nanoid/v2" type IDGenerator interface { Generate() string } type nanoid struct{} func New() IDGenerator { return &nanoid{} } func (*nanoid) Generate() string { id, err := gonanoid.New(11) if err != nil { panic("can't generate nanoid") } return id }
// Copyright 2020 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package main import ( "fmt" "strconv" "time" ) func main() { m := map[string]string{} go func() { for i := 0; i < 200000; i++ { istr := strconv.Itoa(i) m[istr] = istr } }() go func() { for i := 0; i < 200000; i++ { if _, ok := m["02"]; ok { fmt.Println("aa") } } }() time.Sleep(3 * ti...
package util import ( "fmt" "io/ioutil" "net/url" "os" "path/filepath" "sync" ) type info struct { ObjectMeta GitServerURL *gitURL // The git server address GitAPIURL *releaseURL // The address of the git api GitHome string // The base path of the stored files GitRevision string // ...
package main import "math" import "math/rand" import "math/big" import "errors" import "fmt" import "os" type Key struct { key int n int } type KeyPair struct { Private Key Public Key } func isPrime(n int) bool { if n == 1 { return false } for i := 2; i <= int(math.Floor(math....
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package health import ( "context" "chromiumos/tast/errors" "chromiumos/tast/local/croshealthd" "chromiumos/tast/testing" ) type audioInfo struct { InputDeviceName st...
package operator import ( "context" "fmt" "reflect" "strconv" "strings" "time" "github.com/ghodss/yaml" operatorv1 "github.com/openshift/api/operator/v1" deschedulerv1beta1 "github.com/openshift/cluster-kube-descheduler-operator/pkg/apis/descheduler/v1beta1" operatorconfigclientv1beta1 "github.com/openshif...
package main import ( "database/sql" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "strconv" _ "github.com/go-sql-driver/mysql" "github.com/gorilla/mux" ) //Todo Struct type Todo struct { UserID int `json:"userId"` ID int `json:"id"` Title string `json:"title"` Completed bool ...
package main import "fmt" //常量 学习 const p ="date & taxes" func main() { const q = 42 fmt.Println(p) fmt.Println(q) }
package lexers import ( "regexp" ) // TODO(moorereason): can this be factored away? var bashAnalyserRe = regexp.MustCompile(`(?m)^#!.*/bin/(?:env |)(?:bash|zsh|sh|ksh)`) func init() { // nolint: gochecknoinits Get("bash").SetAnalyser(func(text string) float32 { if bashAnalyserRe.FindString(text) != "" { retur...
package datastore import ( "context" "errors" "cloud.google.com/go/datastore" "github.com/go-kit/kit/log" "google.golang.org/api/iterator" "github.com/revas/animo-service/pkg" ) type GoogleDatastoreAnimoService struct { Logger log.Logger Client *datastore.Client } // Ensure InMemoryAnimoService implements ...
package interfaces import "github.com/t-ash0410/tdd-sample/backend/internal/api/todo/entities" type IListUsecase interface { Handle(result *[]entities.Task) error } type IAddUsecase interface { Handle(name string, description string) error }
package main import "fmt" type Directon int const ( North Directon = iota East South West ) func (d Directon) String() string { return [...]string{"North", "East", "South", "West"}[d] } func main() { fmt.Println(South) }