text
stringlengths
11
4.05M
/* * Copyright 2017 - 2019 KB Kontrakt LLC - 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 require...
package main import ( "context" "log" "os" "time" api "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/util/wait" corev1 "k8s.io/client-go/kubernetes/typed/core/v1" "k8s.io/client-go/rest" "k8s.io/client-go/tools/cache" ...
package main import ( "context" "encoding/base64" "errors" "fmt" "net/http" "strings" ) func defaultAuth(r *http.Request) error { if accessKey == "" { return errors.New("no default login credentials set") } if r.Header.Get("X-Access") == accessKey { return nil } if r.URL.Query().Get("access-key") == ac...
package backend import ( "flag" "fmt" "net/http" "os" "os/signal" "syscall" "testing" "github.com/DexterLB/mvm/imdb/jsonapi" "github.com/bitterfly/kuho/spiderdata" ) var dbURN string func init() { var ( dbName string dbUser string ) flag.StringVar(&dbName, "db.name", "", "name of database to connec...
package modules import ( "errors" "os/exec" "path/filepath" "regexp" "strings" "github.com/wx13/genesis" ) type Dpkg struct { Path string Name string Force bool Absent bool } func (dpkg Dpkg) path() string { if dpkg.Path == "" { return "" } match, _ := regexp.MatchString("^[.]?/", dpkg.Path) if...
// Copyright 2018 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 leetcode func findMin(nums []int) int { min := nums[0] for i := 1; i < len(nums); i++ { if min > nums[i] { min = nums[i] } } return min }
package server import ( "log" "net" "github.com/VanBur/tcp-chat/internal/room" ) type Server struct { listener net.Listener room *room.Room stopServe bool } func New(network, address string) (*Server, error) { listener, err := net.Listen(network, address) if err != nil { return nil, err } return ...
package main import "testing" func TestWeightedQuickUnionNew(t *testing.T) { for _, tc := range []struct { name string n int err error ids []int }{ { name: "empty", err: ErrNotPositiveN, }, { name: "n is negative number", n: -1, err: ErrNotPositiveN, }, { name: "n is po...
// Package event implements python's threading.Event api using golang primitives. package event import ( "context" ) // Event is a communication primitive allowing for multiple goroutines to wait // on an event to be set. type Event struct { next chan chan struct{} } // New creates a new event instance. func New()...
// Copyright © 2019 mg // // 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 // to use, copy, modify, merge, publish, distribute, ...
package controller import ( // "sixedu/service" "fmt" ) type UserController struct { } func (u *UserController) List() { //展示用户信息 view = "index_view" users := userService.GetList() fmt.Println("| username | passsword | age | sex |") //fmt.Println(users) for _,v := range users { ...
package token_filter import ( "bytes" "search-engine/chapter6/analysis" "unicode/utf8" ) type NgramFilter struct { minLength int maxLength int } func NewNgramFilter(minLength, maxLength int) analysis.TokenFilter { return &NgramFilter{ minLength: minLength, maxLength: maxLength, } } func (s *NgramFilter) ...
package main import ( "bytes" "fmt" "io" "os" ) func stdoutWrite() { proverbs := []string{ "Channels orchestrate mutexes serialize\n", "Cgo is not Go\n", "Errors are values\n", "Don't panic\n", } for _, p := range proverbs { n, err := os.Stdout.Write([]byte(p)) if err != nil { fmt.Println(err) ...
package files import ( "io" "mime/multipart" "strings" "testing" ) func TestSliceFiles(t *testing.T) { sf := NewMapDirectory(map[string]Node{ "1": NewBytesFile([]byte("Some text!\n")), "2": NewBytesFile([]byte("beep")), "3": NewBytesFile([]byte("boop")), }) buf := make([]byte, 20) it := sf.Entries() ...
package data import ( "testing" ) func TestIsEmpty(t *testing.T) { s := NewCellsSet() if !s.IsEmpty() { t.Error("It must be empty") } c := NewCell(0, 0) s.Add(c) if s.IsEmpty() { t.Error("It must not be empty") } s.Remove(c) if !s.IsEmpty() { t.Error("It must be empty") } } func TestAdd(t *testing...
package main import ( "fmt" "log" "time" "github.com/syndtr/goleveldb/leveldb" ) // Subscription contains information about subreddit users type Subscription struct { Subreddit *Subreddit Name string Chats []int LastID string LastUpdate int64 exit chan bool DB *leveldb.DB } ...
package datahandler import ( "encoding/csv" "log" "os" ) //Open `UsersFile` and look for first row (account) with given `email` or `token` //If account was found return that and true //In other case return empty user and false func FindByEmailOrToken(email, token string) (User, bool) { usersDb, err := os.OpenFile...
package regexample import ( "fmt" "regexp" ) func Class() { execute(`[\w]+ <[a-z]+[0-9a-zа-я]+@[a-z]+\.[a-z]{2,}>`, `ars <arespuma@mail.ru>`) } func execute(pattern string, s string) { match, err := regexp.MatchString(pattern, s) if err != nil { panic(err) } fmt.Println(match) }
package dict type ErrorWrapper struct { *BaseException cause error } func NewWrapper(cause error, format string, args ...interface{}) *ErrorWrapper { return &ErrorWrapper{ BaseException: newBaseException(3, format, args...), cause: cause, } } func (self *ErrorWrapper) Cause() error { return self.cau...
package services import ( "crypto/sha256" "encoding/base64" ) type PasswordService struct{ } func NewPasswordService() *PasswordService{ return &PasswordService{} } func (service *PasswordService) EncodePassword (password string) string { sha := sha256.New() sha.Write([]byte(password)) hash := base64.URLEnco...
package base import ( "time" ) // Add a new point to a GTS func (dps *Datapoints) Add(ts time.Time, value interface{}) *Datapoints{ if dps == nil { dps = &Datapoints{} } *dps = append(*dps, []interface{}{ ts.UnixNano() / 1000, value, }) return dps } // AddWithGeo a new point to a GTS with geolocation f...
package main import ( "testing" ) func TestTwoSum(t *testing.T) { args := []int{0, 1, -1, 10, -10, 2147483647, -2147483648} rets := []int{0, 1, -1, 1, -1, 0, 0} for index, arg := range args { if rets[index] != reverse(arg) { t.Errorf("TestTwoSum fail.arg:%d\tret:%d\texpect:%d\n", arg, reverse(arg), rets[inde...
package main type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // 翻转二叉树 (先序) func invertTree(root *TreeNode) *TreeNode { if root == nil { return root } root.Left, root.Right = root.Right, root.Left invertTree(root.Left) invertTree(root.Right) return root } // 翻转二叉树 (中序) func invertTree(ro...
package main func main(){} type ListNode struct { Val int Next *ListNode } func reversePrint(head *ListNode) []int { res := []int{} for head != nil { res = append(res, head.Val) head = head.Next } l := len(res)-1 for i := 0; i < l - i;i++ { temp := res[i] res[i] = res[l-i] res[l-i] = temp } ret...
package websocket import ( "database/sql" "encoding/json" _ "github.com/go-sql-driver/mysql" log "github.com/sirupsen/logrus" "strconv" "strings" "time" ) type Pool struct { Register chan *Client Unregister chan *Client Clients map[*Client]bool Send chan Message } func NewPool() *Pool { return...
package db import ( "encoding/json" "strconv" "time" "github.com/steam-authority/steam-authority/helpers" "github.com/steam-authority/steam-authority/memcache" ) type Tag struct { ID int `gorm:"not null;primary_key;AUTO_INCREMENT"` CreatedAt *time.Time `gorm:"not null"` UpdatedAt *time.Time `go...
package resources import ( "errors" "net/http" "github.com/manyminds/api2go" "gopkg.in/mgo.v2/bson" "themis/utils" "themis/models" "themis/database" ) // WorkItemResource for api2go routes. type WorkItemResource struct { WorkItemStorage *database.WorkItemStorage } func (c WorkItemResource) getFilterFromReq...
package urlutil import ( "fmt" "net/url" "strconv" "testing" "time" "github.com/stretchr/testify/assert" ) func TestBuildTimeParameters(t *testing.T) { t.Parallel() params := make(url.Values) BuildTimeParameters(params, time.Minute) assert.True(t, params.Has(QueryIssued)) assert.True(t, params.Has(QueryE...
// Copyright (C) 2020 Cisco Systems 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 agr...
package metadata var BannerBase64 = "DQogIF9fXyAgIF9fICBfX19fICBfX19fICAgX18gIF8gIF8gIF8gIF8gDQogLyBfXykgLyAgXCggIF8gXCggIF8gXCAvICBcKCBcLyApKCBcLyApDQooIChfIFwoICBPICkpIF9fLyApICAgLyggIE8gKSkgICggICkgIC8gDQogXF9fXy8gXF9fLyhfXykgIChfX1xfKSBcX18vKF8vXF8pKF9fLyAgDQo=" var VersionTpl = `%s Name: goproxy Version: %s Build...
package main import ( "database/sql" "fmt" "log" _ "github.com/denisenkom/go-mssqldb" ) func main() { condb, errdb := sql.Open("mssql", "server=xxxxxxxxx;user id=xxxxx;password=xxxx;database=xxxx;") if errdb != nil { fmt.Println(" Error open db:", errdb.Error()) } var ( id int FirstName s...
package main import ( "encoding/json" "fmt" "net" "os" ) type Info struct { Id string Host string } type trade struct { From string To string Quantity int Sort string } type clidata struct { Host string First int Second int } type message struct { Kind ...
package appraisal import ( "time" "fareastdominions.com/evepaste/eve/entity" "golang.org/x/net/context" "github.com/aplulu/buyback/models/itemprice" "encoding/json" "fareastdominions.com/evepaste/utils" "github.com/mjibson/goon" "google.golang.org/appengine/log" ) type Appraisal struct { Id int...
package key import ( "github.com/BoutiqaatREPO/nitrous/common" "github.com/gin-gonic/gin" "github.com/sanksons/tavern" "github.com/sanksons/tavern/common/entity" ) func DeleteKeyHandler(context *gin.Context, adapter tavern.CacheAdapter) { name := context.Param("name") _, err := adapter.Destroy(entity.CacheKey{...
package actor import ( "testing" "time" "github.com/stretchr/testify/assert" ) func TestFuture_PipeTo_Message(t *testing.T) { a1, p1 := spawnMockProcess("a1") a2, p2 := spawnMockProcess("a2") a3, p3 := spawnMockProcess("a3") defer func() { removeMockProcess(a1) removeMockProcess(a2) removeMockProcess(a3...
package params import ( "fmt" sdk "github.com/irisnet/irishub/types" abci "github.com/tendermint/tendermint/abci/types" ) // query endpoints supported by the params Querier const ( QueryModule = "module" ) // creates a querier for params REST endpoints func NewQuerier(keeper Keeper) sdk.Querier { return func(c...
package api import ( "dingtalk/model" "encoding/json" "errors" "fmt" "net/url" ) // DingExtContact dingding extcontact type DingExtContact struct { Tocken string `json:"tocken" yaml:"tocken"` // 应用访问tocken BaseURL string `json:"base_url" yaml:"base_url"` // 接口地址:https://oapi.dingtalk.com } // NewDingExtC...
package migrations import ( "database/sql" "io/ioutil" "os" "path" "testing" ) func initAt010(db *sql.DB, pin string) error { var sqlStmt string if pin != "" { sqlStmt = "PRAGMA key = '" + pin + "';" } sqlStmt += ` create table contacts (id text primary key not null, address text not null, username tex...
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scan import ( "fmt" "strings" "testing" "unicode" ) // We first implement a lexer for a simple language. The tests proper are at the end of the fi...
package scraper import ( "github.com/znconrad5/fantasyfootball" "testing" ) func TestNflUrlGenerator(t *testing.T) { generator := &nflUrlGenerator{ positions: []fantasyfootball.Position{fantasyfootball.QB}, season: 2012, startWeek: 1, endWeek: 31, } urls := generator.generateUrls() _, ok := urls["h...
package services import ( "strings" "github.com/anfelo/bookstore_oauth-api/src/domain/accesstoken" "github.com/anfelo/bookstore_oauth-api/src/domain/users" "github.com/anfelo/bookstore_utils/errors" ) // Repository access token repository interface type Repository interface { GetByID(string) (*accesstoken.Acces...
package handlers import ( "aws-lambda-api/pkg/update" "net/http" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" ) func GetUpdate(req events.APIGatewayProxyRequest, tableName string, dynaClient dynamodbiface.DynamoDBAPI) ( *events...
package easypost import ( "context" "net/http" ) type Refund struct { ID string `json:"id,omitempty"` Object string `json:"object,omitempty"` CreatedAt *DateTime `json:"created_at,omitempty"` UpdatedAt *DateTime `json:"updated_at,omitempty"` TrackingCode ...
package chargeback import ( "fmt" "strings" "time" log "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/runtime" cbTypes "github.com/operator-framework/operator-metering/pkg/apis/chargeback/v1alpha1" "github.com/operator-framework/operator-metering/pkg/presto" ) func (c *Chargeback) generateReport(logge...
package model import ( "Seaman/utils" "time" ) type TplWfHiFormT struct { Id string `xorm:"not null pk VARCHAR(64)"` ProcInstId string `xorm:"not null comment('流程实例ID') unique VARCHAR(64)"` BusinessKey string `xorm:"not null comment('业务ID') VARCHAR(64)"` ProcDefId string...
// Copyright 2023 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 in wr...
/* Alice, Bob and Charlie are playing a new game called Buddy NIM. The game is played at two tables; on the first table, there are N heaps containing A1,A2,…,AN stones and on the second table, there are M heaps containing B1,B2,…,BM stones respectively. Initially, Alice is playing at the first table and Bob is playin...
package lcd import ( "fmt" "github.com/irisnet/irishub/app/v1/asset" "github.com/irisnet/irishub/app/v1/bank" "github.com/irisnet/irishub/app/v1/stake" "net/http" "strings" "github.com/gorilla/mux" "github.com/irisnet/irishub/app/protocol" "github.com/irisnet/irishub/app/v1/auth" "github.com/irisnet/irishub...
package main import ( "context" "log" "time" "fmt" "io" "os" "strconv" "encoding/csv" // Llamamos el paquete de gRPC "google.golang.org/grpc" // Llamamos el compilado que nos generó protoc pb "./logistica" ) const ( address = "localhost:50053" // Definimos por que host y puerto nos comunicamos ) typ...
package nats_streaming import ( "context" "errors" "io/ioutil" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/sirupsen/logrus" "github.com/batchcorp/collector-schemas/build/go/protos/events" "github.com/batchcorp/plumber-schemas/build/go/protos/args" "github.com/batchcorp/plumber-...
package ircserver import "gopkg.in/sorcix/irc.v2" func init() { Commands["server_SVSNICK"] = &ircCommand{ Func: (*IRCServer).cmdServerSvsnick, MinParams: 2, } } func (i *IRCServer) cmdServerSvsnick(s *Session, reply *Replyctx, msg *irc.Message) { // e.g. “SVSNICK blArgh Guest30503 :1425036445” if !IsVal...
package main import ( "encoding/json" "flag" "fmt" "os" "github.com/grafana/plugin-validator/pkg/grafana" "github.com/grafana/plugin-validator/pkg/plugin" ) func main() { var ( pluginURLFlag = flag.String("url", "", "URL to the plugin") schemaPathFlag = flag.String("schema", "./config/plugin.schema.json"...
package main import ( ibclient "github.com/infobloxopen/infoblox-go-client" "log" ) func main() { config := LoadConfig() conn, err := ibclient.NewConnector( config.GridHost, config.WapiVer, config.WapiPort, config.WapiUsername, config.WapiPassword, config.SslVerify, config.HttpRequestTimeout, con...
package stringutil func deduplicateList(list []string, makeIfEmpty bool) ( []string, map[string]struct{}) { if len(list) < 1 && !makeIfEmpty { return list, nil } copiedEntries := make(map[string]struct{}, len(list)) outputList := make([]string, 0, len(list)) for _, entry := range list { if _, ok := copiedEnt...
package view import "net/http" type PaymentData struct { } type PSuccessData struct { } type PDenyData struct { } //Payment renders payment view func Payment(w http.ResponseWriter, r *http.Request, data PaymentData) { render(w, r, payment, data) } //Success renders pSuccess view func Success(w http.ResponseWrite...
/* Create a gather function that accepts a string argument and returns another function. The function calls should support continued chaining until order is called. order should accept a number as an argument and return another function. The function calls should support continued chaining until get is called. get s...
package letter import ( "encoding/json" "logicdata/entity" "pb/c2s" "server" "server/libs/log" "server/libs/rpc" "server/share" "time" ) type Appendix struct { Configid string UID uint64 Amount int16 RemainTime int32 } const ( ERR_MAILBOX_FULL = share.ERROR_LETTER + iota ERR_APPENDIX_NOT_E...
package main import "fmt" func main() { //fmt.Println(minReorder(6, [][]int{ // {0, 2}, {0, 3}, {4, 1}, {4, 5}, {5, 0}, //})) // //fmt.Println(minReorder(5, [][]int{ // {4, 3}, // {2, 3}, // {1, 2}, // {1, 0}, //})) fmt.Println(minReorder(6, [][]int{ {0, 1}, {1, 3}, {2, 3}, {4, 0}, {4, 5}, }))...
package uinput import ( "testing" ) func TestTouchPadCreation(t *testing.T) { touchPad, err := CreateTouchPad(0, 1079, 0, 719) if err != nil { t.Fatal("Failed to create virtual touchpad") } err = touchPad.Close() if err != nil { t.Fatal("Failed to close virtual touchpad device") } } func TestVirtualTouch...
// Copyright 2019 Google 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...
package collector import ( "bytes" "io/ioutil" "encoding/xml" "github.com/prometheus/common/log" "github.com/prometheus/client_golang/prometheus" ) const ( // Subsystem(s). volume = "volume" ) var ( up = prometheus.NewDesc( prometheus.BuildFQName(namespace, volume, "up"), "Was the last query of Gluster ...
package easyscripts type Variable interface { Name() string Value() string } func NewVariable(name, value string) Variable { return &variable{name: name, value: value} } type variable struct { name string value string } func (v *variable) Name() string { return v.name } func (v *variable) Value() string { r...
package signal import ( "os" "os/signal" ) // Notify redirect os/signal.Notify func Notify(c chan<- os.Signal, sig ...os.Signal) { signal.Notify(c, sig...) }
package 组合 import "sort" var combinations [][]int func combinationSum2(candidates []int, target int) [][]int { combinations = make([][]int, 0) sort.Ints(candidates) formCombinations(candidates, []int{}, 0, target) return combinations } func formCombinations(sortedArray []int, nowCombinations []int, nowSum int, ...
package login import ( "fmt" "net/http" ) //INGRESO acceso al sistema func INGRESO(w http.ResponseWriter, r *http.Request) { resp := "metodo de conexion no permitida" //respuesta servidor por defecto if r.Method == http.MethodPost { usr, _ := r.URL.Query()["usr"] //user pwd, _ := r.URL.Query()["pwd"] //passw...
package game_map import ( "fmt" "github.com/faiface/pixel" "github.com/faiface/pixel/pixelgl" "github.com/faiface/pixel/text" "github.com/steelx/go-rpg-cgm/combat" "github.com/steelx/go-rpg-cgm/gui" "github.com/steelx/go-rpg-cgm/world" "math" "reflect" ) type LootSummaryState struct { win *pixelgl.Wi...
package accmanager import( "stockdb" "stockdb/accountdb" "dbcreator/accgenerator" //"parser" "excel/account" //"handler/acchandler" "download/accdownload" acc "entity/accountentity" //"entity/dbentity" "util" //"time" "fmt" ) const( Balance = "balancesheet" Inco...
package protobuf type ClientMessage interface { } type CSRequest struct { ClientID string MessageProtocolNum int Message ClientMessage } func (h CSRequest) GetProtocolNum()int{ return RequestNum } type CSResponse struct { ClientID string MessageProtocolNum int Message ClientMessage } func (h CSR...
package shell import ( "fmt" "net/http" "strings" ) type post int func (post) name() string { return "post" } func (post) description() string { return "perform an HTTP post" } func (p post) usage() string { return fmt.Sprintf("%s <url>", p.name()) } func (post) run(env *env, args []string) error { url, er...
/* --- Day 3: Squares With Three Sides --- Now that you can think clearly, you move deeper into the labyrinth of hallways and office furniture that makes up this part of Easter Bunny HQ. This must be a graphic design department; the walls are covered in specifications for triangles. Or are they? The design document ...
package responses import "time" type Team struct { ID uint CreatedAt time.Time UpdatedAt time.Time Name string Description string }
package cli import ( "reflect" "strings" "testing" ) func Test_getCommandLineSettings(t *testing.T) { tests := []struct { name string argsString string wantSettings CommandLineSettings wantErr bool }{ {"1 path, no Recursive flag", "-p /usr/mgr", CommandLineSettings{FolderPaths: []string{...
package main import ( "fmt" "math/rand" "sort" "time" ) type Hero struct { Name string Age int } //HeroSlice数据类型实现https://studygolang.com/pkgdoc的sort包的type Interface interface {}接口 type HeroSlice []Hero //切片的长度 func (hs HeroSlice) Len() int { return len(hs) } //使用什么标准排序,按年龄从小到大排序 func (hs HeroSlice) Less(i...
package main import ( "flag" "fmt" tw "github.com/olekukonko/tablewriter" "io/ioutil" "os" "path/filepath" "runtime" "strconv" "strings" ) const ( BANNER = ` ___ ___ ___ /\__\ /\ \ /\__\ /:/ / ___ \:\ \ /:/ _/_ ...
package main import "net/http" import "fmt" import "io/ioutil" import "net/url" /* Go语言内置的net/http包十分优秀,提供了HTTP客户端和服务端的实现 */ func main() { //一个简单的发送http请求的client端 resp, err := http.Get("http://www.liwenzhou.com/") if err != nil { fmt.Println("get request error,error:", err) return } defer resp.Body.Clo...
package main import ( "github.com/google/wire" "learn/04_goProject/homework/internal/config" "learn/04_goProject/homework/internal/db" ) func InitApp() (*App, error) { panic(wire.Build(config.Provider, db.Provider, NewApp)) // 调用wire.Build方法传入所有的依赖对象以及构建最终对象的函数得到目标对象 }
package service import ( "context" "errors" "github.com/micro/go-micro" "io/ioutil" "log" "moriaty.com/cia/cia-common/base/constant" supporter "moriaty.com/cia/cia-common/proto/supporter/executor" "moriaty.com/cia/cia-executor/bean" "moriaty.com/cia/cia-executor/config" "moriaty.com/cia/cia-executor/handle" ...
// Package band provides band specific defaults and configuration. package band import ( "errors" "fmt" "time" ) // Name defines the band-name type. type Name string // Modulation defines the modulation type. type Modulation string // Possible modulation types. const ( LoRaModulation Modulation = "LORA" FSKMod...
package main import ( "flag" "fmt" ) var fval = flag.Int("val", 100, "Val") func findSmallerOrEqualsRecr(ar []int, maxv, left, right int) int { if left > right { return -1 } pos := (left + right) / 2 val := ar[pos] if val > maxv { return findSmallerOrEqualsRecr(ar, maxv, left, pos-1) } if val == maxv ...
package io import ( "io/ioutil" "os" "github.com/sirupsen/logrus" ) // Logger is the pointer to the already configured logrus logger instance var Logger *logrus.Logger // nolint: gochecknoglobals // InitLogger initializes a new instance of logrus.Logger for later consumption func init() { Logger = logrus.New() ...
package core import ( "github.com/textileio/go-textile/pb" ) func (t *Textile) announce(block *pb.Block, opts feedItemOpts) (*pb.Announce, error) { if block.Type != pb.Block_ANNOUNCE { return nil, ErrBlockWrongType } return &pb.Announce{ Block: block.Id, Date: block.Date, User: t.PeerUser(block.Author)...
package providers import ( "testing" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) func TestEndpointProviders(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "EndpointProviders Test Suite") }
package transactions import ( "encoding/json" "net/http" "github.com/garyburd/redigo/redis" "github.com/felipeguilhermefs/restis/router" ) func DiscardRoute(conn redis.Conn) router.Route { return router.Route{ "/discard", "POST", DiscardHandler(conn), } } func DiscardHandler(conn redis.Conn...
package api import ( "encoding/json" "io" "net/http" "strings" "github.com/azzzak/fakecast/fs" "github.com/azzzak/fakecast/store" "github.com/go-chi/chi" ) type cover struct { Cover string `json:"cover"` } func setCoverURL(cfg *Cfg, c *store.Channel) { if c.Cover != "" { c.Cover = strings.Join([]string{c...
package main import ( "time" "github.com/tenntenn/greeting/v2" ) func main() { println(greeting.Do(time.Now())) }
package timeutil import "fmt" import "time" func FormatConciseDate(t time.Time) string { return fmt.Sprintf("%d%02d%02d", t.Year(), t.Month(), t.Day()) }
package main import "log" type Request struct { RequestType string RequestContent string Number int } type Manager interface{ SetNext(next Manager) RequestHandler(request Request) } type CommonManager struct { Manager Name string } func (cm *CommonManager)SetNext(next Manager){ cm.Manager = next } func (c...
package alertmanager import ( "context" "github.com/prometheus/alertmanager/api/v2/client/general" "github.com/prometheus/alertmanager/api/v2/models" ) func (c Client) Status(ctx context.Context) (*models.AlertmanagerStatus, error) { status, err := c.alertmanager.General.GetStatus(general.NewGetStatusParams().Wi...
package problem0437 func pathSumII(root *TreeNode, sum int) int { preSums := make(map[int]int) preSums[0] = 1 return dfs(root, sum, 0, preSums) } func dfs(root *TreeNode, sum, curSum int, preSums map[int]int) int { if root == nil { return 0 } curSum += root.Val // 如果curSum-sum存在说明存在路径可达 total := preSums[cur...
package hh import ( "fmt" "io" "log" "os" "sync" "time" "github.com/messagedb/messagedb/db" ) var ErrHintedHandoffDisabled = fmt.Errorf("hinted handoff disabled") type Service struct { mu sync.RWMutex wg sync.WaitGroup closing chan struct{} Logger *log.Logger cfg Config ShardWriter shard...
package main import ( "flag" "fmt" "io/ioutil" "os" "github.com/jlaffaye/ftp" "bytes" "log" ) var connection *ftp.ServerConn var ftpURL = "students.yss.su:21" var login = "*****" var password = "****" var ftpPath = "./" // path on ftp server func MakeDir(path string) { connection.MakeDir(path) } func Up...
package handler import ( "bytes" "encoding/json" "net/http" "net/http/httptest" "testing" "github.com/golang/mock/gomock" "github.com/gorilla/mux" "github.com/markus-azer/products-service/pkg/entity" "github.com/markus-azer/products-service/pkg/product" "github.com/stretchr/testify/assert" ) // func TestRo...
package leetcode import "testing" func TestSurfaceArea(t *testing.T) { if surfaceArea([][]int{[]int{2}}) != 10 { t.Fatal() } if surfaceArea([][]int{ []int{1, 2}, []int{3, 4}, }) != 34 { t.Fatal() } if surfaceArea([][]int{ []int{1, 0}, []int{0, 2}, }) != 16 { t.Fatal() } if surfaceArea([][]in...
package stateless import ( aliceapi "github.com/yandex-cloud/examples/serverless/alice-shareable-todolist/app/alice/api" "github.com/yandex-cloud/examples/serverless/alice-shareable-todolist/app/model" ) func selectList(text *aliceText, options []*model.ACLEntry) *aliceapi.Resp { var buttons []*aliceapi.Button fo...
package idonia import ( "encoding/base64" "fmt" "github.com/dgrijalva/jwt-go" "io" "net/http" "net/url" "strings" "time" ) var ApiKey string var ApiSecret string var UserAgent = "Idonia Connect" var APIHost string var AccountID uint32 var Token string var httpClient *http.Client type ErrorResponse struct { ...
package controller import ( "net/http" "path/filepath" "github.com/gin-gonic/gin" "github.com/google/uuid" "github.com/YusukeKishino/go-blog/client" ) type AdminImagesController struct { s3Client client.S3Client } func NewAdminImagesController(s3Client client.S3Client) *AdminImagesController { return &Admin...
package main import ( "fmt" "github.com/BurntSushi/toml" ) //Config 订制配置文件解析载体 type Config struct { Database *Database SQL *SQL } //Database 订制Database块 type Database struct { Driver string Username string `toml:"us"` //表示该属性对应toml里的us Password string } //SQL 订制SQL语句结构 type SQL struct { SQL1 string `...
package controllers import ( "chatAppServer/models" "encoding/json" ) /*FriendsController 好友控制器 */ type FriendsController struct { MainController } /*SearchFriendsResult 返回结果 */ type SearchFriendsResult struct { Status int `json:"status"` Msg string `json:"msg"` Data []models....
package main import ( "fmt" ) //close :主要用于关闭channel , len: 用于求长度,比如string、array、slice、map、channel //new:主要用于分配值类型的内存,如 int、struct返回类型是指针 //make:用于分配内存,主要用于分配引用类型,例如chan、map、slice //append:用于追加元素到数组、slice中 //panic和recover:用于错误处理 panic可以在任何地方引起,但是recover只有再defer调用函数中有效,defer一定要再可能引发panic的语句前定义 func funca(){ f...