text stringlengths 11 4.05M |
|---|
package main
import (
"bufio"
"encoding/gob"
"encoding/xml"
"flag"
"fmt"
"io/ioutil"
"math"
"os"
"path"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
"sync"
"time"
. "GoParsLog_1C/Tools"
"runtime/pprof"
)
//var Tools, error = build.Import("Tools/Chain", "", build.IgnoreVendor)
type Data stru... |
package utils
import (
"errors"
"os/exec"
"strings"
)
// SetGlobalENVBool 设置全局环境变量
func SetGlobalENVBool(envName, data string) bool {
return SetGlobalENV(envName, data) == nil
}
// SetGlobalENV 设置全局环境变量
//
// 执行该命令可能并不能正确的判断是否成功
//
// `windows` 的操作系统相关东西不太懂...
func SetGlobalENV(envName, data string) error {
var... |
package handlers
import (
"net/http"
"strconv"
"github.com/labstack/echo"
"github.com/letrannhatviet/my_framework/db"
"github.com/letrannhatviet/my_framework/db/types"
)
func AddStudent(c echo.Context) error {
var req types.StudentAddReq
if err := c.Bind(&req); err != nil {
return c.JSON(http.StatusBadReque... |
package main
import (
"errors"
f "fmt"
"math"
)
func main() {
f.Println("err")
result, err := Sqrt(0)
f.Println(result)
f.Println(err)
}
func Sqrt(f float64) (float64, error) {
if f <= 0 {
return 0, errors.New("math : source root of negative number")
} else {
return math.Sqrt(f), errors.New("ok")
}... |
package main
import (
"fmt"
"io/ioutil"
"strconv"
"strings"
)
func main() {
data, err := ioutil.ReadFile("input.txt")
if err != nil {
panic(err)
}
lines := strings.Split(strings.TrimSpace(string(data)), "\n")
part1(lines)
part2(lines)
}
func part1(lines []string) {
fuel := 0
for _, line := range lin... |
package util
import (
"fmt"
"github.com/codegangsta/cli"
"github.com/codegangsta/inject"
"log"
"reflect"
)
var appFlags = map[string]cli.Flag{}
//添加字符串参数
func AddFlagString(sf cli.StringFlag) cli.StringFlag {
if _, ok := appFlags[sf.Name]; ok {
panic(fmt.Sprintf("flag %s denined", sf.Name))
} else {
appFl... |
package gate
import (
"fmt"
"github.com/dming/lodos/log"
"github.com/dming/lodos/gate"
)
/**
存储用户的Session信息.
Session Bind Userid以后每次设置 settings都会调用一次Storage
*/
func (gate *Gate) Storage(Userid string, session gate.Session) (err error) {
/*
//增量更新settings
var result *safemap.BeeMap4String
if gate.storage.Check(... |
package api
import (
"encoding/json"
"net/http"
"sort"
"internal/ctxutil"
"github.com/garyburd/redigo/redis"
)
const (
prefixMaker = "maker"
)
type jsonMaker struct {
ID int64 `json:"id,omitempty"`
IDSpecDEC []int64 `json:"id_spec_dec,omitempty"`
IDSpecINF []int64 `json:"id_spec_inf,omitempty"`
... |
package Problem0564
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
// tcs is testcase slice
var tcs = []struct {
n string
ans string
}{
{
"9",
"8",
},
{
"99999999999999999",
"100000000000000001",
},
{
"8888",
"8778",
},
{
"100000000000000001",
"99999999999999999",
... |
package wsio
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"github.com/golang/glog"
)
/////////////////////////////////////
// IN
/////////////////////////////////////
// From Server: "ManageGetIpcam", "ManageSetIpcam", "ManageReconnectIpcam"
type FromServerCommand struct {
From uint `json:"f... |
package main
/*
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
char getch(){
char ch = 0;
struct termios old = {0};
fflush(stdout);
if( tcgetattr(0, &old) < 0 ) perror("tcsetattr()");
old.c_lflag &= ~ICANON;
old.c_lflag &= ~ECHO;
old.c_cc[VMIN] = 1;
... |
/*
BFS: 一般用来寻找最短路径问题, 需要用到queue数据结构, 走迷宫, 解密码锁等会用到
BFS算法框架为:
func bfs(start, target)
var q queue //核心数据结构, 放入需要处理的结点
visited := make(map[*node]struct{}) //存入已遍历的结点, 防止走回头路
//首先加入start结点
q.offer(start)
visited.add(start)
var step int //存入走过的步数, 本实例就是求步数,其他问题需要结合题目
//遍历q队列的所有结点
for (q not empty)
sz := q.size... |
package main
import "github.com/lrsec/goroutine_pool"
func initMQProducerStage(input chan interface{}) (output chan interface{}, err error) {
handler := func(interface{}) interface{} {
//TODO read/write connection messages
return nil
}
//TODO 调节 pool 参数
pool, err := goroutine_pool.NewPool(100, 10*10000, 200... |
package client
import (
"io/ioutil"
"testing"
"github.com/golang/protobuf/proto"
"github.com/turnage/redditproto"
)
func TestLoad(t *testing.T) {
expected := &redditproto.UserAgent{}
if err := proto.UnmarshalText(`
user_agent: "test"
client_id: "id"
client_secret: "secret"
username: "user"
password: ... |
package main
import (
"path/filepath"
"os"
)
func createNodeFunction(path string){
indexJs := getStringFromBindata("data/nodejs/index.js")
functionJson := getStringFromBindata("data/nodejs/function.json")
absPath, _ := filepath.Abs("./functions")
if _, err := os.Stat(absPath); err == nil {
path = absPath+"/... |
/**
Copyright @ 2014 OPS, Qunar Inc. (qunar.com)
Author: tingfang.bao <tingfang.bao@qunar.com>
DateTime: 14-8-20 下午12:21
*/
package form
import (
//"math"
"net/http"
"regexp"
)
/**
表单类的抽象
*/
type Form struct {
Name string
Action string
Fields map[string]Field
IsValid bool
//validResults map[string]*Va... |
package rest
import (
"net/http"
"reflect"
"testing"
)
func TestNewAPIClient(t *testing.T) {
type args struct {
username string
password string
}
tests := []struct {
name string
args args
want *APIClient
}{
{"base-case", args{"username", "password"},
&APIClient{
Client: &http.Client{
Tr... |
package main
import (
"io"
"os"
"time"
)
var _output io.Writer = os.Stdout
type S struct {
s string
}
func (s S) Print() {
io.WriteString(_output, s.s)
}
func main() {
s := S{"Hello World\n"}
time.AfterFunc(time.Millisecond, s.Print)
}
|
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
gnmipb "github.com/openconfig/gnmi/proto/gnmi"
pb "github.com/polarbroadband/gnmi/pkg/gnmiprobe"
client "github.com/polarbroadband/gnmi/pkg/probeclient"
"github.com/google/gnxi/utils/xpath"
"google.golang.org/gr... |
package capabilities
import (
"fmt"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/syndtr/gocapability/capability"
"strings"
)
const allCapabilityTypes = capability.CAPS | capability.BOUNDS | capability.AMBS
type Capabilities struct {
CapMap map[string]capability.Cap
Pid capability.... |
package cron
import "github.com/jinzhu/gorm"
const (
specJobTable = "spec_job"
)
type mysqlJobListPersistence struct {
db *gorm.DB
}
func newMysqlPersistence(db *gorm.DB) JobListPersistence {
m := &mysqlJobListPersistence{
db: db,
}
if err := db.AutoMigrate(new(SpecJob)).Error; err != nil {
panic("mysql jo... |
package account
import (
"database/sql"
"github.com/DemoHn/obsidian-panel/app/secret"
"github.com/DemoHn/obsidian-panel/infra"
"github.com/DemoHn/obsidian-panel/util"
)
// infra variables
var log = infra.Log
// AccountsFilter - define filter properties for listing accounts
type AccountsFilter struct {
NameLike... |
package endpoints
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/go-kit/kit/endpoint"
kithttp "github.com/go-kit/kit/transport/http"
"github.com/google/uuid"
"github.com/sumelms/microservice-course/internal/matrix/domain"
"github.com/sumelms/microservice-course/pkg/validator"
)
typ... |
// ˅
package main
import (
"math/rand"
"time"
)
// ˄
// Generate a random number.
type RandomNumber struct {
// ˅
// ˄
Number
// ˅
// ˄
}
func NewRandomNumber() *RandomNumber {
// ˅
rand.Seed(time.Now().UnixNano())
return &RandomNumber{Number{value: 0}}
// ˄
}
func (self *RandomNumber) Generate() {
... |
// Copyright © 2019 NAME HERE <EMAIL ADDRESS>
//
// 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 ... |
package css
type Selector interface {
Selector() string
}
func selectorsToStrings(selectorsSelectors []Selector) []string {
var selectors []string
for i := range selectorsSelectors {
selectors = append(selectors, selectorsSelectors[i].Selector())
}
return selectors
}
|
package api
type Intents struct {
Confirm *EmptyObj `json:"YANDEX.CONFIRM"`
Reject *EmptyObj `json:"YANDEX.REJECT"`
AddItem *IntentAddItem `json:"list_item_add"`
DeleteItem *IntentDeleteItem `json:"list_item_delete"`
ViewList *IntentViewList `json:"list_view"`
CreateList *IntentC... |
package controllers
import (
"fmt"
"strconv"
"github.com/humio/humio-operator/pkg/kubernetes"
corev1 "k8s.io/api/core/v1"
)
const (
containerStateCreating = "ContainerCreating"
containerStateCompleted = "Completed"
podInitializing = "PodInitializing"
PodConditionReasonUnsche... |
package main
import (
"bytes"
"sync"
)
// A mode set.
type Modeset struct {
modes map[rune]string
mm sync.RWMutex
}
func NewModeset() Modeset {
return Modeset{modes: make(map[rune]string)}
}
func (m *Modeset) Get(r rune) (val string, ok bool) {
m.mm.RLock()
defer m.mm.RUnlock()
val, ok = m.modes[r]
ret... |
package index
import (
"fmt"
"github.com/garyburd/redigo/redis"
"github.com/juju/errgo"
)
type Field interface {
Name() string
Type() FieldType
// Verify whether the persisted keys matchs the expected type for this field.
// Return nil if everything is sound.
// Check() error
// Key to a Redis of keys cont... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//757. Set Intersection Size At Least Two
//An integer interval [a, b] (for integers a < b) is a set of all consecutive integers from a to b, including... |
package main
import (
"fmt"
"net/http"
"net/http/pprof"
"sync"
)
var mu sync.Mutex
var chain string
const (
pprofAddr string =":7890"
)
func StartHttpDebuger() {
pprofHandler := http.NewServeMux()
pprofHandler.Handle("/debug/pprof/",http.HandlerFunc(pprof.Index))
server := &http.Server{Addr: pprofAddr, Ha... |
package rancher
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"github.com/sirupsen/logrus"
"github.com/docker/libcompose/docker/builder"
"github.com/docker/libcompose/project"
)
type Uploader interface {
Upload(p *project.Project, name string, reader io.ReadSeeker, hash stri... |
package cain
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document01200101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:cain.012.001.01 Document"`
Message *KeyExchangeResponse `xml:"KeyXchgRspn"`
}
func (d *Document01200101) AddMessage() *K... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-08-14 09:02
# @File : lt_61_Search_for_a_Range.go
# @Description :
# @Attention :
*/
package half
func searchRange(nums []int, target int) []int {
start := 0
end := len(nums) - 1
result := []int{-1, -1}
for start < end {
mid := (start + end) >> 1
i... |
package lpcorpus
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"math"
"unicode/utf8"
)
// Note: this hacky union type is total overkill for this use, but the code might come in
// useful later in some place where high performance is more
// important so let's keep it for now.
// Value holds one of t... |
package schedulerd
import (
"context"
"github.com/sensu/sensu-go/backend/messaging"
"github.com/sensu/sensu-go/backend/store"
"github.com/sensu/sensu-go/types"
)
// Schedulerd handles scheduling check requests for each check's
// configured interval and publishing to the message bus.
type Schedulerd struct {
st... |
package gedcom_test
import (
"github.com/elliotchance/gedcom"
"github.com/stretchr/testify/assert"
"testing"
)
func TestFilterFlags_Filter(t *testing.T) {
t.Run("NoDuplicateNames", func(t *testing.T) {
doc1 := gedcom.NewDocument()
doc1.AddIndividual("P1",
gedcom.NewNameNode("Bob /Smith/"),
gedcom.NewNam... |
package models
import (
"encoding/json"
"errors"
"fmt"
"github.com/gomodule/redigo/redis"
)
const (
sqlForCreatePenalty = "INSERT INTO penalties(id,company_id,points,punish_number,content,decision,Date) VALUES(?,?,?,?,?,?,?);"
)
type Penalty struct {
ID int `orm:"column(id)"`
CompanyID int ... |
// Copyright 2020 The Reed Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
package discover
import (
"fmt"
"net"
"testing"
)
func TestPacket(t *testing.T) {
m := make(map[*timeoutEvent]string)
addr, _ := net.R... |
package cache
import (
"fmt"
"os"
"github.com/go-redis/redis/v7"
)
var client *redis.Client
func init() {
client = redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:6379", os.Getenv("REDIS_URL")), // use default Addr
DB: 0, // use default DB
})
}
|
package main
import (
"flag"
"fmt"
)
func hello(name string) {
fmt.Println(name + " hello world!")
}
var name string
func init() {
flag.StringVar(&name, "name", "everyone", "person object")
// flag.String 与 flag.StringVar 功能类似,用法存在些许差异
// name := flag.String("name", "everyone", "person object")
}
func main()... |
package main
import (
"github.com/stretchr/testify/assert"
"math/big"
"testing"
)
func Test_Solve(t *testing.T) {
a, b := Solve(big.NewInt(10), big.NewInt(2))
assert.Equal(t, a, 6)
assert.Equal(t, b, 4)
}
|
package github
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
func UpdateIssues(url string, jsonStr []byte) (*Issue, error) {
// req, _ := http.NewRequest("PATCH", url, bytes.NewBufferString(jsonStr))
req, _ := http.NewRequest("PATCH", url, bytes.NewReader(jsonStr))
req.Header.Set("Authorization", token)
... |
package parser
import (
"encoding/json"
"fmt"
)
type Wal2JsonChange struct {
// Operation kind (e.g. insert, update, delete)
Kind string `json:"kind"`
// Schema & Table names
Schema string `json:"schema"`
Table string `json:"table"`
// Column names
ColumnNames []string `json:"columnnames"`
// Human-read... |
/*
Copyright 2018 Pressinfra SRL.
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... |
package structs
type EmpDep struct {
Id int `json:"id" query:"id" db:"id"`
EmployeeId int `json:"employee_id" query:"employeeid" db:"employee_id"`
DepartmentId int `json:"department_id" query:"departmentid" db:"department_id"`
EffectFrom string `json:"effect_from" query:"effectfrom" db:"effe... |
package printer
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/hokaccha/go-prettyjson"
"github.com/logrusorgru/aurora"
"github.com/olekukonko/tablewriter"
"github.com/sirupsen/logrus"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"github.com/batchcorp/plumber-schemas/build/go/pro... |
package frontend
//i think when renderRPHome gets called, the old recurring payments list will be removed
import (
"github.com/gin-gonic/gin"
"net/http"
"strconv"
)
func (s *Server) rpDelPost(ctx * gin.Context) {
sessionToken := ctx.GetString("sessionToken")
id := ctx.PostForm("id")
n, err := strconv.At... |
package main
import "fmt"
import "io/ioutil"
import "net/http"
//import "net/url"
import "bytes"
import "compress/gzip"
import "encoding/json"
import "encoding/base64"
func DoPVerb(verb string, route string, params map[string]interface{}) string {
var buf, _ = json.Marshal(params)
//fmt.Println(string(buf))
//b... |
package msi
import (
"encoding/json"
"errors"
"fmt"
"github.com/Sirupsen/logrus"
"io/ioutil"
"net/http"
"net/url"
"os"
"strconv"
"sync"
"time"
)
const (
realTimeGracePeriod = time.Second * 30
refreshGracePeriod = time.Minute * 30
StorageResource = "https://storage.azure.com/"
)
type tokenJson stru... |
package main
import (
"encoding/base64"
"fmt"
"io/ioutil"
"log"
"net/http"
"os/exec"
"strings"
"time"
)
// Gets networking port information
func getOpenPorts() string {
cmd := "./Bash Functions/getOpenPorts.sh"
// Get's output of 'nmap' command
openPortsByte, _ := exec.Command(cmd).Output()
openPortsStri... |
package data
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"path"
"time"
"github.com/decentraland/content-service/metrics"
"github.com/sirupsen/logrus"
)
type accessResponse struct {
Ok bool `json:"ok"`
Data *AccessData `json:"data"`
}
type AccessData struct {
Id ... |
package main
import (
"fmt"
"strconv"
)
func main() {
//var num1 int = 99
//var num2 float64 = 23.456
//var b1 bool = true
//var myChar byte = 'h'
// 第一种方式,使用fmt.Sprintf方法转化
//strNum1 := fmt.Sprintf("%d", num1)
//fmt.Printf("str type %T str=%q \n", strNum1, strNum1)
//
//strNum2 := fmt.Sprintf("%f", num2)... |
package main
import (
"flag"
"io/ioutil"
"log"
"net/http"
"github.com/nats-io/nats"
)
var natsServer = flag.String("nats", "", "NATS server URI")
var natsClient *nats.Conn
type product struct {
Name string `json:"name"`
SKU string `json:"sku"`
}
func init() {
flag.Parse()
}
func main() {
var err error
... |
#Continue to edit the branch beta-1.0
|
package textfilehandledemo
import (
"encoding/binary"
"fmt"
"os"
"strconv"
"testing"
)
func TestHandleFile(t *testing.T) {
os.Mkdir("testdir",0777)
os.MkdirAll("testdir/t1/t2/t3",0777)
err := os.Remove("testdir")
if err != nil{
fmt.Println(err)
}
//os.RemoveAll("testdir")
userFile := "test_str.txt"
f... |
package main
import (
"fmt"
)
func main() {
var i interface{}
i = "Hello"
j := i.(string)
k, ok := i.(int)
fmt.Println(j, k, ok)
// m := i.(int)
// fmt.Println(m) //Panic
}
|
package leetcode
type stack []int
func (s *stack) Push(v int) {
*s = append(*s, v)
}
func (s *stack) Pop() {
if len(*s) == 0 {
return
}
*s = (*s)[:len(*s)-1]
}
func (s *stack) Top() int {
if len(*s) == 0 {
return 0
}
return (*s)[len(*s)-1]
}
func (s *stack) Empty() bool {
return len(*s) == 0
}
// 辅助栈
typ... |
package controller
import (
"fmt"
"net/http"
"strconv"
"../service"
"../util"
)
var contactService service.ContactService
//
func Addfriend(w http.ResponseWriter, request *http.Request) {
request.ParseForm()
from, err1 := strconv.ParseInt(request.PostForm.Get("fromid"), 10, 64)
to, err2 := strconv.ParseIn... |
package repo_manager
import (
"bytes"
"context"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"path"
"regexp"
"strings"
"go.skia.org/infra/autoroll/go/codereview"
"go.skia.org/infra/autoroll/go/revision"
"go.skia.org/infra/go/depot_tools"
"go.skia.org/infra/go/exec"
"go.skia.org/infra/go/gerrit"
"go.skia... |
package main
import (
"bufio"
"fmt"
"os"
"os/exec"
"strings"
"io/ioutil"
"path/filepath"
"github.com/codegangsta/cli"
)
func fix(c *cli.Context) error {
repo := c.String("repo")
if fixErr := fixExistingSubmodules(repo); fixErr != nil {
return fmt.Errorf("failed to fix existing submodules: %s", fixErr)
... |
package config
// This file includes configs for the run program settings
var (
// default read permission files
defaultReadableFiles = []string{
"/etc/ld.so.nohwcap",
"/etc/ld.so.preload",
"/etc/ld.so.cache",
"/usr/lib/locale/locale-archive",
"/proc/self/exe",
"/etc/timezone",
"/usr/share/zoneinfo/",... |
package configuration
import (
"fmt"
"os"
"strings"
"github.com/spf13/pflag"
"github.com/authelia/authelia/v4/internal/configuration/schema"
"github.com/authelia/authelia/v4/internal/utils"
)
// koanfEnvironmentCallback returns a koanf callback to map the environment vars to Configuration keys.
func koanfEnvi... |
/*Write a Go program that finds the sum of all command-line arguments that are
valid numbers*/
package main
import (
"fmt"
"io"
"os"
"strconv"
)
func main() {
mainString := ""
var sum = 0.0
var average = 0.0
if len(os.Args) == 1 {
mainString = "Please provide one input at least"
} else {
for i := 1; i ... |
package models
// FetchResponse holds one payment
type FetchResponse struct {
Data *Payment `json:"data"`
}
// ListResponse holds one payment
type ListResponse struct {
Data *[]Payment `json:"data"`
}
// BeneficiaryParty holds information about amount and currency for receiver
type BeneficiaryParty struct {
ID ... |
package tree
import (
"fmt"
"math/rand"
"sort"
"strings"
"testing"
"github.com/gaissmai/go-inet/inet"
"github.com/gaissmai/go-inet/internal"
)
func TestTreeInsertBulk(t *testing.T) {
n := 20000
cidrs := internal.GenBlockMixed(n)
ranges := internal.GenRangeMixed(n)
blocks := make([]inet.Block, 0, len(cidr... |
package main
import (
"bufio"
"os"
"strings"
)
type Action func([]byte, *ClientConnection)
var commandMap map[string]Action = map[string]Action{
"login": Login,
"logout": Logout,
"list": UserList,
"help": Help,
}
func Help(message []byte, client *ClientConnection) {
helpfile, err := os.Open("help.txt")... |
package main
import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
func goimports(paths []string, verbose bool) error {
args := []string{"-l", "-w"}
for _, path := range paths {
args = append(args, path)
}
if verbose {
fmt.Println("goimports", strings.Join(args, " "))
}
cmd := exec.Command... |
package main
import (
"crypto/tls"
"io"
"net/http"
"strings"
"time"
log "github.com/Sirupsen/logrus"
"github.com/fuyufjh/splunk-hec-go"
"github.com/urfave/cli"
)
func init() {
app.Commands = append(app.Commands,
cli.Command{
Name: "splunk",
Usage: "forward messages to splunk",
Action: func(c *c... |
package server
import (
"context"
"errors"
"fmt"
"net"
log "github.com/golang/glog"
"lib/shmcache"
"lib/client"
"recall_cf/config"
"recall_cf/handler"
"recall_cf/proto/recall_cf"
)
type ServerImpl struct {
Listen net.Listener
Config *config.Config
}
func (s *ServerIm... |
package sort
import "fmt"
var s []int = []int{23, 42, 35, 10, 34}
func BubbleSort() {
//s := []int{23, 42, 35, 10, 34}
for i := 0; i < len(s); i++ {
for j := 0; j < len(s)-i-1; j++ {
if s[j] > s[j+1] {
s[j+1], s[j] = s[j], s[j+1]
}
}
}
fmt.Println(s)
}
|
package whois
import (
"encoding/json"
"errors"
"net/http"
)
type WhoisXMLAPI struct {
APIKey string
}
type whoisResponse struct {
WhoisRecord map[string]interface{} `json:"WhoisRecord"`
}
func (w *WhoisXMLAPI) Lookup(domain string) (bool, error) {
response, err := http.Get("https://www.whoisxmlapi.com/whoiss... |
package handler
import (
"context"
"fmt"
aria2pb "github.com/jlb0906/micro-movie/aria2-srv/proto/aria2"
"github.com/jlb0906/micro-movie/basic/common"
pb "github.com/jlb0906/micro-movie/movie-srv/proto/movie"
"github.com/jlb0906/micro-movie/movie-srv/service/movie"
"github.com/micro/go-micro/v2/client"
"github.... |
// Package main -
package main
import (
"fmt"
"github.com/shanehowearth/concurrency_in_go/pipeline"
"github.com/shanehowearth/concurrency_in_go/teechannel"
)
func main() {
done := make(chan interface{})
defer close(done)
out1, out2 := teechannel.Tee(done, pipeline.Take(done, pipeline.Repeat(done, 1, 2), 4))
... |
package main
/**
* @Author: yirufeng
* @Date: 2021/8/21 5:52 下午
* @Desc:
**/
// Add get the sum of two nums
func Add(a, b int) int {
return a + b
}
|
package main
import (
"math"
)
type Vec2 [2]float32
type Vec2f64 [2]float64
type IntVec2 [2]int
func (a *Vec2) set(v *Vec2) {
a[0] = v[0]
a[1] = v[1]
}
func (a *Vec2f64) to32() *Vec2 {
return &Vec2{float32(a[0]), float32(a[1])}
}
func (a *Vec2f64) len() float64 {
return math.Sqrt(a[0]*a[0] + a[1]*a[1])
}
fu... |
/*
Copyright 2019 The Kubernetes 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, ... |
/**
* Copyright (C) 2019, Xiongfa Li.
* All right reserved.
* @author xiongfa.li
* @date 2019/2/28
* @time 17:16
* @version V1.0
* Description:
*/
package goid
import (
"crypto/rand"
"encoding/base64"
)
func RandomId(length int) string {
b := make([]byte, length)
if _, err := rand.Read(b); e... |
package _62_Unique_Paths
func uniquePaths(m int, n int) int {
var res = []int{}
for i := 0; i < n; i++ {
res = append(res, 0)
}
res[0] = 1
for i := 0; i < m; i++ {
for j := 1; j < n; j++ {
res[j] += res[j-1]
}
}
return res[n-1]
}
|
package main
import (
"fmt"
"io"
"log"
"os"
"time"
"github.com/nobonobo/tinygo-tls/orig/crypto/tls"
orig "github.com/nobonobo/tinygo-tls/orig/net"
)
const header = `GET / HTTP/1.0
Host: localhostt:8443
`
type stdConn struct {
}
// Read ...
func (c *stdConn) Read(b []byte) (n int, err error) { return os.Std... |
package etcd
import (
"context"
"encoding/json"
"fmt"
"go.etcd.io/etcd/api/v3/mvccpb"
clientv3 "go.etcd.io/etcd/client/v3"
"google.golang.org/grpc/resolver"
"log"
)
const schema = "etcd"
// Resolver implements grpc.resolve.Builder
type Resolver struct {
endpoints []string
service string
cli *client... |
package push
import (
"testing"
"github.com/10gen/realm-cli/internal/cli"
"github.com/10gen/realm-cli/internal/utils/test/assert"
)
func TestPushErrors(t *testing.T) {
t.Run("err project not found should disable usage", func(t *testing.T) {
var err error = errProjectNotFound{}
_, ok := err.(cli.DisableUsage... |
package onlinestore
import (
"crypto/sha1"
"database/sql"
"encoding/hex"
"errors"
"strings"
"sync"
"time"
"github.com/feast-dev/feast/go/internal/feast/registry"
"context"
"fmt"
_ "github.com/mattn/go-sqlite3"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
"gi... |
// Package models contains the types for schema 'public'.
package models
// GENERATED BY XO. DO NOT EDIT.
import (
"database/sql"
"errors"
"time"
)
// Activity represents a row from 'public.activities'.
type Activity struct {
ID int `json:"id"` // id
UserID sql.NullInt64 ... |
package ksqlparser
import "fmt"
type identifier struct {
Name string
Alias string
}
func (i identifier) String() string {
if i.Alias != "" {
return fmt.Sprintf("%s %s %s", i.Name, ReservedAs, i.Alias)
}
return i.Name
}
func (p *parser) parseIdentifier() (string, error) {
item := p.pop()
if len(item) == 0 ... |
package onelogin
import (
"io"
"bytes"
"net/url"
"io/ioutil"
"net/http"
"encoding/json"
)
/**
** client := HttpClient{Url:"http://www.google.com"}
** raw_response, err := client.go("GET", nil)
**
** raw_response, err := client.go("GET", &response_object)
**
**/
type HttpClient struct {
Ur... |
package dynamic_programming
import "testing"
func Test_uniquePaths(t *testing.T) {
res := uniquePaths2(3, 2)
if res != 3 {
t.Error(res)
}
}
|
package keeper
import (
"fmt"
"strings"
"github.com/provenance-io/provenance/x/metadata/types"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/... |
package panels
import (
"github.com/jesseduffield/gocui"
lcUtils "github.com/jesseduffield/lazycore/pkg/utils"
)
type ListPanel[T comparable] struct {
SelectedIdx int
List *FilteredList[T]
View *gocui.View
}
func (self *ListPanel[T]) SetSelectedLineIdx(value int) {
clampedValue := 0
if self.List... |
package db
import (
"gitee.com/johng/gf/g"
)
// 增量更新
func AddUpdate(tbName string, data g.List) error {
db := g.DB()
_, e := db.BatchSave(tbName, data, 20)
return e
}
// 全量更新
func AllUpdate(tbName string, data g.List) error {
db := g.DB()
_, e := db.BatchReplace(tbName, data, 20)
return e
}
|
package smawebboxgo
import (
"strconv"
"time"
)
// https://stackoverflow.com/a/42872183/1411901
// https://stackoverflow.com/questions/20895552/how-to-read-input-from-console-line
// https://stackoverflow.com/questions/19303137/golang-read-ints-from-stdin-until-eof-while-reporting-format-errors
type WebboxClient st... |
package intf
const (
//todo
MSTAG = "api"
)
|
package totp
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/sha1"
"crypto/sha256"
"encoding/base32"
"encoding/binary"
"fmt"
"io"
"math"
"time"
"github.com/pkg/errors"
"gopkg.in/go-playground/validator.v9"
"github.com/teejays/clog"
"github.com/teejays/n-factor-vault... |
package errors
// Op is..,
type Op string
|
package templatescompiler
import (
boshblob "github.com/cloudfoundry/bosh-agent/blobstore"
bosherr "github.com/cloudfoundry/bosh-agent/errors"
boshlog "github.com/cloudfoundry/bosh-agent/logger"
boshcmd "github.com/cloudfoundry/bosh-agent/platform/commands"
boshsys "github.com/cloudfoundry/bosh-agent/system"
bm... |
package main
/**
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
- push(x) —— 将元素 x 推入栈中。
- pop() —— 删除栈顶的元素。
- top() —— 获取栈顶元素。
- getMin() —— 检索栈中的最小元素。
*/
/**
OK
*/
type MinStackWithMe struct {
arr []int
len int
}
/** initialize your data structure here. */
func ConstructorWithMe() MinStackWithMe {
var stack MinSt... |
package main
import (
"encoding/json"
// "fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"github.com/gorilla/mux"
)
/*
TEST CURL:
curl -H "Content-Type: application/json" -d '{"category": "generic", "test": true, "serial": 1}' http://localhost:8080/load/generic_test_document_key
*/
func Loader(w http.ResponseWrit... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//686. Repeated String Match
//Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no... |
package cf
import (
"encoding/json"
"fmt"
"time"
"github.com/cloudfoundry-incubator/notifications/metrics"
)
type CloudControllerUser struct {
Guid string `json:"guid"`
}
type CloudControllerUsersResponse struct {
Resources []struct {
Metadata struct {
Guid string `json:"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.