text
stringlengths
11
4.05M
package openvswitch import ( "strings" "net" "github.com/Sirupsen/logrus" ) func GenerateNetworkAndHealthCheck(uri string) (string, error) { var err error network := "unix" if strings.Contains(uri, ":") { network = "tcp" } conn, err := net.Dial(network, uri) if err != nil { logrus.WithFields(logrus.Fiel...
package main import "fmt" func main() { slice := []string{"banana", "maçã", "jaca"} for index, value := range slice { fmt.Println("Index:", index, "there is the value:", value) } // slice[3] = "pêssego" // error array subjacente é de 3 elementos // []string{"banana", "maçã", "jaca"} from [3]string{"banana",...
package asocks var bufferPool = make(chan []byte, 100) func GetBuffer() []byte { var buffer []byte select { case buffer = <-bufferPool: default: buffer = make([]byte, 5120) } return buffer } func GiveBuffer(buffer []byte) { select { case bufferPool <- buffe...
package registrator //Registrator defines contract for services to register themselves to the Service Discovery Service type Registrator interface { Register(serviceName , serviceID , server string , port int ) error Deregister(serviceID string) error }
package evaluator import ( "os" "github.com/kasworld/nonkey/enum/objecttype" "github.com/kasworld/nonkey/interpreter/asti" "github.com/kasworld/nonkey/interpreter/object" ) // os.getenv() -> ( Hash ) func builtinOsEnvironment(node asti.NodeI, env *object.Environment, args ...object.ObjectI) object.ObjectI { os...
package model import ( gj "github.com/kpawlik/geojson" ) type Location struct { Type string `json:"type"` Coordinates gj.MultiLine `json:"coordinates"` } type PolyRegion struct { Name string `json:"name"` Location Location `json:"location,omitempty"` }
/* Copyright 2021 The KubeVela Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, so...
package replacement // // @title 测试文档 // @version v1.0 // @desc 此处可写一些 API 的相关说明 // @host 192.168.5.6:8080,api.dlab.com // @basePath / // -------- Module -------- // @tag.name 日志模块 // @tag.name 订单模块 // @tag.name 物流模块 // ------- Security ------- // @securityDef.apikey JWT_Token /...
package main import ( "database/sql" "io/ioutil" "log" "net/http" "strconv" "github.com/go-chi/chi" _ "github.com/jackc/pgx/v4/stdlib" ) // This is an example of a trivial Web Service running against a PostgreSQL // database, to illustrate the problem of how to pass sql.DB instances (or // other pieces of glo...
package logic import ( "testing" "fmt" ) func TestNewLogicMemoryDecorator(t *testing.T) { fmt.Println("Process with memory.") handler := NewHandler() handler.WrapMemory() //Run the process. handler.Operate1() }
package main import ( "github.com/gabrielEscame/go-engine/engine" "github.com/gabrielEscame/go-engine/pong" "github.com/veandco/go-sdl2/sdl" ) func main() { ball := pong.NewBall(50, 50, 10) player := pong.NewPlayer() e := engine.NewEngine() entities := []engine.CollidableEntity{ ball, player, } e.Setu...
package main import ( "fmt" "github.com/gorilla/mux" "net/http" ) const ( userID = "user_id" ) var router *mux.Router func index(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html") url, err := router.Get(userID).URL("id", "1") if err != nil { http.Error(w, "Something went ...
package pagination import ( "testing" "gotest.tools/assert" ) func Test_ORMLimit(t *testing.T) { // positive case limit, offset, err := GetORMLimitOffset(1, 5, 12) assert.Assert(t, err == nil) assert.Equal(t, limit, 5) assert.Equal(t, offset, 0) // nagitive case, pagesize overload limit, offset, err = GetOR...
package store import ( "errors" "github.com/stetsd/blo-go/models" ) var articleList = []models.Article{ models.Article{ID: 1, Title: "Article 1", Content: "Turbo Power!!!"}, models.Article{ID: 2, Title: "Article 2", Content: "Turbo Love!!!"}, } var userList = []models.User{ models.User{Username: "boris", Passwo...
package util import ( "bytes" "encoding/binary" ) func PanicIfErr(err error) { if err != nil { panic(err) } } func PanicIfErrMsg(err error, msg string) { if err != nil { panic(msg) } } //整形转换成字节 func IntToBytes(n int) []byte { x := int32(n) bytesBuffer := bytes.NewBuffer([]byte{}) _ = binary.Write(byte...
// Source : https://oj.leetcode.com/problems/unique-paths/ // Author : Austin Vern Songer // Date : 2016-03-07 /********************************************************************************** * * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). * * The r...
package detector import ( "errors" log "github.com/golang/glog" "github.com/samuel/go-zookeeper/zk" "github.com/stretchr/testify/assert" "os" "strings" "testing" "time" ) var test_zk_hosts = []string{"localhost:2181"} func TestZkClientNew(t *testing.T) { path := "/mesos" chEvent := make(chan zk.Event) con...
package datastore import ( "github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions/redis" "github.com/raychongtk/go-web/util" "net/http" ) func ProvideSessionStore() redis.Store { var config *SessionConfig util.Load("dev", ".", &config) store, _ := redis.NewStore(10, "tcp", config.SessionAddress, co...
// +build !remoteclient package main import ( "fmt" "os" "github.com/containers/buildah/pkg/parse" "github.com/containers/libpod/pkg/apparmor" "github.com/containers/libpod/pkg/cgroups" "github.com/containers/libpod/pkg/rootless" "github.com/containers/libpod/pkg/sysinfo" "github.com/opencontainers/selinux/g...
package craft import "complie/src/tokentype" type Token interface { //返回token类型 GetType() tokentype.TokenType //返回token文本 GetText() string } type SimpleToken struct { ttype tokentype.TokenType text string } func NewSimpleToken() *SimpleToken { return &SimpleToken{ ttype: 0, text: "", } } func (this *S...
package nanokontrol2 import ( "fmt" "github.com/telyn/midi/korg/korgdevices" "github.com/telyn/midi/korg/korgsysex/format4" "github.com/telyn/midi/sysex" ) const ( SetModeRequestID byte = 0x00 DataDumpRequestID byte = 0x1F ) const ( ModeRequestFunctionID byte = 0x12 ) type DataDumpRequest struct { Channel...
package weibo import ( "context" "net/http" "net/url" "time" "github.com/otamoe/oauth-client" ) type ( Client struct { oauth.OAuth2 } ) var Endpoint = oauth.Endpoint{ Name: "weibo", AuthorizeURL: "https://api.weibo.com/oauth2/authorize", AccessTokenURL: "https://api.weibo.com/oauth2/acces...
package main import "fmt" func main() { i := 100 var j int = 1234 fmt.Printf("%v + %v = %v\n", i, j, i+j) f := 1.5 fmt.Printf("f = %v\n", f) }
package catapult import ( "net/http" "time" "net/url" "net" "bytes" "encoding/json" "io" "github.com/k0kubun/pp" "golang.org/x/net/context" "gopkg.in/h2non/gentleman.v1/utils" ) type Request struct { timeout time.Duration Context *Ctx rawRequest *http.Request } func (r *Request) populateRaw...
package main import "fmt" func enqueue(queue[] int, element int) []int { queue = append(queue, element); // Simply append to enqueue. fmt.Println("Enqueued:", element); return queue } func dequeue(queue[] int) ([]int) { element := queue[0]; // The first element is the one to be dequeued. fmt.Println("Dequeu...
package installer import ( "fmt" "github.com/wx13/genesis" ) var StatusCount struct { Pass, Fail, Unknown, Done int } func ReportSummary() { fmt.Println("") fmt.Println(" Summary:") fmt.Println(" Pass: ", StatusCount.Pass) fmt.Println(" Done: ", StatusCount.Done) fmt.Println(" Unknown:...
package product import ( "context" "fmt" "errors" "strings" "github.com/gingerxman/eel" ) const STICK_BOUNDARY = 10000000 const DISPLAY_INDEX_ORDER_ASC = 1 const DISPLAY_INDEX_ORDER_DESC = 2 type ItemPos struct { Id int Table string DisplayIndex int OriginalDisplayIndex int } type itemPos = ItemPos var _...
package cmd import ( "fmt" "os" "github.com/spf13/cobra" ) var stancrCmd = &cobra.Command{ Use: "stancr", Short: "A template (boilerplate) manager for scaffolding your future projects", Run: func(cmd *cobra.Command, args []string) { fmt.Println("Hello Stancr!") }, } // Execute the stancr (cobra) root com...
package main import ( "fmt" "os" "strings" ) // Directory List // Natural sort (by directory then name) type FileSort []os.FileInfo func (l FileSort) Len() int { return len(l) } func (l FileSort) Swap(i, j int) { l[i], l[j] = l[j], l[i] } func (l FileSort) Less(i, j int) bool { if l[i].IsDir() && !l[j].IsDir...
package controller import ( "net/http" "posthis/utils" "strconv" "github.com/gorilla/context" "github.com/gorilla/mux" ) //Handlers func GetReposts() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { repostModel := RepostModel{} vars := mux.Vars(r) strId := vars["id...
package main import ( "fmt" "io" "log" "net/http" "os" "os/exec" "github.com/jantb/olive/editor" ) import _ "net/http/pprof" import _ "net/http" type readwriter struct { io.Reader io.Writer } func die(format string, args ...interface{}) { fmt.Fprintf(os.Stderr, format, args...) os.Exit(1) } func main() {...
package chain import ( "github.com/iotaledger/wasp/packages/coretypes/requestargs" "os" "github.com/iotaledger/wasp/client/chainclient" "github.com/iotaledger/wasp/packages/coretypes" "github.com/iotaledger/wasp/packages/sctransaction" "github.com/iotaledger/wasp/tools/wasp-cli/log" "github.com/iotaledger/wasp...
package main import ( "bufio" "encoding/json" "fmt" "os" "sort" "strings" "time" ) // Schedule holds data about one rotation. type Schedule struct { Title string `json:"title"` Periods []string `json:"periods"` Times []string `json:"times"` Dismissal string `json:"dismissal"` } // ScheduleMa...
//+build !amd64 noasm package assembler func L2(X []float32) (nrm2 float32) { for i := range x { sum += x[i] * x[i] } sum = Sqrt(sum) return }
/* * Copyright 2018 Haines Chan * * This program is free software; you can redistribute and/or modify it * under the terms of the standard MIT license. See LICENSE for more details */ package monkey import ( "encoding/json" "github.com/hainesc/anchor/pkg/store/etcd" "log" "net/http" "strings" ) // InUseHan...
package util import "errors" // Various errors for help with signalling erroneous state var ( ErrorAlreadyRunning = errors.New("already running") ErrorNotRunning = errors.New("not running") ) // BaseConfig holds data that is common to all Transport implementations type BaseConfig struct { Path str...
package seev import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document03600108 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:seev.036.001.08 Document"` Message *CorporateActionMovementConfirmationV08 `xml:"CorpActnMvmntConf"` }...
package handler import ( "strings" "github.com/hashicorp/hcl/v2" "github.com/hashicorp/hcl/v2/hclsyntax" "github.com/hashicorp/hcl/v2/hclwrite" "github.com/zclconf/go-cty/cty" "go.mercari.io/hcledit/internal/ast" ) type readHandler struct { results map[string]cty.Value } func NewReadHandler(results map[stri...
package git /* #include <git2.h> #include <git2/sys/openssl.h> */ import "C" import ( "bytes" "encoding/hex" "errors" "runtime" "strings" "unsafe" ) //go:generate stringer -type ErrorClass -trimprefix ErrorClass -tags static type ErrorClass int const ( ErrorClassNone ErrorClass = C.GIT_ERROR_NONE Error...
package main import ( "fmt" "github.com/jeffreylowy/intro-to-go/henlo" "github.com/jeffreylowy/intro-to-go/loops" ) func main() { //randNum := generateRandomNumber(generateSeedValue(), 100) askQuestion() kals := henlo.Doggo{ Name: "Kali", Color: "gray and white", Age: 8, } k := fmt.Sprintf("My dog...
package service import ( "context" "fmt" pbDD "github.com/go-ocf/cloud/resource-directory/pb/device-directory" "github.com/go-ocf/sdk/schema/cloud" coap "github.com/go-ocf/go-coap" "github.com/go-ocf/kit/codec/cbor" "github.com/go-ocf/kit/codec/json" "github.com/go-ocf/kit/strings" "google.golang.org/grpc/c...
package db import ( "fmt" "log" ) const tmpName = "asdhiaosdjhasoingqe" func SwapTable(table1, table2 string) { db, err := dbConnection() if err != nil { log.Fatal(err) } tx := db.Begin() if err = tx.Exec(fmt.Sprintf("RENAME table %s to %s, %s to %s, %s to %s", table1, tmpName, table2, table1, tmpName, ta...
package mysql_storage import ( "database/sql" "github.com/jmoiron/sqlx" "server/src/dto" ) type ArticleRepository struct { db *sqlx.DB } func (repo *ArticleRepository) GetArticleById(id int) (*dto.Article, error) { selectStatement := "SELECT * FROM `Articles` WHERE ArticleId = ?" article := &dto.Article{} if ...
package setup import ( "github.com/rancher/norman/httperror" "github.com/rancher/norman/types" "github.com/rancher/rancher/pkg/auth/tokens" ) func AuthProviderFormatter(apiContext *types.APIContext, resource *types.RawResource) { resource.AddAction(apiContext, "login") } func ActionHandler(actionName string, act...
package auth import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document01300101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:auth.013.001.01 Document"` Message *MoneyMarketUnsecuredMarketStatisticalReportV01 `xml:"MnyMk...
package hpke_test import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/pomerium/pomerium/pkg/hpke" ) func TestStubFetcher(t *testing.T) { t.Parallel() hpkePrivateKey, err := hpke.GeneratePrivateKey() require.NoError(t, err) expected := hpkePr...
package mail import ( "os" "github.com/mitchdennett/flameframework/contracts" "github.com/mitchdennett/flameframework/drivers" ) func Compose() contracts.MailContract { maildriver := os.Getenv("MAIL_DRIVER") if maildriver == "smtp" { return drivers.MailSmtpDriver{} } else { } return drivers.MailSmtpDrive...
package main import ( "bufio" "fmt" "os" "strconv" ) func main() { scan := bufio.NewScanner(os.Stdin) scan.Scan() t, _ := strconv.Atoi(scan.Text()) for ; t > 0; t-- { scan.Scan() s := scan.Text() tot := 0 for i := 0; i < len(s)/2; i++ { j := len(s) - 1 - i a := s[i] b := s[j] if a > b { ...
package download import ( "net/http" "net/url" "time" ) type Task struct { Client *http.Client Request *http.Request } func Default() *Task { req, _ := http.NewRequest("GET", "", nil) return &Task{ Request: req, Client: &http.Client{}, } } func (t *Task)URL(dst string) error { u, err := url.Parse(dst...
package graphql import ( "context" "testing" "github.com/sensu/sensu-go/backend/apid/graphql/schema" "github.com/sensu/sensu-go/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) type mockQueryEventFetcher struct { record *types.Event err error } func (m mockQueryEventFet...
package menu // Menu router import ( "strconv" "net/http" "encoding/json" "portal/util" "portal/model" "portal/service" "github.com/gin-gonic/gin" ) // Create router func CreateRouter(c *gin.Context) { var jsonBody model.Route err := c.BindJSON(&jsonBody) if err != nil { util.RespondBadRequest(c) retur...
package dynamic func (name Name) Compact(args ...interface{}) (paramNames []string, paramAndValues map[string]interface{}) { return name.DepthCompact(1, args...) } func (name Name) DepthCompact(depth int, args ...interface{}) (paramNames []string, paramAndValues map[string]interface{}) { paramNames = name.VarNameDe...
/* Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4] Note: Each element in the result must be unique. The result can be in any order. */ package main import...
package main import ( "reflect" "testing" ) func TestCalc(t *testing.T) { tests := []struct { name string args string want string wantErr bool }{ { name: "simple calculation", args: "2+3-1", want: "4", wantErr: false, }, { name: "calculation with different priorit...
/* Copyright © 2022 SUSE 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 writing, software distri...
package hash_table import ( "fmt" "errors" ) type Node struct { Data interface{} Key int } type HashTable struct { table []*Node } func NewHashTable(len int) (*HashTable, error) { if len <= 0 { return nil, errors.New("Hashtable's size must be over 0!") } ht := &HashTable{} ht.SetS...
package src import ( "bytes" "encoding/json" "net/http" "github.com/getsentry/sentry-go" log "github.com/sirupsen/logrus" ) type Events struct { newEventIds []uint64 events []Dogodek } func getEvents(english bool) ([]Dogodek, error) { log.Debug("Retrieving traffic data...") url := "https://opendata.si...
package proc import ( "io/ioutil" "path/filepath" "strings" ) func extractCmdLine(basePath string) (string, error) { content, err := ioutil.ReadFile(filepath.Join(basePath, cmdLine)) if err != nil { return "", err } c := 0 // cursor of useful bytes for i := 0; i < len(content)-1; i++ { // Check if next by...
package ldclient import ( "regexp" "strings" ) const ( operatorIn Operator = "in" operatorEndsWith Operator = "endsWith" operatorStartsWith Operator = "startsWith" operatorMatches Operator = "matches" operatorContains Operator = "contains" ) type opFn (func(interface{}, interface{}) bool) var ...
package ep import ( "github.com/harriklein/pBE/pBEServer/ep/auth" "github.com/harriklein/pBE/pBEServer/ep/docs" "github.com/harriklein/pBE/pBEServer/ep/dummy" ) // EndPointsInit initializes all endpoints func Init() { auth.Init() dummy.Init() docs.Init() }
/* 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...
// +build unit package utils import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) func TestGetFreePort(t *testing.T) { addr, port, err := GetFreeAddrPort() assert.NoError(t, err) assert.NotEqual(t, port, 0) assert.Equal(t, addr, fmt.Sprintf("127.0.0.1:%d", port)) }
// Package okta implements OpenID Connect for okta // // https://www.pomerium.com/docs/identity-providers/okta package okta import ( "context" "fmt" "github.com/pomerium/pomerium/internal/identity/oauth" pom_oidc "github.com/pomerium/pomerium/internal/identity/oidc" ) const ( // Name identifies the Okta identit...
package pdu import ( "errors" "fmt" "log" "strings" "time" expect "github.com/google/goexpect" "github.com/ziutek/telnet" ) type PDU struct { ex expect.Expecter timeout time.Duration } func Dial(network, addr string, timeout time.Duration) (*PDU, error) { conn, err := telnet.Dial(network, addr) if e...
package main import ( "flag" "log" "strconv" "time" "github.com/matscus/Hamster/Package/Clients/client" "github.com/matscus/Hamster/Guns/busM5/asserts" "github.com/matscus/Hamster/Guns/busM5/mqops" "github.com/matscus/Hamster/Guns/busM5/pool" ) var ( duration ...
package run import ( "encoding/json" "io/ioutil" "sync" "time" ) type Run struct { sync.RWMutex ID string Name string Category string segments []*Segment started, ended time.Time paused time.Duration } func Load(filename string) (*Run, error) { data, err := iout...
package kubernetes import ( "context" "encoding/base64" "encoding/json" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // DockerCredential provides login information for authenticating to a Docker Registry type DockerCredential struct { Username string `json:"username"` Password strin...
package handler import ( "context" "errors" "fmt" "github.com/jinmukeji/go-pkg/v2/age" "github.com/golang/protobuf/ptypes" "github.com/jinmukeji/jiujiantang-services/service/auth" "github.com/jinmukeji/jiujiantang-services/service/mysqldb" corepb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/cor...
package main func trailingZeroes(n int) int { // 有5 * 2就会多一个0.而且2的数量远远比5的数量多(2的倍数和5的倍数) // 所以只要算5的数量。25 = 5 * 5, 125 = 5 * 5 * 5,以此类推 res := 0 for n > 0 { n /= 5 res += n } return res }
package repo import ( "github.com/google/uuid" "grhamm.com/todo/data" "grhamm.com/todo/entity" ) var todoList []entity.Todo func Insert(todo entity.Todo) entity.Todo { return data.InsertTodo(todo) } func Index() []entity.Todo { return data.FindTodo() } func UpdateToFinished(id uuid.UUID) { data.SetFinishTodo...
package authentication import ( "fmt" "strings" "github.com/go-ldap/ldap/v3" "github.com/authelia/authelia/v4/internal/configuration/schema" "github.com/authelia/authelia/v4/internal/utils" ) // StartupCheck implements the startup check provider interface. func (p *LDAPUserProvider) StartupCheck() (err error) ...
package leetcode func removeDuplicates(S string) string { stack := make([]rune, len(S)) size := 0 for _, c := range S { if size > 0 && c == stack[size-1] { size-- } else { stack[size] = c size++ } } return string(stack[:size]) }
package main import ( "fmt" "io" "log" "strconv" "strings" "syscall/js" "github.com/embly/star" "github.com/embly/star/src" "go.starlark.net/resolve" "go.starlark.net/starlark" "go.starlark.net/syntax" ) func main() { registerCallbacks() c := make(chan struct{}, 0) star.AddPackages(src.Packages) threa...
package main import ( "github.com/kataras/iris" "github.com/bxyb214/iot-lock-server/apis" ) func Route(app *iris.Application) { apiPrefix := Config.Api.Prefix router := app.Party(apiPrefix) { router.Get("/login", apis.Login) } }
package aliyunsms import ( "net/url" "testing" ) const ( AccessKeyID = "AccessKeyID" AccessKeySecret = "AccessKeySecret" SignName = "阿里云短信测试专用" ) func Test_signature_method(t *testing.T) { string_to_sign := `POST&%2F&AccessKeyId%3Dtestid%26Action%3DSingleSendSms%26Format%3DXML%26ParamString%3D%257B%2522name%2...
package example //go:generate genmock -package=github.com/philpearl/ut/example -interface=Fred -mock-package=example type George struct{} type Fred interface { sanit(blah string) iit(fred any) many(things ...string) doit(blah string) int donit(blah, fah string) (int, error) adonit(blah, fah George, brian func(...
package mux import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "net/http" ) var _ = Describe("mux", func() { It("should return a new mux with empty routes", func() { mux := GetNewMux() Expect(mux).NotTo(BeNil()) Expect(mux.routes).To(HaveLen(0)) }) It("should register a new handler function",...
package models import ( "encoding/json" "io/ioutil" "project/modules/generators" "sync" ) const ( sessionsfilePath = `/tmp/sessions.json` ) type Session struct { Key string `json:"key"` Caches map[string]*Cache `json:"caches"` sync.RWMutex } func signup() ( session *Session, ) { caches := ...
/* For license and copyright information please see LEGAL file in repository */ package approuter // Assets use to store app needed data from repo like html, css, js, ... type Assets struct { Name string Files map[string]*AssetsFile // Name Dependencies map[string]*Assets // Name } // AssetsFil...
package easypost import ( "context" "github.com/google/uuid" "io" "net/url" "time" ) // HookEvent is the base type for all hook events type HookEvent struct { } // HookEventSubscriber is the base type for all hook event subscribers. // ID needs to be unique in order to find and remove the subscriber type HookEv...
package data import ( "fmt" ) type cellsBase struct { cells map[string]*Cell } func newCellsBase() *cellsBase { return &cellsBase{make(map[string]*Cell)} } // IsEmpty returns whether a set is empty func (s *cellsBase) IsEmpty() bool { return 0 == len(s.cells) } func (s *cellsBase) Size() int { return len(s.ce...
package main import "fmt" func main() { fmt.Println(max()) fmt.Println(max(3)) fmt.Println(max(1, 2, 3, 4)) fmt.Println(min()) fmt.Println(min(3)) fmt.Println(min(1, 2, 3, 4)) values := []int{1, 2, 3, 4} fmt.Println(max(values...)) fmt.Println(min(values...)) } func max(vals ...int) int { temp := 0 for...
package main import ( "encoding/json" "fmt" "log" "net/http" "strings" ) type API struct { mux *http.ServeMux service *Service } func (api *API) ServeHTTP(w http.ResponseWriter, r *http.Request) { api.mux.ServeHTTP(w, r) } func APIHandler(service *Service) http.Handler { api := new(API) api.service = ...
package awspreset import ( "bytes" "encoding/json" "io" "io/ioutil" "net/http" "regexp" "github.com/pkg/errors" ) const ( errFailedToExtractConsoleCSRF = "failed to extract CSRF token from console HTML body" errFailedToEncodeRequest = "failed to encode JSON request" errFailedToDecodeResponse = "fa...
package clone_mt19937 const ( uMT = 11 dMT = 0xffffffff sMT = 7 bMT = 0x9d2c5680 tMT = 15 cMT = 0xefc60000 lMT = 18 ) func Untemper(number uint32) uint32 { y := number y ^= y >> lMT y ^= y << tMT & cMT for i := 0; i < sMT; i++ { y ^= y << sMT & bMT } y ^= y >> uMT y ^= y >> (uMT * 2) return y }
package testx import "testing" const ( ErrorTextFormat = "%v not equal: [\nExpected: %v\nActual: %v\n]\n" ) func CompareString(label string, expected string, actual string, t *testing.T) bool { if expected != actual { t.Errorf(ErrorTextFormat, label, expected, actual) return true } return false } func Co...
// Copyright 2020 Paul Greenberg greenpau@outlook.com // // 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 applica...
package mysqldb import "context" // Datastore 定义数据访问接口 type Datastore interface { // FindUserIDByToken 根据 token 返回 userID,如果token失效返回 error FindUserIDByToken(ctx context.Context, token string) (int32, error) // CreateSubscription 创建订阅 CreateSubscription(ctx context.Context, subscription *Subscription) (*Subscript...
package main import ( "github.com/MakeFang/GoUtility/interactor" "github.com/MakeFang/GoUtility/slackrtm" "github.com/MakeFang/GoUtility/sqldb" _ "github.com/joho/godotenv/autoload" "os" ) func main() { db := sqldb.SetupDB() interactor.SetDB(db) defer db.Close() botToken := os.Getenv("BOT_OAUTH_ACCESS_TOKE...
package main import "fmt" func main() { fmt.Println("vim-go") var head *ListNode list := []int{1, 2, 3, 4, 5} for i, _ := range list { push(&head, list[len(list)-1-i]) } display(head) node := reverseKGroup(head, 3) display(node) } type ListNode struct { Val int Next *ListNode } func length(head *List...
package main import ( "fmt" "sync" "testing" "time" ) func TestPool(t *testing.T) { pool := sync.Pool{ New: func() interface{} { return "Default" }, } pool.Put("Zakir") pool.Put("Azzah") pool.Put("Weebs") for i := 0; i < 10; i++ { go func() { data := pool.Get() fmt.Println(data) time.Sle...
package main import ( "crypto/tls" "flag" "fmt" "io/ioutil" "log" "math" "net" "net/http" "runtime" "sort" "strconv" "sync" "time" "github.com/arangodb/go-driver/v2/arangodb" "github.com/arangodb/go-driver/v2/connection" "golang.org/x/net/http2" ) // Book is the basic data structure used for tests ty...
package main import "fmt" func main() { fmt.Println(pivotIndex([]int{ 1, 7, 3, 6, 5, 6, })) fmt.Println(pivotIndex([]int{ 1, 2, 3, })) fmt.Println(pivotIndex([]int{ 2, 1, -1, })) } func pivotIndex(nums []int) int { ln := len(nums) leftSum := make([]int, ln) rightSum := make([]int, ln) for i := 0;...
package web import ( "accountBook/application/web/controllers" "accountBook/models/beans/dbBeans" "accountBook/models/endpoints/web" "encoding/json" ) // 收支类型相关接口 type ReceiptTypeController struct { controllers.RestController Serv web.IReceiptTypeEndpoint } // @Title 收支类型列表 // @Description 收支类型列表 // @Param tok...
package api import ( "encoding/json" "fmt" "net/http" "sort" "internal/ctxutil" "github.com/garyburd/redigo/redis" ) const ( prefixClassATC = "class:atc" prefixClassNFC = "class:nfc" prefixClassFSC = "class:fsc" prefixClassBFC = "class:bfc" prefixClassCFC = "class:cfc" prefixClassMPC = "class:mpc" pref...
package common import ( "errors" ) type SqQueue struct { data []interface{} size int front int tail int } func NewQueue(size int) *SqQueue { return &SqQueue{ data: make([]interface{}, size), size: size, front: 0, tail: 0, } } //长度 func (q *SqQueue) QueueLength() int { return (q.tail - q.front ...
package systemd import ( "fmt" "os/exec" "path" "strings" "github.com/miekg/vks/pkg/unit" corev1 "k8s.io/api/core/v1" ) // commandAndArgs returns an updated ExecStart strings slice taking the pod's Command and Args // into account. func commandAndArgs(uf *unit.File, c corev1.Container) []string { // If comman...
package main import "fmt" type walker interface { walk(miles int) } type camel struct{ Name string } func (c camel) walk(miles int) { fmt.Println(c.Name, "is walking ", miles) } func longWalk(w walker) { w.walk(500) w.walk(500) } func main() { c:=camel{"Bill"} longWalk(c) }
package davepdf import ( "fmt" ) type ShadingType = int const ( ShadingType3 ShadingType = 3 ) type PdfShading struct { id int Type ShadingType Coords []float64 Function *PdfFunction Extend []bool } func (pdf *Pdf) NewShading() *PdfShading { shading := &PdfShading{} pdf.newObjId() shading....
// https://github.com/tjgq/broadcast/blob/master/broadcast.go package broadcast import ( "sync" logging "github.com/ipfs/go-log" ) var log = logging.Logger("tex-broadcast") // Broadcaster implements a broadcast channel. // The zero value is a usable unbuffered channel. type Broadcaster struct { m sync.Mu...