text stringlengths 11 4.05M |
|---|
package main
import (
"fmt"
"github.com/lingdor/midlog"
"github.com/lingdor/midlog-examples/library2"
"os"
)
var Logger = midlog.New("routeLog")
func main() {
//config log writer
midlog.SetWriter(&MyWriter{})
library2.DumpLog("library2 log")
library2.DumpError("library2 error log")
Logger.Info("hello worl... |
package isogram
import (
"unicode"
)
//IsIsogram - determines whether or not 'word' is an isogram
func IsIsogram(word string) bool {
isogram := true
var values = map[rune]rune{}
for _, runeValue := range word {
runeValue = unicode.ToUpper(runeValue)
if runeValue == 45 || runeValue == 32 {
continue //skip ... |
package main
import "github.com/robertsmieja-templates/golang-cli-template/cmd"
func main() {
cmd.Execute()
}
|
package utils
import "time"
//待优化
type SimpleCache struct {
cache map[string]*element
globalExpire int64
}
func CreateSimpleCache() SimpleCache {
return CreateSimpleCacheExpire(defaultExpire)
}
func CreateSimpleCacheExpire(globalExpire int64) SimpleCache {
return SimpleCache{
cache:make(map[string]*element),
... |
package main
import (
"fmt"
"io/ioutil"
"os"
"regexp"
)
func main() {
// var filePath string
for _, file := range os.Args[1:] {
fileInfos, err := ioutil.ReadDir(file)
fmt.Println(err)
for _, info := range fileInfos {
name := info.Name()
r1 := regexp.MustCompile(".js")
r2 := regexp.MustCompile... |
package main
import (
"fmt"
"github.com/Densuke-fitness/Practice4forGoCi/fizzbuzz"
)
func main() {
fmt.Println(fizzbuzz.Convert(15))
} |
package core
/*
** Defined Transfer Syntax UIDs
*/
var (
// UIDLittleEndianImplicitTransferSyntax : Implicit VR Little Endian: Default Transfer Syntax for DICOM
UIDLittleEndianImplicitTransferSyntax = "1.2.840.10008.1.2"
// UIDLittleEndianExplicitTransferSyntax : Explicit VR Little Endian
UIDLittleEndianExplicit... |
package hello
import (
"fmt"
"time"
)
var SupportedLangs = map[string]string{
"en-US": "Hello, World!",
"ru-RU": "Здравствуй, Мир!",
"zh-CN": "你好,世界!",
"fr-FR": "Bonjour le Monde!",
}
func World() error {
return WorldIn("en-US")
}
func WorldIn(lang string) error {
if greeting, found := SupportedLangs[lang];... |
package model
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestConvBoolToBytes(t *testing.T) {
restrue := ConvBoolToBytes(true)
resfalse := ConvBoolToBytes(false)
assert.Len(t, restrue, 1)
assert.Len(t, resfalse, 1)
assert.Equal(t, byte(1), restrue[0])
assert.Equal(t, byte(0), resfalse[0])
... |
package main
import "fmt"
type Account struct {
Name string
Amount float64
}
func (a *Account) Add(amt float64) {
a.Amount = a.Amount + amt
}
func (a *Account) Withdraw(amt float64) bool {
if a.Amount < amt {
return false
}
a.Amount = a.Amount - amt
return true
}
func (a Account) Print() {
fmt.Printf("... |
package main
import (
"bytes"
"fmt"
"image"
"image/color"
"image/draw"
"image/jpeg"
"github.com/enjoy-web/ehttp"
"github.com/gin-gonic/gin"
)
type ErrorMessage struct {
Message string `json:"message" desc:"the error message"`
Details string `json:"detail" desc:"the error detail"`
}
var DocDownloadText = &... |
package main
import (
"ch9/formatter"
"ch9/math"
"fmt"
)
func main() {
num := math.Double(2)
output := formatter.Format(num)
fmt.Println(output)
}
|
package article
import (
"github.com/go-chi/chi"
"github.com/go-chi/render"
"github.com/hardstylez72/bblog/internal/api/controller"
ma "github.com/hardstylez72/bblog/internal/api/model/article"
"github.com/hardstylez72/bblog/internal/storage/user"
"net/http"
)
func (c articleController) GetArticleByIdHandler(w ... |
package main
import (
"fmt"
"github.com/jlarusso/gonads/interactors"
)
func main() {
p1 := make(map[string]int)
p1["tomatoes"] = 1
p1["heat"] = 100
p1["salt"] = 2
result1 := interactors.MakeSauce(p1)
fmt.Println(result1) // => Failure(Not enough tomatoes)
p2 := make(map[string]int)
p2["tomatoes"] = 10
p... |
package fitbit
import (
"context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/fitbit"
)
type AuthConfig struct {
ClientID string
ClientSecret string
RedirectURL string
}
func newConfig() *oauth2.Config {
return &oauth2.Config{
Endpoint: fitbit.Endpoint,
Scopes: []string{"activity", "location", "soc... |
package levigo
// #cgo LDFLAGS: -lleveldb
// #include "levigo.h"
import "C"
// CompressionOpt is a value for Options.SetCompression.
type CompressionOpt int
// Known compression arguments for Options.SetCompression.
const (
NoCompression = CompressionOpt(0)
SnappyCompression = CompressionOpt(1)
)
// Options r... |
package account
import (
"bytes"
"crypto/sha256"
"errors"
"time"
jwtLib "github.com/dgrijalva/jwt-go"
)
// RegisterAndSign - register the account to db, and sign the jwt for it
func (acct *AccountService) RegisterAndSign(name string, password string, isAdmin bool) (jwt string, err error) {
db := acct.DB
var ... |
package test
// ========== Unit tests for the init and run other tests ================
|
package oidc_test
import (
"context"
"io"
"net/http"
"net/http/httptest"
"net/url"
"regexp"
"testing"
"github.com/ory/fosite"
"github.com/ory/fosite/token/jwt"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/valyala/fasthttp"
"github.com/authelia/authelia/v4/intern... |
/*
Copyright 2021 CodeNotary, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... |
package charge
import "github.com/gucastiliao/special-case-pattern/pkg/model"
type CompleteCharge struct {
subscription model.Subscription
}
func NewCompleteCharge(subscription model.Subscription) CompleteCharge {
return CompleteCharge{
subscription: subscription,
}
}
func (c CompleteCharge) Execute() error {
... |
package persist_lib
func Testservice1UnaryExample1Query(tx Runable, req Testservice1UnaryExample1QueryParams) *Result {
row := tx.QueryRow(
"SELECT id AS 'table_key', id, value, msg as inner_message, status as inner_enum FROM test_table WHERE id = $1 ",
req.GetTableId(),
req.GetStartTime(),
)
return newResult... |
package urlshort
import "net/http"
func MapHandler(pathsToUrls map[string]string, fallback http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if url, ok := pathsToUrls[r.URL.Path]; ok {
http.Redirect(w, r, url, http.StatusMovedPermanently)
} else {
fallback.ServeHTTP(w, ... |
package binance
import (
"context"
bin "github.com/adshao/go-binance"
"github.com/google/uuid"
"github.com/mhereman/cryptotrader/logger"
"github.com/mhereman/cryptotrader/types"
)
// GetOrder executes the get order request
func (b Binance) GetOrder(ctx context.Context, order types.Order) (info types.OrderInfo, ... |
package handlers
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
"../kvstore"
)
var (
// Store is the shared KV Store
Store kvstore.Store
)
func init() {
Store = kvstore.Initialize()
}
// Route defines the Mux
// router individual route
type Route struct {
Path stri... |
package main
import (
"bufio"
"encoding/csv"
"fmt"
"os"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
// GradientCSVFilePath path to gradient stock grid csv
const GradientCSVFilePath = "./data/sp500_grid.csv"
// DBFilename SQLite Database filename
const DBFilename = "db/development.db"... |
package main
import (
"encoding/json"
"fmt"
"shuxiang/common/mq"
"github.com/streadway/amqp"
)
var Client mq.MessagingClient
// 初始化rabbitmq
func init() {
Client.Conn = Client.ConnectToRabbitmq("amqp://guest:guest@192.168.10.252:5672")
// fmt.Println("************")
}
func getBooking(delivery amqp.Delivery) ... |
package main
import "fmt"
func main() {
var numOfCases int
fmt.Scanf("%d", &numOfCases)
for i := 0; i < numOfCases; i++ {
var x int
fmt.Scanf("%d", &x)
result, calls := fib(x)
fmt.Printf("fib(%d) = %d calls = %d\n", x, calls, result)
}
}
// Gets the (n+1)th number and the number of recursive calls in ... |
package dto
type Exercise struct {
ExerciseId int `json:"exercise_id" db:"ExerciseId"`
Name string `json:"name" db:"Name"`
ExerciseTime int `json:"exercise_time" db:"ExerciseTime"`
}
|
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func isPalindrome(head *ListNode) bool {
if(head == nil){
return true
}
arr := make([]int, 0)
for head != nil{
arr = append(arr, head.Val)
head = head.Next
}
... |
package main
import (
"practice/studySort/bucketSort/dataStruct"
)
/**
桶排序
桶排序的动效 https://www.cs.usfca.edu/~galles/visualization/BucketSort.html
JavaScript的实现 http://bubkoo.com/2014/01/15/sort-algorithm/bucket-sort/
先预备好固定数量的桶,每个待排的数都通过一个函数计算得出对应的桶编号
每个桶中可以放多个数,以链表的数据结构进行存储
*/
const BucketNum = 10
// 入口... |
package mongo
import "go.mongodb.org/mongo-driver/bson/primitive"
// DBRef is a MongoDB DBRef type
type DBRef struct {
// A reference collection
Ref string `bson:"$ref"`
// A reference identifier
ID primitive.ObjectID `bson:"$id"`
}
|
package constant
const (
/****************************************** mongo ****************************************/
/****************************************** feedback ****************************************/
FeedbackUnReadStatus = 0
FeedbackReadedStatus = 1
/****************************************** redis... |
package hamming
import "fmt"
const testVersion = 5
func Distance(a, b string) (int, error) {
if len(a) != len(b) {
return -1, fmt.Errorf("String length %d, %d not equal", len(a), len(b))
} else {
var count int
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
count++
}
}
return count, nil
}
}
|
package typematch
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"go/types"
"strconv"
"strings"
)
type patternOp int
const (
opType patternOp = iota
opPointer
opVar
opSlice
opArray
opMap
)
type Pattern struct {
typeMatches map[string]types.Type
int64Matches map[string]int64
root *pattern
}
type p... |
package model
// camera 基础表字段
type Camera struct {
ID int `gorm:"primary_key:AUTO_INCREMENT;column:id;not null" json:"id"`
Camera_address string `gorm:"column:camera_address" json:"camera_address"`
Camera_status int `gorm:"column:camera_status" json:"camera_status"`
Camera_position string `gorm:"column:camera_p... |
package minnow
import (
"log"
"os"
"time"
)
type IngestDirInfo struct {
IngestPath Path
MinAge time.Duration
ProcessedBy []ProcessorId
RemoveOnceIngested bool
}
type DirectoryIngester struct {
workPath Path
ingestDirChan chan IngestDirInfo
dispatchChan chan DispatchInfo
lo... |
package ratecounter
import (
"testing"
"time"
)
func TestAvgRateCounter(t *testing.T) {
interval := 50 * time.Millisecond
r := NewAvgRateCounter(interval)
check := func(expectedRate float64, expectedHits int64) {
rate, hits := r.Rate(), r.Hits()
if rate != expectedRate {
t.Error("Expected rate ", rate, "... |
package bytesutil
import (
"bytes"
"compress/zlib"
"crypto/rand"
"fmt"
"io"
"math/big"
)
// Constants for byte sizes in decimal and binary formats
const (
KILO int64 = 1000 // 1000 power 1 (10 power 3)
KIBI int64 = 1024 // 1024 power 1 (2 power 10)
MEGA = KILO * KILO // 1000 power 2 (10 p... |
package main
import (
"log"
"ukor/cmd/ukor"
)
func main() {
if err := ukor.RootCommand().Execute(); err != nil {
log.Fatal(err)
}
}
|
package main
import (
"fmt"
"log"
"math/big"
"path/filepath"
"strings"
)
func GenerateProductOfNs(files []string) (*big.Int, error) {
product := big.NewInt(1)
for _, file := range files {
publicKey, err := ReadPublicKey(file)
if err != nil {
return nil, err
}
product.Mul(product, publicKey.N)
}
... |
package main
import (
"math"
)
/**
跳跃游戏 II
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
示例 1:
```
输入: [2, 3, 1, 1, 4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
```
说明:
假设你总是可以到达数组的最后一个位置。
*/
/**
循环到 len(nums) - 1, 最后一个元素不访问,因为到达最后一个元素之后,就不会再往... |
/*
Bytelandian Currency is made of coins with integers on them. There is a coin for each non-negative integer (including 0).
You have access to a peculiar money changing machine.
If you insert a N-valued coin, with N positive, It pays back 3 coins of the value N/2,N/3 and N/4, rounded down.
For example, if you insert ... |
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"text/template"
)
var tmp *template.Template
func init() {
tmp = template.Must(template.ParseFiles("index.gohtml"))
}
func main() {
var port string
var arg string
if len(os.Args) > 1 {
arg = os.Args[1]
}
if arg != "" {
p... |
package main
import "fmt"
import "strconv"
import "math/rand"
const minkeysize = 16
// Generate presorted load, always return unique key,
// return nil after `n` keys.
func Generateloads(klen, vlen, n int64) func(k, v []byte) ([]byte, []byte) {
var textint [1024]byte
keynum := int64(0)
return func(key, value []b... |
package domain
// Dealership holds dealership object
type Dealership struct {
Address
Name string
DealershipID string
GroundInventory map[string]*GroundTransportation
}
|
// Package clientserverpair provides a buffered, connected pair of dialers and
// listeners.
//
// This pair of objects differs from the net.Pipe implementation in that reads
// and writes are buffered and operations on them do not block, unless the
// respective internal buffer(s) is/are full.
package clientserverpair... |
package main
import (
"runtime"
"github.com/therecipe/qt/androidextras"
"github.com/therecipe/qt/core"
"github.com/therecipe/qt/qml"
)
var Application *application
type application struct {
core.QObject
_ func() `constructor:"init"`
_ func() `signal:"onPermissionsGranted"`
_ func() `sign... |
package main
import (
"fmt"
"github.com/joho/godotenv"
"log"
"os"
"github.com/sendgrid/sendgrid-go"
"github.com/sendgrid/sendgrid-go/helpers/mail"
)
func main() {
err := godotenv.Load(".env")
if err != nil {
log.Println(err)
}
from := mail.NewEmail("Example User", "soichi.sumi@gmail.com")
subject := "S... |
package sim
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"math/rand"
"os"
)
type SeedPod struct {
src *os.File
n int
offset int64
size int64
}
func NewSeedPod(src string, offset int64) (*SeedPod, error) {
f, err := os.Open(src)
if err != nil {
return nil, err
}
info, err := f.Stat()
if err != n... |
package server
import (
"io/fs"
"net/url"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/valyala/fasthttp"
"github.com/authelia/authelia/v4/internal/configuration/schema"
"github.com/authelia/authelia/v4/internal/mocks"
"github.com/authelia/authelia/v4... |
package e2e
import (
"context"
"fmt"
"path/filepath"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
operatorsv1 "github.com/operator-framework/api/... |
func isPowerOfThree(n int) bool {
return sol1(n)
}
func sol1(n int) bool {
if n < 1 {
return false
}
cur := n
for cur > 0 {
if cur % 3 != 0 && cur != 1 {
return false
}
cur = cur / 3
}
return true
}
|
package main
func main() {
}
func countBinarySubstrings(s string) int {
var ptr, last, ans int
n := len(s)
for ptr < n {
c := s[ptr]
count := 0
for ptr < n && s[ptr] == c {
ptr++
count++
}
ans += min(count, last)
last = count
}
return ans
}
func min(x, y int) int {
if x < y {
return x
}
... |
// Copyright 2023 Google 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 required by applica... |
package tmpl
import "strings"
func FillTmpl(tmpl string, values map[string]string) string {
if values == nil {
return tmpl
}
for k, v := range values {
tmpl = strings.Replace(tmpl, "{{"+k+"}}", v, 1)
}
return tmpl
}
|
package endpoints
import (
"encoding/json"
"github.com/valyala/fasthttp"
"log"
"strconv"
"strings"
"technodb-final/app/dbhandlers"
"technodb-final/app/models"
)
//var PostErrors = map[string]error{
// "conflict": errors.New("Post already exists"),
// "none": errors.New("Post not found"),
// "parent":errors.New(... |
package controllers
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/BolajiOlajide/go-api/database"
"github.com/gorilla/mux"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// CreatePerson endpoint for creating a person
func CreatePerson(response http.ResponseWrit... |
package easypost_test
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"time"
"github.com/EasyPost/easypost-go/v3"
)
type Fixture struct {
Addresses map[string]*easypost.Address `json:"addresses,omitempty"`
CarrierAccounts map[string]*easypost.CarrierAccount `json:... |
/*
* Copyright 2017 StreamSets 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... |
package format
import (
"testing"
)
// duplicate the map so individual tests dont mess with things
func getTestMap() map[string]interface{} {
m := map[string]interface{}{
"int": 1,
"negativeInt": -2,
"answer to life": 42,
"string": "test",
"emptyString": "",
"true": tr... |
package renter
// skyfilefanout.go implements the encoding and decoding of skyfile fanouts. A
// fanout is a description of all of the Merkle roots in a file, organized by
// chunk. Each chunk has N pieces, and each piece has a Merkle root which is a
// 32 byte hash.
//
// The fanout is encoded such that the first 32 ... |
package domain
// BindRequest encapsulates the request payload information
// for a bind request.
type BindRequest struct {
// BindingID is the ID value for the service binding
// represented by this bind request.
BindingID string
// InstanceID is the ID value for the service instance
// to be bound in this bind... |
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"github.com/julienschmidt/httprouter"
)
var (
answer = ""
webRoot = "web-root"
whitelistFile = "tmp/whitelist"
)
func main() {
loadAnswer()
router := httprouter.New()
router.POST("/answer", answerPost)
router.NotFound = htt... |
package consensus
import (
"context"
"encoding/hex"
"math/big"
"time"
"github.com/Secured-Finance/dione/ethclient"
"github.com/asaskevich/EventBus"
"github.com/ethereum/go-ethereum/common"
"github.com/Secured-Finance/dione/config"
"github.com/Secured-Finance/dione/cache"
"github.com/ethereum/go-ethereu... |
package main
import "sync"
func merge(done <-chan struct{}, ch ...<-chan int) <-chan int {
var wg sync.WaitGroup
out := make(chan int)
output := func(c <-chan int) {
for n := range c {
select {
case out <- n:
case <-done:
}
}
wg.Done()
}
wg.Add(len(ch))
for _, c := range ch {
go output(c)
... |
//自定义中间件 recorder记录
package main
import (
"net/http"
"net/http/httptest"
)
type MiddleWare struct {
http.Handler
}
func (self *MiddleWare)ServeHTTP(w http.ResponseWriter, r *http.Request) {
rec := httptest.NewRecorder()
self.Handler.ServeHTTP(rec,r)
for k,v := range rec.Header(){
w.... |
package ber
import (
"bytes"
"io"
"math"
"testing"
)
func TestReadIdentifier(t *testing.T) {
testCases := map[string]struct {
Data []byte
ExpectedIdentifier Identifier
ExpectedBytesRead int
ExpectedError string
}{
"empty": {
Data: []byte{},
ExpectedBytesRead: 0,
ExpectedEr... |
package feed
import (
"api/factory"
"encoding/json"
"net/http"
)
func Create(response http.ResponseWriter, request *http.Request) {
feed := New()
var feedRequest Feed
defer request.Body.Close()
{
if err := json.NewDecoder(request.Body).Decode(&feedRequest); err != nil {
response.WriteHeader(http.StatusI... |
package main
import (
"bytes"
"encoding/json"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"testing"
)
var drinkList = []string{"beer", "wine", "coke"}
const user = "marvin"
const playlistUser = "paranoid"
func TestPingPongRoute(t *testing.T) {
router := InitRoutes()
queueDrinks = fals... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-09-18 08:55
# @File : lt_1171_Remove_Zero_Sum_Consecutive_Nodes_from_Linked_List.go
# @Description :
# @Attention :
*/
package v0
/*
去除和抵消为0的值
关键: 对每个元素的下标取和,如果 有重复的说明,[x,y] 之间的是可以抵消掉的
*/
func removeZeroSumSublists(head *ListNode) *ListNode {
if nil ==... |
package ptrace
import (
"context"
"os"
"github.com/criyle/go-sandbox/pkg/forkexec"
"github.com/criyle/go-sandbox/ptracer"
"github.com/criyle/go-sandbox/runner"
)
// Run starts the tracing process
func (r *Runner) Run(c context.Context) runner.Result {
ch := &forkexec.Runner{
Args: r.Args,
Env: r.E... |
package repo
import "fmt"
// Repo uniquely identifies a GitHub repository.
type Repo struct {
Owner string
Name string
}
func (r *Repo) String() string {
if r.Owner == "" && r.Name == "" {
return ""
}
return fmt.Sprintf("%v/%v", r.Owner, r.Name)
}
|
package cmd
import (
"github.com/spf13/cobra"
)
// Create the cancel command
var cmdCancel = &cobra.Command{
Use: "cancel WORKFLOW",
Short: "Cancel a workflow",
Long: `Cancel a Swif workflow.
Use "sw rm WORKFLOW" to delete a workflow.`,
Example: `1. sw cancel my-workflow
2. sw cancel ana`,
Run: runCancel,
}
... |
package car
import (
"github.com/shanghuiyang/rpi-devices/dev"
)
// Config ...
type Config struct {
Engine *dev.L298N
Servo *dev.SG90
GY25 *dev.GY25
Horn *dev.Buzzer
Led *dev.Led
Light *dev.Led
Camera *dev.Camera
GPS *dev.GPS
LC12S *dev.LC12S
Collisions []*d... |
package main
func main() {
}
func smallerNumbersThanCurrent(nums []int) []int {
cnt := [101]int{}
for _, v := range nums {
cnt[v]++
}
for i := 0; i < 100; i++ {
cnt[i+1] += cnt[i]
}
ans := make([]int, len(nums))
for i, v := range nums {
if v > 0 {
ans[i] = cnt[v-1]
}
}
return ans
}
|
/*
Copyright The Helm 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, software
di... |
package proxy
import (
"fmt"
"net"
"net/http"
"net/url"
"time"
)
type Proxy struct {
Scheme string
IP string
Port string
ConnTime time.Duration
}
func (p *Proxy) Test(client *http.Client, URL string, check func(resp *http.Response) error) error {
transport, err := p.Transport(client.Timeout)
i... |
package main
import (
"fmt"
"net/http"
"os"
)
func Handler_header(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "write header! ")
fmt.Println(r.Header.Get("Accept-Language"))
w.Header().Set("Accept-Language", r.Header.Get("Accept-Language"))
fmt.Printf("ClientIP: %s \n", r.RemoteAddr)
fmt.Printf("... |
package backends
import (
//"fmt"
"io"
//"github.com/lioneagle/abnf/src/basic"
//"github.com/lioneagle/goutil/src/chars"
"github.com/lioneagle/goutil/src/code_gen/backends"
//"github.com/lioneagle/goutil/src/code_gen/model"
)
type CGeneratorH struct {
CGeneratorBase
}
func NewCGeneratorH(w io.Writer, config... |
package snow
import (
"fmt"
"github.com/HuiOnePos/flysnow/models"
"github.com/HuiOnePos/flysnow/utils"
"gopkg.in/mgo.v2/bson"
)
type ClearReq struct {
TagTerms map[string][]string `json:"tag_terms" `
Query bson.M `json:"query"`
STime int64 `json:"s_time"`
ETime int64 ... |
package log
import (
"github.com/MuratSs/assert"
"testing"
)
func TestLevel_String(t *testing.T) {
var actual string
var assert = assert.With(t)
actual = DEBUG.String()
assert.That(actual).IsEqualTo("DEBUG")
actual = INFO.String()
assert.That(actual).IsEqualTo("INFO")
actual = WARN.String()
assert.That(a... |
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("==START")
c := make(chan bool)
people := [2]string{"A","B"}
for _, person := range people {
go print(person, c)
}
time.Sleep(time.Second * 5)
result := <-c
fmt.Println(result)
fmt.Println("==END")
}
func print(person string, c chan bool)... |
package pkg
import (
"net/http"
"regexp"
"strings"
"sync"
"github.com/davecgh/go-spew/spew"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
const keyAuthDefaultHTTPBasicUser = "gte"
const keyAuthApiKeyQuery = "__gteApiKey"
const keyArgsHea... |
/*
* @lc app=leetcode.cn id=31 lang=golang
*
* [31] 下一个排列
*/
// @lc code=start
package main
import "fmt"
func main() {
var nums []int
nums = []int{1,2,3,4,5}
nums2 := make([]int, len(nums))
copy(nums2, nums)
nextPermutation(nums)
fmt.Printf("%v, %v\n", nums2, nums)
}
func nextPermutation(nums []int) {
... |
package stack
import "errors"
//Stack is a good type
type Stack []interface{}
//Push a value
func (stack *Stack) Push(val interface{}) error {
*stack = append(*stack, val)
return nil
}
//Pop a value
func (stack *Stack) Pop() (interface{}, error) {
thestack := *stack
if len(thestack) == 0 {
return nil, errors.... |
package ical
import (
"fmt"
"io"
"strings"
)
const timeFormat = "20060102T150405Z"
// NewEncoder ...
func NewEncoder(w io.Writer) *Encoder {
return &Encoder{w: w}
}
// Encode ...
func (ec *Encoder) Encode(cal VCalendar) {
fmt.Fprintln(ec.w, "BEGIN:VCALENDAR\nVERSION:2.0\nMETHOD:PUBLISH")
for _, e := range c... |
package Problem0389
func findTheDifference(s string, t string) byte {
rec := make([]int, 26)
for i := range s {
rec[s[i]-'a']--
rec[t[i]-'a']++
}
rec[t[len(t)-1]-'a']++
var i int
for i = 0; i < 26; i++ {
if rec[i] == 1 {
break
}
}
return byte('a' + i)
}
|
package slice
func rotate(x []int, r int) {
// If r is negative means left rotating
// Then rotate on the right by len(x) + r
if r < 0 {
r = len(x) + (r % len(x))
}
y := make([]int, len(x))
copy(y, x)
for i := range y {
x[(i+r)%len(x)] = y[i]
}
}
|
package log
import (
"bytes"
"crypto/tls"
"fmt"
"io"
"net"
"os"
"path/filepath"
"time"
raftboltdb "github.com/hashicorp/raft-boltdb"
api "github.com/alexeyqian/proglog/api/v1"
)
var (
_ raft.FSM = (*fsm)(nil)
)
type fsm struct {
log *Log
}
type DistributedLog struct {
config Config
log *Log
raft *ra... |
package viewmodel
// Signup struct
type Signup struct {
Title string
Active string
Email string
Password string
PasswordConfirmation string
FirstName string
LastName string
Alert string
AlertMessage string
A... |
package dshelp
import (
"testing"
cid "gx/ipfs/QmR8BauakNcBa3RbE4nbQu76PDiJgoQgz8AJdhJuiU4TAw/go-cid"
)
func TestKey(t *testing.T) {
c, _ := cid.Decode("QmP63DkAFEnDYNjDYBpyNDfttu1fvUw99x1brscPzpqmmq")
dsKey := CidToDsKey(c)
c2, err := DsKeyToCid(dsKey)
if err != nil {
t.Fatal(err)
}
if c.String() != c2.St... |
package redis
import (
"fmt"
"testing"
"time"
"github.com/garyburd/redigo/redis"
)
//var srv *disposable_redis.Server
func TestBatch(t *testing.T) {
//t.SkipNow()
conn, e := redis.Dial("tcp", srv.Addr())
if e != nil {
t.Fatal("Could not connect to server:", e)
}
var b *Batch = NewBatch(conn)
val := fm... |
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestMemoryStorage(t *testing.T) {
ms := newMemoryStorage()
imageRanks := ms.GetImageRanks()
assert.Equal(t, len(imageRanks), 0, "New MemoryStorage is empty.")
ms.Meme("me", "http://foo.bar/z.gif")
imageRanks = ms.GetImageRanks()
a... |
// Package cmd contains definitions for executable commands and is responsible
// for the validation of flags and arguments.
package cmd
import (
"github.com/urfave/cli"
"github.com/davidsbond/mona/internal/command"
"github.com/davidsbond/mona/internal/config"
)
// The ActionFunc type is a method that takes a CLI... |
package utils
import (
"context"
"github.com/mojocn/base64Captcha"
"time"
"github.com/go-redis/redis/v8"
)
type CaptchaConfig struct {
KeyPrefix string
Expire time.Duration
}
type Captcha struct {
redis *redis.Client
keyPrefix string
expire time.Duration
}
func NewCaptcha(redisClient *redis.Clie... |
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"math/rand"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"gopkg.in/redis.v3"
)
// TestProxy ...
func TestProxy(t *testing.T) {
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
client := redis.New... |
package service
import (
"context"
"culture/cloud/base/server/rpc/proto"
"errors"
"log"
"time"
)
type DemoService struct {}
func (s *DemoService) UserInfo(ctx context.Context, req *proto.Request) (*proto.Response, error) {
log.Println("DemoService UserInfo " + time.Now().Format("2006-01-02 15:04:05"))
if req.... |
package storage
import (
"sync"
"github.com/appootb/substratum/storage"
)
func Init() {
if storage.Implementor() == nil {
storage.RegisterImplementor(&Manager{})
}
}
type Manager struct {
sync.Map
}
func (m *Manager) New(component string) {
m.Store(component, &Storage{})
}
func (m *Manager) Get(component ... |
// Licensed to SolID under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. SolID licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compli... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.