text stringlengths 11 4.05M |
|---|
package main
import "fmt"
func main() {
p := plusTwo()
fmt.Printf("%v\n", p(2))
fmt.Printf("%v\n", plusX(2)(2))
fmt.Printf("%v\n", plusX(8)(2))
}
func plusTwo() func(int) int {
return func(i int) int { return i + 2 }
}
func plusX(x int) func(int) int {
return func(i int) int { return i + x }
}
|
package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
func main() {
//타겟 난수 생성
seconds := time.Now().Unix()
rand.Seed(seconds)
target := rand.Intn(100) + 1
fmt.Println("1에서 100사이의 난수 생성 완료.")
fmt.Println("뭐게?")
reader := bufio.NewReader(os.Stdin)
success := false
f... |
package main
// async.go runs portions of the task asynchronously
// Job describes a task for the worker
// This job is to generate a Diff containing []int of width b-a containing values k
type Job struct {
t Transform
}
// Diff is a fragment of a State slice affected by this transform
type Diff struct {
t Transfo... |
package main
import (
"fmt"
)
func main() {
var quilometros uint8
quilometros = 150
fmt.Println(quilometros)
}
|
package main
import (
"log"
"encoding/json"
"io/ioutil"
"github.com/Shopify/sarama"
)
type Entity struct {
Database string `json:"database"`
Table string `json:"table"`
BeforeColumns Columns `json:"beforeColumns"`
AfterColumns Columns `json:"afterColumns"`
EventType string `json:"event... |
package prediction
import (
pbcodec "github.com/streamingfast/sparkle/pb/dfuse/ethereum/codec/v1"
)
func (s *Subgraph) HandlePredictionUnpauseEvent(trace *pbcodec.TransactionTrace, ev *PredictionUnpauseEvent) error {
if s.StepBelow(2) {
return nil
}
market := NewMarket("1")
if err := s.Load(market); err != nil... |
package work
import (
"syscall"
"time"
)
type Disk struct {
MonitorData
}
func (d *Disk) SetMonitorData() {
fs := syscall.Statfs_t{}
err := syscall.Statfs("/", &fs)
if err != nil {
return
}
free := float64(fs.Bfree)
all := float64(fs.Blocks)
used := all - free
d.Data = used / all
d.MonitorTime = time.N... |
package main
import (
"bufio"
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"math/rand"
"mime/multipart"
"net/http"
"os"
"os/exec"
"strings"
"time"
)
func CreateRandomNumber() string {
return fmt.Sprintf("%015v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))... |
package consumergroup
import (
"encoding/json"
"fmt"
"path"
"sort"
"strconv"
"time"
"github.com/samuel/go-zookeeper/zk"
)
// ZK wraps a zookeeper connection
type ZK struct {
*zk.Conn
}
// NewZK creates a new connection instance
func NewZK(servers []string, recvTimeout time.Duration) (*ZK, error) {
conn, _,... |
// +build ignore
package main
import (
"fmt"
"log"
"net/http"
"os"
"syscall"
shutdown "github.com/klauspost/shutdown2"
)
// This example shows a server that has logging to a file
//
// When the webserver is closed, it will close the file when all requests have
// been finished.
//
// In a real world, you woul... |
package core
func NewAtom(value Type) *Type {
ptr := &value
return &Type{Atom: &ptr}
}
func (node *Type) IsAtom() bool {
return node.Atom != nil
}
func (node *Type) AsAtom() Type {
if node.IsAtom() {
return **node.Atom
}
return *NewNil()
}
func (node *Type) SetAtom(value Type) {
*node.Atom = &value
}
|
package blocking
import (
"context"
"fmt"
users "github.com/ivansukach/bets/internal/repositories/blocked-users"
log "github.com/sirupsen/logrus"
)
type Service struct {
blockedUsersRps users.Repository
}
func New(blockedUsersRps users.Repository) *Service {
return &Service{blockedUsersRps: blockedUsersRps}
}
... |
package main
import (
"fmt"
"github.com/gocrazygh/luhn"
)
func main() {
a := luhn.Check("79927398713")
b := luhn.Check("1111")
fmt.Println(a)
fmt.Println(b)
}
|
package 链表
func reverseBetween(head *ListNode, left int, right int) *ListNode {
// 1. 初始化。
dummyHead := &ListNode{
Next: head,
}
pre := dummyHead
// 2. 让 pre 走到翻转链表的前一个节点。
for i := 1; i < left; i++ {
pre = pre.Next
}
// 3. 执行翻转。
cur := pre.Next
for i := 1; i <= right-left; i++ {
next := cur.Next
cu... |
package goSolution
func reverseBetween(head *ListNode, left int, right int) *ListNode {
p := &ListNode{Next: head}
index := 0
var last, next *ListNode
var leftNode, rightNode *ListNode
var leftInnerNode, rightInnerNode *ListNode
for c := p; c != nil; c, index = next, index + 1 {
next = c.Next
if index >= lef... |
package stateful
import (
"context"
"fmt"
aliceapi "github.com/yandex-cloud/examples/serverless/alice-shareable-todolist/app/alice/api"
"github.com/yandex-cloud/examples/serverless/alice-shareable-todolist/app/errors"
)
func (h *Handler) listAllListsFromScratch(ctx context.Context, req *aliceapi.Request) (*alice... |
package taxjar
type Rate struct {
Zip string `json:"zip"`
State string `json:"state`
StateRate float64 `json:"state_rate,string"`
County string `json:"county"`
CountyRate float64 `json:"county_rate,string"`
City string `... |
package cms
import "github.com/yueyongyue/aliyungo/common"
const (
TestAccessKeyId = "YOUR_ACCESS_KEY_ID"
TestAccessKeySecret = "YOUR_ACCESS_KEY_SECRET"
TestRegionID = common.Hangzhou
)
var testClient *CMSClient
func NewTestClient() *CMSClient {
if testClient == nil {
testClient = NewCMSClient(Test... |
// Package config parses command-line/environment/config file arguments
// and make available to other packages.
package config
import (
"io/ioutil"
"path"
"runtime"
"gopkg.in/yaml.v2"
"github.com/Akagi201/utilgo/conflag"
flags "github.com/jessevdk/go-flags"
"github.com/tengattack/tgo/log"
)
// Opts configs
... |
package main
import (
"context"
"fmt"
"time"
)
var exitChan = make(chan bool, 1)
func f2(ctx context.Context) {
LOOP:
for {
fmt.Println("保德路")
time.Sleep(time.Millisecond * 500)
select {
case <-ctx.Done():
break LOOP
default:
}
}
}
func f(ctx context.Context) {
go f2(ctx)
LOOP:
for {
fmt.Pri... |
package cmd
import (
"os"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/authelia/authelia/v4/internal/utils"
)
func newBuildCmd() (cmd *cobra.Command) {
cmd = &cobra.Command{
Use: "build",
Short: cmdBuildShort,
Long: cmdBuildLong,
Example: cmd... |
package rest
// Options REST 参数
type Options struct {
APIBase string // API Base URL
WxCallbackServerBase string // 微信回调地址
WxH5ServerBase string // 微信h5地址
}
|
package handler
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
gwApi "github.com/aws/aws-sdk-go/service/apigatewaymanagementapi"
"github.com/aws/aws-sdk-go/service/dynamodb"
)
var (
Dynamo = NewDynamo()
DynamoDbTableConnections = os.Getenv(EnvDynamoDbTableConnect... |
package controller
import (
"context"
"path"
"time"
"github.com/Masterminds/semver"
"github.com/kyma-project/helm-broker/internal"
"github.com/kyma-project/helm-broker/internal/controller/addons"
"github.com/kyma-project/helm-broker/internal/storage"
addonsv1alpha1 "github.com/kyma-project/helm-broker/pkg/api... |
package pascaltriangle
import (
"fmt"
"testing"
)
func TestBasic(t *testing.T) {
var trianglehigh = 30
for i := 0; i < trianglehigh; i++ {
// Just add white space for view
for k := trianglehigh - i; k > 0; k-- {
fmt.Printf(" ")
} // for
for j := 0; j < i+1; j++ {
fmt.Printf("%d ", combination(i, j))... |
// Copyright 2018 Andreas Pannewitz. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
)
// ===========================================================================
func ExampleID_Unit() {
var i ID
i = i.Uni... |
package main
import (
"fmt"
"os"
"os/user"
"compiler/evaluate"
)
func main(){
user, err := user.Current()
if err != nil{
panic(err)
}
fmt.Printf("Hello %s!This is my IDK language\n ",user.Username)
fmt.Printf("You can type something in command line,but first check ../grammar/toke.go\n")
repl.Start(... |
package main
import (
"fmt"
"os"
"github.com/gin-gonic/gin"
"gopkg.in/urfave/cli.v1"
)
func helpAction(c *cli.Context) error {
fmt.Println("Coucou")
return nil
}
func listenAction(c *cli.Context) error {
kafkaHost := os.Getenv("kafka_host")
topic := os.Getenv("kafka_topic")
group := os.Getenv("kafka_group... |
package eventbus
import (
"github.com/asaskevich/EventBus"
)
type TaniaEventBus interface {
Publish(eventName string, event interface{})
Subscribe(eventName string, handlerFunc interface{})
}
type SimpleEventBus struct {
bus EventBus.Bus
}
func NewSimpleEventBus(bus EventBus.Bus) *SimpleEventBus {
return &Simp... |
package util
import (
"io/ioutil"
"path/filepath"
yaml "gopkg.in/yaml.v1"
)
//Config 全局配置
type Config struct {
Debug bool `yaml:"debug"`
APP string `yaml:"app"`
Auto bool `yaml:"automatic"`
Device string `yaml:"device"`
OCR string `yaml:"ocr"`
AdbAddress ... |
package main
import (
"io/ioutil"
"log"
"net"
"net/http"
"text/template"
)
type networkHandler struct{}
var networkTemplate = `
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<div class="container">
<body>
<h1>Network Info</h1>
<h3>Interfaces... |
package main
import (
"fmt"
"testing"
)
func TestTwoSum(t *testing.T) {
ans := TwoSum([]int{1, 3, 5, 6}, 7)
fmt.Println(ans)
}
|
package dao
import (
"git.dustess.com/mk-base/mongo-driver/mongo"
"git.dustess.com/mk-training/mk-blog-svc/pkg/blogstatistics/model"
"go.mongodb.org/mongo-driver/bson"
)
// AsynStaticsByBlog 统计数据(非实时)
func (m *BlogStatDao) AsynStaticsByBlog(filter interface{}) (result []model.StatBlog) {
pipe := []bson.M{
{"$ma... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-08-18 14:52
# @File : of_剑指_Offer_21_调整数组顺序使奇数位于偶数前面.go
# @Description : 双指针
# @Attention :
*/
package offer
func exchange(nums []int) []int {
slow := 0
fast := 0
for fast < len(nums) {
if nums[fast]&1 == 1 {
nums[slow], nums[fast] = nums[fast], num... |
package envoy
import "github.com/pivotal-cf-experimental/envoy/domain"
// Broker defines the interface that makes up a Service Broker for CloudFoundry.
// The Broker interface is the combined interface including all of the expected
// functionality of a service broker.
type Broker interface {
Cataloger
Credentialer... |
package main
import (
"fmt"
"github.com/nattaponra/my-go/interface/geometry"
)
//Interface
type Geometry interface {
Area() float64
Perim() float64
}
func Measure(g Geometry) {
fmt.Println(g)
fmt.Println("Area:", g.Area())
fmt.Println("Perim:", g.Perim())
}
func main() {
Measure(geometry.Rect{Height: 10, W... |
package command_helpers
import (
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
helm_v3 "helm.sh/helm/v3/cmd/helm"
"helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/chart/loader"
"github.com/werf/logboek"
"helm.sh/helm/v3/pkg/cli"
"helm.sh/helm/v3/pkg/downloader"
"helm.sh/helm/v3/pkg/getter"
)
type Bui... |
package main
import (
"strings"
"github.com/therecipe/qt/core"
"github.com/therecipe/qt/gui"
"github.com/therecipe/qt/sql"
)
type CustomSqlModel struct {
*sql.QSqlQueryModel
}
func newCustomSqlModel(p *core.QObject) *CustomSqlModel {
var model = &CustomSqlModel{sql.NewQSqlQueryModel(p)}
mod... |
package session
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestSessionStore(t *testing.T) {
Convey(`Testing the Session Store`, t, func() {
s := NewStore()
s.Delete("foo")
s1, existed := s.GetOrNew("foo")
So(existed, ShouldBeFalse)
So(s1.Name(), ShouldEqual, "foo")
var s... |
package main
import "fmt"
func main() {
m := make(map[string]int)
m["k1"] = 7
m["k2"] = 71
fmt.Println("map:", m)
fmt.Println("k1 value:", m["k1"])
}
|
package lru
type Cell struct {
Key interface{}
Value interface{}
}
type ILRU interface {
Get(key interface{}) interface{}
Set(c Cell)
QueueLen() int
}
|
// Copyright 2015-2018 trivago N.V.
//
// 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 main
import (
"fmt"
"github.com/zdq0394/algorithm/base/queue"
)
func main() {
q := queue.NewQueue()
q.Add(1)
q.Add(2)
q.Add(3)
var v int
var e error
v, e = q.Peek()
fmt.Println(v, e)
q.Remove()
v, e = q.Peek()
fmt.Println(v, e)
fmt.Println("Length:", q.Length())
}
|
package main
import (
"math/rand"
"os"
"time"
"github.com/xmwilldo/edge-health/cmd/app-health/app"
"github.com/xmwilldo/edge-health/pkg/app-health-daemon/util"
"k8s.io/component-base/logs"
)
func main() {
rand.Seed(time.Now().UnixNano())
ctx, _ := util.SignalWatch()
command := app.NewAppHealthCommand(ctx)... |
package cloud
import (
"testing"
client "github.com/devspace-cloud/devspace/pkg/devspace/cloud/client/testing"
config "github.com/devspace-cloud/devspace/pkg/devspace/cloud/config/testing"
"github.com/devspace-cloud/devspace/pkg/devspace/cloud/config/versions/latest"
"github.com/devspace-cloud/devspace/pkg/util/... |
// Copyright 2021-present Open Networking Foundation.
//
// 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 main Contains the main() function of the Server and is the entry of the Programm
package main
|
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//658. Find K Closest Elements
//Given a sorted array, two integers k and x, find the k closest elements to x in the array. The result should also be s... |
package pdu
import (
"fmt"
"strconv"
"time"
)
// Time see SMPP v5, section 4.7.23.4 (132p)
type Time struct{ time.Time }
func (t *Time) From(input string) (err error) {
t.Time = time.Time{}
if len(input) == 0 {
return
}
parts, symbol := fromTimeString(input)
if !(symbol == '+' || symbol == '-') {
err = E... |
package handlers
import (
"github.com/EgorLyutov/Inventor/models"
"github.com/EgorLyutov/Inventor/tools"
"gopkg.in/mgo.v2"
"html/template"
"log"
"net/http"
"strconv"
"strings"
"time"
"github.com/gorilla/context"
)
func HandleServer(args map[string]interface{}, id string, w http.ResponseWriter, r *http.Reque... |
package routers
import (
"key-value/lib/ws"
"encoding/json"
"log"
"fmt"
)
func createRequestHandler(strategy RequestStrategy) requestHandler {
return func(request Request) Response {
value, err := strategy(request)
errorMsg := ``
if err != nil {
errorMsg = err.Error()
}
return Response{
Success:... |
/*
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... |
//
// Copyright (C) 2019-2021 vdaas.org vald team <vald@vdaas.org>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless requir... |
package models
type Entry struct {
ID int `db:"entry_id"`
User
Slug string `db:"slug"`
DisplayName string `db:"display_name"`
}
|
package config
type NodeEvents struct {
Enabled *bool `json:"enabled,omitempty"`
}
func (e NodeEvents) IsEnabled() bool {
return e.Enabled == nil || *e.Enabled
}
|
package main
import (
"io"
"os"
"path/filepath"
)
type teeFileReader struct {
r io.ReadCloser
f *os.File
}
// TeeReader returns a Reader that writes to the named file what it reads from
// r. All reads from r performed through it are matched with corresponding
// writes. There is no internal buffering - the wri... |
package abclientstate
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/volatiletech/authboss/v3"
)
func TestGetCookieState(t *testing.T) {
t.Parallel()
var c CookieState = map[string]string{"hello": "world"}
val, ok := c.Get("hello")
if !ok {
t.Error("could not get co... |
package http
// -> username string
import (
"github.com/gin-gonic/gin"
"github.com/hokora/bank/util"
"net/http"
)
func (s *Server) createAccount(ctx *gin.Context) {
username := ctx.GetString("username")
pw := util.NewPacketWriterNoLen(len(username) + 1)
pw.AppendString(username)
success, _, err := s.m... |
package structs
type AppUserUpdate struct {
Avatar string `json:"avatar"`
UpdatedAt string `json:"updated_at"`
}
|
// Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
package coretypes
import (
"bytes"
"errors"
"fmt"
"io"
"strings"
"github.com/mr-tron/base58"
)
// ContractIDLength size of the contract ID in bytes
const ContractIDLength = ChainIDLength + HnameLength
// ContractID global identifier of th... |
package day5
import (
"testing"
"github.com/kdeberk/advent-of-code/2019/internal/utils"
)
const part1Answer = 13978427
const part2Answer = 11189491
func TestPart1(t *testing.T) {
program, _ := utils.ReadProgram("../../input/5.txt")
machine := utils.MakeMachine("day5", program)
answer, _ := part1(machine)
if ... |
// Copyright 2014-2015 The DevMine 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 repotool is able to fetch information from a source code repository.
// Typically, it can get all commits, their authors and commiters and ... |
package lib
import (
"github.com/dproject21/di_container_test/sampleinterface"
"github.com/fgrosse/goldi"
)
var container *goldi.Container
func CreateContainer() {
registry := goldi.NewTypeRegistry()
RegisterTypes(registry)
// create a new container when your application loads
config := map[string]interface{... |
package v5
import (
"encoding/json"
"net/http"
"reflect"
"strings"
)
// ByID is "id" constant to use as `by` property in methods
const ByID = "id"
// ByExternalId is "externalId" constant to use as `by` property in methods
const ByExternalID = "externalId"
// Client type
type Client struct {
URL string
... |
/*
Copyright IBM Corporation 2020
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... |
// +build windows
package main
const (
// identifies if test suite is running on a unix platform
isUnixCli = false
)
|
package main
import (
"fmt"
"io"
"log"
"os"
"strings"
"github.com/biogo/hts/bam"
"github.com/biogo/hts/sam"
)
func DecodeQual(qual []byte) string {
squal := make([]string, 0, len(qual))
for pos := range qual {
squal = append(squal, string(qual[pos]+33))
}
return strings.Join(squal, "")
}
f... |
package x
import (
"errors"
"fmt"
"ms/sun/shared/base"
)
//TODO: WE MUST separate int from string to not let empty string "" from preloading or loading and inserting into caches
// Action - PRIMARY
// Action - ActorUserId
// Blocked - PRIMARY
// Comment - PRIMARY
//field//field//field
///// Generated from in... |
/*
Fast Random Generator for use from single threaded data injection code. It is
especially useful if you need to load test a service while generating random
data. It that case, the random generator locks can become a bottleneck.
*/
package random // import "fluux.io/random"
import (
"math/rand"
"strconv"
"strings"... |
package igapi
import (
"github.com/lemkova/instagramapi-go/signature"
"github.com/lemkova/instagramapi-go/igreq"
u "net/url"
"strings"
"fmt"
"log"
)
const (
uagent = "Instagram 9.2.0 Android (18/4.3; 320dpi; 720x1280; Xiaomi; HM 1SW; armani; qcom; en_US)"
challange... |
package ui
import (
"fmt"
"strings"
"github.com/chzyer/readline"
"github.com/kr/text"
"github.com/manifoldco/torus-cli/prefs"
)
// enableProgress is whether progress events should be displayed
var enableProgress = false
// enableHints is whether hints should be displayed
var enableHints = false
// Init prepa... |
package main
import (
"bytes"
"fmt"
"unicode/utf8"
)
type tokenClass string
const (
tkObjStart tokenClass = "{"
tkObjEnd tokenClass = "}"
tkArrStart tokenClass = "["
tkArrEnd tokenClass = "]"
tkDot tokenClass = "."
tkLiteral tokenClass = "LITERAL"
tkRawLiteral tokenClass = ":LITERAL"
... |
// 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 main
import (
"fmt"
"os"
"strings"
"github.com/giantswarm/conair/btrfs"
"github.com/giantswarm/conair/nspawn"
)
var (
flagBind stringSlice
flagSnapshot stringSlice
cmdRun = &Command{
Name: "run",
Summary: "Run a container",
Usage: "[-bind=S] [-snapshot=S] <image> [<container>]",
... |
package todolist
import (
"bufio"
"fmt"
"io"
"os"
"os/user"
"strconv"
"strings"
)
type ConfigStore struct {
FileLocation string
Loaded bool
}
type Config struct {
Aliases map[string]string
Reports map[string]map[string]string
Views ... |
package cmd
import (
"github.com/bitrise-io/go-utils/log"
"github.com/fehersanyi/microtis-cli/stargate"
"github.com/spf13/cobra"
)
// jumpCmd represents the jump command
var jumpCmd = &cobra.Command{
Use: "jump",
Short: "jump will hehe, jump to a given directory for you",
Long: ``,
Run: func(cmd *cobra.Comm... |
// Copyright 2016 Etix Labs
//
// 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... |
/*
Auther :chenglinguang
date: 2019-01-11
*/
package main
import (
"os/exec"
//"log"
"io/ioutil"
"fmt"
"strings"
)
func main(){
myFolder := "/etc/fluent"
var fileConf map[int]string
fileConf = listFile(myFolder)
//start the fluentd process in this folder
for _,file := range(fileCo... |
package main
import (
"bytes"
"fmt"
"github.com/gorilla/websocket"
"log"
"net/http"
"time"
)
type Client struct {
hub *Hub
conn *websocket.Conn
id string
send chan []byte
}
const (
// Time allowed to write a message to the peer.
writeWait = 10 * time.Second
// Time allowed to read the next pong mess... |
// Copyright © 2018 Sunface <CTO@188.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 applicable law or ... |
package plan
import (
"github.com/kainosnoema/terracost-cli/prices"
"github.com/kainosnoema/terracost-cli/terraform"
)
// Resource maps a Terraform resource to AWS pricing
type Resource struct {
Address string
Action string
Before prices.ByID
After prices.ByID
}
// Calculate takes a TF plan, fetches AWS pr... |
package main
import "fmt"
func main() {
// 声明一个变量并初始化
var a = "RUNOOB"
fmt.Println(a)
// 没有初始化就为零值
var b int
fmt.Println(b)
// bool 零值为 false
var c bool
fmt.Println(c)
d := "1"
p := &d
fmt.Println(d)
fmt.Println(*p)
*p = "3"
fmt.Println(*p)
} |
package qa
import (
"context"
"github.com/go-kit/kit/endpoint"
"qa/pkg"
)
type Endpoints struct {
ReadQuestionEndpoint endpoint.Endpoint
ReadAllQuestionsEndpoint endpoint.Endpoint
CreateQuestionEndpoint endpoint.Endpoint
UpdateQuestionEndpoint endpoint.Endpoint
DeleteQuestionEndpoint e... |
package gravity
import (
"github.com/althea-net/cosmos-gravity-bridge/gravity/x/gravity/keeper"
"github.com/althea-net/cosmos-gravity-bridge/gravity/x/gravity/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)
func handleMsgCreateOrchestratorAddress(ctx sdk.Context, k keeper.Keeper, msg *types.MsgCreateOrchestrator... |
package main
import (
"bufio"
"bytes"
"fmt"
"io"
)
// mp4Reader handles all things related to the buffer.
// It receives an io.ReadSeeker from invoker and reads un-parsed
// data from the latter.
type mp4Reader struct {
readSeeker io.ReadSeeker
b []byte // processing bytes
a *atom // process... |
// Package user contains protobuf types for users.
package user
import (
context "context"
"google.golang.org/protobuf/types/known/structpb"
"github.com/pomerium/pomerium/internal/identity"
"github.com/pomerium/pomerium/pkg/grpc/databroker"
"github.com/pomerium/pomerium/pkg/slices"
)
// Get gets a user from th... |
// Copyright 2020 Torben Schinke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... |
package two_sum
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestTwoSum(t *testing.T) {
nums := []int{2, 7, 11, 15}
target := 9
assert.Equal(t, []int{0, 1}, twoSum(nums, target))
nums = []int{2, 11, 15, 5}
target = 7
assert.Equal(t, []int{0, 3}, twoSum(nums, target))
}
|
package main
import (
"container/heap"
"fmt"
"io/ioutil"
"log"
"math"
"math/rand"
"runtime"
"sync"
"time"
)
/*
n person
2 person dorm rooms
match room-mates to satisfy most requests
p1, p2, ..., pn
slot1, slot2, ..., slotn
slot1 and slot2 -> room1
*/
type roommates [2]int
type selectorFunc func(numPerson... |
// HELPER FUNCTION - Using bytes.Buffer for efficient string concatenation in Go
package helper
import (
"bytes"
)
func Concat(values []string) string {
var b bytes.Buffer
for _, s := range values {
b.WriteString(s)
}
return b.String()
}
|
package main
import "fmt"
func main() {
// 1、byte 类型的默认值为 0, 最大值为255
var ch byte
fmt.Println("ch =", ch)
fmt.Printf("ch = %c, %T\n", ch, ch)
ch = 255
fmt.Println("ch =", ch)
fmt.Printf("ch = %c\n", ch)
// 2、字符使用单引号, 可以直接进行数值计算,以反斜杠开头的字符是转义字符
var a = 'a'
fmt.Println("a = ", a)
fmt.Printf("a = %c\n", a)
f... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//637. Average of Levels in Binary Tree
//Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
/... |
package _429_N_ary_Tree_Level_Order_Traversal
type Node struct {
Val int
Children []*Node
}
func levelOrder(root *Node) [][]int {
var (
ret [][]int
q, tq []*Node
)
if root == nil {
return ret
}
q = append(q, root)
for len(q) > 0 {
tr := []int{}
for _, n := range q {
if n == nil {
conti... |
package pg
import (
"github.com/kyleconroy/sqlc/internal/sql/ast"
)
type RangeTableSample struct {
Relation ast.Node
Method *ast.List
Args *ast.List
Repeatable ast.Node
Location int
}
func (n *RangeTableSample) Pos() int {
return n.Location
}
|
package network
import "github.com/meidoworks/nekoq-api/errorutil"
var _ERROR_CHANNEL_CLOSED = errorutil.New("channel closed <- network <- nekoq-api")
func ErrChannelClosed() error {
return _ERROR_CHANNEL_CLOSED
}
var _ERROR_CHANNEL_QUEUE_NOT_READY = errorutil.New("write queue not ready <- network <- nekoq-api")
... |
package controllers
import (
"fmt"
"github.com/cmsvault/api/logging"
"net/http"
)
func Index() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
fmt.Printf("Params %+v", ctx.Value("params"))
_, err := fmt.Fprint(w, "Not protected!\n")
if err != nil ... |
package main
import (
"fmt"
"strconv"
"strings"
)
func highestProduct(num string, size int) int {
strArr := strings.Split(num, "")
max := 0
for i := 0; i < len(strArr)-size+1; i++ {
product := 1
for j := i; j < i+size; j++ {
num, _ := strconv.Atoi(strArr[j])
product *= num
}
if product > max {
... |
package service
import (
"io"
"net/http"
"os"
humanize "github.com/dustin/go-humanize"
)
type WriteCounter struct {
Total uint64
onProgress func(string)
}
func (wc *WriteCounter) Write(p []byte) (int, error) {
n := len(p)
wc.Total += uint64(n)
wc.onProgress(humanize.Bytes(wc.Total))
return n, nil
}
... |
package wifi
import (
"bylib/bylog"
"bylib/byutils"
"encoding/json"
"fmt"
"github.com/go-cmd/cmd"
"runtime"
"strconv"
"strings"
"time"
)
type ConnResult struct{
Result string `json:"result"`
Message string `json:"message"`
IP string `json:"ip"`
Connect bool `json:"connect"`
}
//ap管理器
type ApManager struc... |
package main
import (
"io/ioutil"
"os"
"strings"
"github.com/UlisseMini/leetlog"
)
func main() {
files, err := ioutil.ReadDir(".")
if err != nil {
leetlog.Fatal(err)
}
padnum := 23
for _, file := range files {
fname := file.Name()
if !strings.HasPrefix(fname, "license_") {
continue
}
newName ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.