text stringlengths 11 4.05M |
|---|
/**
序列最长递增子序列长度
*/
package backTrack
type SubqueryMax struct {
arr []int
cnt int
}
func newSubqueryMax(arr []int, cnt int) *SubqueryMax {
return &SubqueryMax{
arr: arr,
cnt: cnt,
}
}
func (sm *SubqueryMax) getMax(i int) int {
if i == 0 {
return 1
}
var length int
if sm.arr[i] >= sm.arr[i-1] {
lengt... |
package routes
import (
"encoding/json"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
"github.com/winded/tyomaa/backend/db"
"github.com/winded/tyomaa/backend/middleware"
"github.com/winded/tyomaa/backend/util"
"github.com/winded/tyomaa/backend/util/context"
"github.com/winded/tyomaa/sh... |
package main
import (
"io/ioutil"
"os"
"strings"
"text/template"
"github.com/aymerick/douceur/css"
"github.com/aymerick/douceur/parser"
"gopkg.in/alecthomas/kingpin.v3-unstable"
"github.com/alecthomas/chroma/v2"
)
const (
outputTemplate = `package styles
import (
"github.com/alecthomas/chroma/v2"
)
// {... |
package main
import (
"io/ioutil"
"log"
"os"
"testing"
"time"
)
func TestExecute(t *testing.T) {
defer quiet()()
loop := &Loop{}
loop.Commands = Commands{
{Exec: "true"},
}
ok, err := loop.Execute()
if !ok {
t.Error("not ok")
}
if err != nil {
t.Fatal(err)
}
}
func TestExecuteFail(t *testing.T) {... |
/*
* Copyright 2020 The Magma Authors.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
*... |
package libldbrest
import (
"net/http"
"sync/atomic"
)
// An atomic.Value that deals specifically with http.Handlers, and which can act
// as an http.Handler itself by grabbing and running the currently held Handler.
type SwappableHandler struct {
holder atomic.Value
}
func (sh *SwappableHandler) Store(handler ht... |
package h_test
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/josephspurrier/h"
"github.com/stretchr/testify/assert"
)
func TestFResponseOK(t *testing.T) {
mux := http.NewServeMux()
mux.Handle("/", h.F(func(w http.ResponseWriter, r *http.Request) (int, error) {
return http.St... |
package gateway
import (
"errors"
"net/http"
"github.com/aws/aws-lambda-go/events"
)
type APIRouter struct {
tree map[string]ResourceMap
}
var errHandleNotFound = errors.New("handler not found")
type HandlerAPIFunc func(req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error)
type Resource s... |
// Copyright (c) KwanJunWen
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
package estemplate
import "fmt"
// TokenFilterMultiplexer token filter that will emit multiple tokens at the same position, each
// version of the token having bee... |
package hrtime
import (
"time"
)
var nanoOverhead time.Duration
// Overhead returns approximate overhead for a call to Now() or Since()
func Overhead() time.Duration { return nanoOverhead }
// Since returns time.Duration since start
func Since(start time.Duration) time.Duration { return Now() - start }
func calcu... |
package main
import (
"net/http"
_ "net/http/pprof"
"os"
optimizer "github.com/rmanzoku/go-next-image-optimizer"
)
var (
version = "none"
revision = "none"
port = "9900"
imageSrc = ""
)
func init() {
if os.Getenv("PORT") != "" {
port = os.Getenv("PORT")
}
if os.Getenv("IMAGE_SRC") != "" {
imageS... |
package store
/*!
MIT License
Copyright (c) 2016 json-iterator
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, ... |
package rcap
import (
"net/http"
"testing"
)
func TestDefaultRules(t *testing.T) {
rules := defaultHTTPRules()
t.Run("http allowed", func(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
if err := rules.requestIsAllowed(req); err != nil {
t.Error("error occurred, shoul... |
package simulator
import (
"encoding/json"
"log"
"sync"
"time"
"github.com/dbogatov/dac-lib/dac"
)
type transferable interface {
size() int
name() string
}
// CertificateSize ...
const CertificateSize = 734 // TODO http://fm4dd.com/openssl/certexamples.shtm
var globalBandwidthLock = &sync.Mutex{}
var bandwi... |
/*
* @lc app=leetcode id=687 lang=golang
*
* [687] Longest Univalue Path
*
* https://leetcode.com/problems/longest-univalue-path/description/
*
* algorithms
* Easy (35.88%)
* Likes: 1758
* Dislikes: 477
* Total Accepted: 94.1K
* Total Submissions: 259.8K
* Testcase Example: '[5,4,5,1,1,5]'
*
* Giv... |
package calendar
type OtherEvent struct {
Name string
day int
season string
}
var _ Event = (*OtherEvent)(nil)
func NewOtherEvent(name string, day int, season string) *OtherEvent {
return &OtherEvent{Name: name, day: day, season: season}
}
func (e *OtherEvent) Day() int {
return e.day
}
func (e *OtherEve... |
package objects
import (
"fmt"
"github.com/jecolasurdo/marsrover/pkg/spatial"
)
// ErrRoverExpelledFromEnvironment occurs if the rover's underlaying environment
// no longer recognizes the rover as existing.
func ErrRoverExpelledFromEnvironment(rover *Rover) error {
return fmt.Errorf("rover '%v' is no longer reco... |
// http://jan.newmarch.name/go/socket/chapter-socket.html
// http://www.dotcoo.com/golang-net-dome
package main
import (
"bytes"
// "bufio"
"fmt"
"net"
)
func main() {
conn, err := net.Dial("unix", "/tmp/socket")
if err != nil {
panic(err)
}
fmt.Fprintf(conn, "hello server\n")
// data, err := bufio.NewR... |
package stack
import "testing"
func TestFourPronged(t *testing.T) {
var s string
var rs int
// pass
s = "2+3x5-7"
// s = "2+3x5"
// s = "9+3x8/4"
// s = "3x8/4-10"
s = "3x8/4-10+16x8/4"
s = "3x8/4-10+16x3/4"
// fail
s = "3x8/4-10+16x3/4*10-19"
fp := NewFourPronged(s, len(s))
rs = fp.Operate()
t.Logf... |
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package conference
import (
"context"
"fmt"
"regexp"
"strconv"
"strings"
"time"
"chromiumos/tast/common/action"
"chromiumos/tast/errors"
"chromiumos/tast/local/chr... |
package main //linter warns here???
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
func main() {
file, err := os.Open("input.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
horizontal, depth, newDepth, aim := 0, 0, 0, 0
scanner := bufio.NewScanner(file)
for scanner.Scan() {
row := ... |
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package taskmanager contains local Tast tests that exercise task manager.
package taskmanager
|
package buildkit
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"math/rand"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/loft-sh/devspace/pkg/devspace/pipeline/env"
"mvdan.cc/sh/v3/expand"
devspacecontext "github.com/loft-sh/devspace/pkg/devspace/context"
command2 "github.com/lof... |
package models
//Response will be used to structure our http response
type Response struct {
Message string `json:"message"`
Error string `json:"error"`
Data interface{} `json:"data"`
}
|
package utils
import (
"encoding/json"
"errors"
"time"
"github.com/golang/protobuf/proto"
lpb "github.com/xuperchain/xupercore/bcs/ledger/xledger/xldgpb"
bftPb "github.com/xuperchain/xupercore/kernel/consensus/base/driver/chained-bft/pb"
bftStorage "github.com/xuperchain/xupercore/kernel/consensus/base/driver/... |
package registry
import (
"context"
"fmt"
"net/http"
"time"
)
const httpRequestTimeout = time.Second * 10
const userAgent = "dependency locker"
const npmRegistryUrl = "https://registry.npmjs.org"
const pypiRegistryUrl = "https://pypi.python.org/simple"
var cache map[string]bool
func init() {
cache = map[strin... |
package main
import (
"bufio"
"bytes"
"encoding/binary"
"fmt"
"io"
"net"
"os"
)
func main() {
// 服务器IP地址和端口,创建通信套接字
conn, err := net.Dial("tcp", "192.168.3.12:8989")
if err != nil {
fmt.Println("dial failed, err", err)
return
}
defer conn.Close()
// 获取用户键盘输入(stdin),将输入数据发送给服务器
go func(){
for {
... |
/*
Links
* http://wegicel.github.com/1.html
* http://wegicel.github.com/3.html
* http://wegicel.github.com/4.html
* http://wegicel.github.com/5.html
* http://wegicel.github.com/6.html
* http://wegicel.github.com/7.html
* http://wegicel.github.com/9.html
* http://wegicel.github.com/10.html
* http://wegicel.github.com/11... |
// https://programmers.co.kr/learn/courses/30/lessons/43165
package main
func p43165(numbers []int, target int) int {
result := 0
s(0, 0, target, numbers, &result)
return result
}
func s(depth, now, target int, numbers []int, result *int) {
if depth == len(numbers) {
if now == target {
*result++
}
ret... |
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT License was not distributed with this
// file, you can obtain one at https://opensource.org/licenses/MIT.
//
// Copyright (c) DUSK NETWORK. All rights reserved.
package kadcast
import (
"net"
"github.com/dusk-network/dusk-... |
package loader
import (
"bytes"
"os"
"github.com/loft-sh/devspace/pkg/devspace/config/versions/latest"
yaml "gopkg.in/yaml.v3"
)
// Save writes the data of a config to its yaml file
func Save(path string, config *latest.Config) error {
var buffer bytes.Buffer
yamlEncoder := yaml.NewEncoder(&buffer)
yamlEncod... |
package solutions
func partition(head *ListNode, x int) *ListNode {
if head == nil {
return head
}
smaller, greater := &ListNode{0, nil}, &ListNode{0, nil}
left, right := smaller, greater
for head != nil {
if head.Val < x {
left.Next = head
left = left.Next... |
package lib
import (
"io"
"github.com/opentracing/opentracing-go"
"github.com/uber/jaeger-client-go"
"github.com/uber/jaeger-client-go/config"
"github.com/uber/jaeger-client-go/log"
"github.com/uber/jaeger-lib/metrics"
)
func CreateTracer(serviceName string) (opentracing.Tracer, io.Closer, error) {
var cfg co... |
package util
import (
"testing"
)
func TestAverage(t *testing.T) {
var v float64
input := []float64{1, 2, 3}
v = Average(input)
if v != 2 {
t.Error("Expected 2, got ", v)
}
}
func TestCallURL(t *testing.T) {
done := make(chan bool)
go CallURL(done)
v := <- done
if !v {
t.Error("Expect... |
package tgo
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"regexp"
"time"
)
// ConnectionsResponse holds the response from `GET /network/connections`
type ConnectionsResponse struct {
Incoming bool `json:"incoming"`
PeerID string `json:"peer_id"`
IDPoint struct {
Address string `json... |
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"path"
"strings"
"text/template"
"github.com/gorilla/mux"
_ "github.com/lib/pq"
"github.com/delba/requestbin/model"
"github.com/jinzhu/gorm"
)
var db gorm.DB
func handle(err error) {
if err != nil {
panic(err)
}
}
func init() {
url := os.Gete... |
package skiplist
import (
"fmt"
"math/rand"
"time"
)
var R = rand.New(rand.NewSource(time.Now().UnixNano()))
type Value interface {
Less(Value) bool
Index() int
}
type NodeValue struct {
Index int
Data interface{}
}
type Node struct {
Value Value
level int
Left *Node
Right *Node
Top *Node
Bott... |
package models
import(
"encoding/json"
)
/**
* Type definition for Type29Enum enum
*/
type Type29Enum int
/**
* Value collection for Type29Enum enum
*/
const (
Type29_KREGULAR Type29Enum = 1 + iota
Type29_KRPO
)
func (r Type29Enum) MarshalJSON() ([]byte, error) {
s := Type29... |
package animo
import (
"context"
"errors"
"github.com/go-kit/kit/endpoint"
)
type ResolveProfilesAliasesRequest struct {
ProfilesAliases []string `json:"profilesAliases"`
}
type ResolveProfilesAliasesResponse struct {
ProfilesIds []string `json:"profilesIds"`
Err string `json:"err,omitempty"`
}
typ... |
package zoidberg
type Discoverer interface {
Discover() (Discovery, error)
}
type Discovery struct {
Balancers []Balancer `json:"balancers"`
Apps Apps `json:"apps"`
}
|
package unimatrix
func NewArtifactsOperation(realm string) *Operation {
return NewRealmOperation(realm, "artifacts")
}
|
/*
Copyright 2015 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 in writing, soft... |
/*
* Copyright (c) 2018 WSO2 Inc. (http:www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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/license... |
/*
* Wager service APIs
*
* APIs for a wager system
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package controllers
import (
"github.com/ryannguyen89/wager-service/business"
"github.com/ryannguyen89/wager-service/models"
"github.com/ryannguyen89/wager-service... |
/*
* aggro
*
* Functions for outputting prefix lists in various formats
*
* Copyright (c) 2017 Noora Halme - please see LICENSE.md
*
*/
package main
import (
"fmt"
)
// output prefix list in Linux iptables format
func outputIptables(name string, prefixList *[]string) {
fmt.Printf("iptables -F %s-ingress\... |
package model
// Signature Хранит изображение росписи
type Signature struct {
// Code Закодированное изображение
Code int64 `bson:"signature" json:"signature"`
}
|
// Copyright 2018 Drone.IO 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 ... |
package registry
import (
pb "github.com/raviupreti85/naiveDB/registry/proto"
"github.com/raviupreti85/naiveDB/ring"
"golang.org/x/net/context"
)
type RegistryServer struct {
registry *Registry
}
func NewRegistryServer() *RegistryServer {
return &RegistryServer{registry: NewEmptyRegistry()}
}
func (r *Registry... |
package B
import "github.com/gofiber/fiber/v2"
func two(ctx *fiber.Ctx) error {
return ctx.SendString("B, 2 👋!")
}
|
package for_c_lang
/*
#include <stdio.h>
static void SayHello(const char *name){
puts(name);
}
*/
import "C"
func BasicApp(){
C.SayHello(C.CString("Hello,World!\n"))
} |
package main
import (
"github.com/1and1/oneandone-cloudserver-sdk-go"
"github.com/codegangsta/cli"
)
var privateNetOps []cli.Command
func init() {
pnIdFlag := cli.StringFlag{
Name: "id, i",
Usage: "ID of the private network.",
}
pnNameFlag := cli.StringFlag{
Name: "desc, d",
Usage: "Description of the... |
package block
import (
"time"
)
var (
blocks = []*BlockChain{genesisBlock}
)
var genesisBlock = &BlockChain{
Index: 0,
PrevBlockChainHash: []byte(""),
Timestamp: 1465154705,
Data: []byte(""),
Hash: []byte("0000001ecea26a0894fbd46de4a2217a18e1c7ab965ca6b8b2b57cb62cbceeec"),
Nonce: ... |
package ffmpeg
//#include <libavutil/pixfmt.h>
import "C"
type ColorPrimaries int
const (
ColorPrimaries_Unspecified = 2
)
func (cp ColorPrimaries) ctype() C.enum_AVColorPrimaries {
return (C.enum_AVColorPrimaries)(cp)
}
|
// +build !android
package main
import (
"flag"
"fmt"
"log"
"runtime"
"strconv"
"strings"
"github.com/tideland/goas/v2/loop"
glfw "github.com/go-gl/glfw3"
"github.com/remogatto/mandala"
)
func main() {
runtime.LockOSThread()
verbose := flag.Bool("verbose", false, "produce verbose output")
debug := fla... |
package docs
import "io/ioutil"
var w = ioutil.Discard
type House struct {
Frontdoor Door // aggregation
Windows []*Window // composition
}
func (me *House) Rooms() int { return 0 }
type Door struct {
Material string
}
func (me *Door) Materials() []string {
return []string{}
}
type Window struct {
Mo... |
package main
import "fmt"
func main() {
var x interface{}
var y interface{} = []int{3, 5}
_ = x == x
_ = x == y
fmt.Printf("%T", x)
//_ = y == y // panic 两个比较值的动态类型为同一个不可比较类型。
}
|
// Package store defines an interface for storing metrics to a store,
// such as redis, and it also implments the RedisStore, which is the
// required implmementation for the demo. Note we abstract the store
// into an interface so we can run unit tests without having to actually
// store to redis, among other reasons... |
package game
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestValidateStep(t *testing.T) {
testCases := []struct {
desc string
prevStep Event
nextStep Event
expected bool
}{
{
desc: "Left != Right",
prevStep: Left,
nextStep: Right,
expected: false,
},
{
des... |
/*
Copyright 2018 Bitnine Co., Ltd.
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, softwar... |
package utils
// FindInSlice finds an integer element in a slice passed by
func FindInSlice(s []int, element int) bool {
for _, n := range s {
if element == n {
return true
}
}
return false
}
|
// Copyright 2019 - 2022 The Samply Community
//
// 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 main
import (
"log"
"os"
"strconv"
"time"
)
var logfile *os.File
const logDir string = "logs/"
func initLogger() {
ld := dirPrefix + logDir
if _, err := os.Stat(ld); os.IsNotExist(err) {
os.Mkdir(ld, 0750)
}
var err error
time := strconv.Itoa(int(time.Now().Unix()))
logfile, err = os.OpenFile(ld... |
package schedule
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/coredns/coredns/core/dnsserver"
"github.com/coredns/coredns/plugin"
"github.com/mholt/caddy"
)
func init() {
caddy.RegisterPlugin("schedule", caddy.Plugin{
ServerType: "dns",
Action: setup,
})
}
func setup(c *caddy.Controller) e... |
package fuse
import (
"os"
"strings"
"time"
"github.com/minio/minio-go/v7"
//minio "github.com/minio/minio-go"
)
func NewFileInfo(objectInfo minio.ObjectInfo) os.FileInfo {
return &fileInfo{objectInfo: objectInfo}
}
type fileInfo struct {
objectInfo minio.ObjectInfo
}
func (f *fileInfo) Name() string {
ret... |
// +build stats
package parser_test
import (
"encoding/json"
"fmt"
"github.com/bytesparadise/libasciidoc/pkg/parser"
"github.com/bytesparadise/libasciidoc/pkg/types"
. "github.com/bytesparadise/libasciidoc/testsupport"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("paragraphs",... |
// GENERATED FILE -- DO NOT EDIT
//
package k8smeta
import (
"istio.io/istio/galley/pkg/config/meta/schema/collection"
)
var (
// K8SAppsV1Deployments is the name of collection k8s/apps/v1/deployments
K8SAppsV1Deployments = collection.NewName("k8s/apps/v1/deployments")
// K8SCoreV1Endpoints is the name of coll... |
package notify
import (
"bytes"
"fmt"
"html/template"
"time"
"github.com/fanaticscripter/EggContractor/api"
"github.com/fanaticscripter/EggContractor/util"
)
const _contractMessageTextTmpl = `
{{- define "rewards" -}}
{{- range .}}
- <b>{{.Goal | numfmtwhole}}</b>: {{.Type}} {{.Name}} x{{.Count}};
{{- end}}
{{... |
package cmd
import (
"strconv"
"github.com/spf13/cobra"
"github.com/fanaticscripter/EggContractor/util"
)
var _unitsCommand = &cobra.Command{
Use: "units",
Short: "Print a table of units (order of magnitudes)",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
table := [][]string{
{"... |
package product_attribute_category
import (
"inventory-service/modules/product_attribute_category/dao"
"inventory-service/modules/product_attribute_category/service"
)
func Init() {
dao.Init()
service.Init()
}
|
package zen
import (
"context"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"net/http"
"reflect"
"regexp"
"runtime"
"strconv"
"time"
log "github.com/sirupsen/logrus"
)
const (
inputTagName = "form"
validTagName = "valid"
validMsgName = "msg"
)
// Headers
const (
HeaderAcceptEncoding ... |
package controllers
import (
"christopher/helpers"
"christopher/models"
"encoding/json"
"github.com/gin-gonic/gin"
"log"
"strconv"
)
type MerchantGallerySigle map[string]interface{}
type MerchantGallery struct {
Id int64 `json:"id, Number"`
Photo_url string `json:"photo_url"`
Merchant_uid strin... |
// +build local
package main
import (
gwv "../../gwv"
"path/filepath"
"simonwaldherr.de/go/golibs/gopath"
)
func main() {
dir := gopath.Dir()
HTTPD := gwv.NewWebServer(8080, 60)
HTTPD.ConfigSSL(4443, filepath.Join(dir, "..", "ssl.key"), filepath.Join(dir, "..", "ssl.cert"), true)
HTTPD.URLhandler(
gwv.Favi... |
package bootstrap
import (
"encoding/json"
"fmt"
"io/ioutil"
"ktmall/config"
"ktmall/routes"
"strings"
"github.com/labstack/echo/v4"
)
func RunServer() {
e := SetupServer()
e.Logger.Fatal(e.Start(config.String("APP.PORT")))
}
func SetupServer() *echo.Echo {
e := echo.New()
e.Debug = config.IsDev()
e.Hi... |
// Copyright 2014 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, ... |
/**
Go语言中同时有函数和方法. 一个方法就是一个包含了接受者的函数, 接受者可以是命名类型或结构体类型的一个值或者是一个指针.
func (variable_name variable_data_type) function_name() [return_type] {
// 函数体
}
**/
package main
import "fmt"
// 结构体
type Circle struct {
radius float64
}
func main() {
var c1 Circle
c1.radius = 10.00
fmt.Println("Area of Clircle(c1)=", c1.g... |
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package pb_test
import (
fmt "fmt"
"reflect"
"sort"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"storj.io/common/pb"
)
func TestCompatibility(t *testing.T) {
// when these fail, the X and XSigning definitions are ou... |
// https://programmers.co.kr/learn/courses/30/lessons/12969
package main
import (
"fmt"
"strings"
)
func p12969() {
var a, b int
fmt.Scan(&a, &b)
for i := 0; i < b; i++ {
fmt.Println(strings.Repeat("*", a))
}
}
|
package logif
import (
"log"
"os"
"testing"
)
func TestExample(t *testing.T) {
log.SetOutput(os.Stdout)
Debugf("hello %s", "debug")
Infof("hello %s", "info")
Warningf("hello %s", "warning")
Errorf("hello %s", "error")
DefaultLogger.Debugf("hello %s", "dl debug")
DefaultLogger.Infof("hello %s", "dl info")
... |
// Copyright (C) 2017 Google 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 t... |
package fsjobqueue
import (
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
)
func uuidList(t *testing.T, strs ...string) []uuid.UUID {
var err error
ids := make([]uuid.UUID, len(strs))
for i, s := range strs {
ids[i], err = uuid.Parse(s)
require.NoError(t, err)
}
return ids
}
f... |
package logger
import (
"errors"
"fmt"
"io"
"os"
"github.com/dmitryt/otus-golang-hw/hw12_13_14_15_calendar/internal/config"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
var ErrFileLog = errors.New("cannot setup file log")
func getLogLevel(str string) zerolog.Level {
switch str {
case "error":
re... |
package main
import "fmt"
func ExampleTransformLine() {
fmt.Println(transformLine("/dev/grid/node-x1-y10 90T 71T 19T 78%"))
// Output:
// [1 10 90 71 19 78%]
}
|
package server
import (
"log"
"net/http"
)
type closeHandler struct {
quit chan<- bool
logger *log.Logger
}
func (closeHandler *closeHandler) ServeHTTP(respWriter http.ResponseWriter, req *http.Request) {
closeHandler.logger.Println("Closing server.")
closeHandler.quit <- true
}
|
package BLC
import (
"github.com/boltdb/bolt"
"log"
"fmt"
"time"
"math/big"
)
type BlockChainIterator struct {
currentHash []byte
db *bolt.DB
}
func (blockChain *BlockChain)Iterator() *BlockChainIterator {
return &BlockChainIterator{blockChain.tip, blockChain.db}
}
func (iter *BlockChainIterator) Next() *... |
package main
type a interface {
get() string
}
// cannot define another get method as method
// overloading is not allowed in go.
type b interface {
a
put(string)
}
type impl struct {}
func (i impl) put(s string) {
}
func (i impl) get() string {
return ""
}
func main() {
var x impl
var y b
y = x
y.get()
... |
package cmd
import (
"fmt"
"github.com/spf13/cobra"
"github.com/xr-hui/nox/pkg/template"
)
var (
// Used for flags
templateFlag string
generatorCmd = &cobra.Command{
Use: "generate",
Short: "Auto generate codes follow template settings",
Run: func(cmd *cobra.Command, args []string) {
tmpl, err := t... |
package main
import "strings"
// Leetcode 395. (medium)
func longestSubstring(s string, k int) (res int) {
if s == "" {
return
}
cnt := [26]int{}
for _, b := range s {
cnt[b-'a']++
}
split := byte(0)
for i, c := range cnt {
if c > 0 && c < k {
split = byte('a' + i)
break
}
}
if split == 0 {
... |
package main
import (
"fmt"
"math"
"os"
)
type vector struct{ x, y, z float64 }
func (v vector) add(w vector) vector {
return vector{v.x + w.x, v.y + w.y, v.z + w.z}
}
func (v vector) sub(w vector) vector {
return vector{v.x - w.x, v.y - w.y, v.z - w.z}
}
func (v vector) scale(m float64) vector {
return vect... |
package main
import (
"bufio"
"compress/gzip"
"container/list"
"flag"
"fmt"
"math"
"os"
"strconv"
"strings"
)
const LIMIT1 = 10
const STEP1 = 100
const LIMIT2 = 1000000
const MAX_SCORE = 150000.0
func main() {
action := flag.String("a", "", "action")
limit := flag.Int("n", 1000, "number of imported image... |
package retrievable
import (
"google.golang.org/appengine/datastore"
)
// IntID is a shortcut type that can be embeded in another struct to fulfil
// the KeyRetrievable interface easily in the most common case.
type IntID int64
func (i *IntID) StoreKey(key *datastore.Key) {
*i = IntID(key.IntID())
}
// StringID i... |
package main
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func addOneRow(root *TreeNode, v int, d int) *TreeNode {
if root == nil {
return root
}
if d == 1 {
root = &TreeNode{Val: v, Left: root}
} else if d == 2 {
L, R := root.Left, root.Right
root.Left = &TreeNode... |
package main
import (
"fmt"
"go-design-pattern/creational-pattern/singleton"
)
func CallSingletonWithLock() {
for i := 0; i < 10; i++ {
go singleton.GetDBInstanceWithLock()
}
fmt.Scanln()
}
func CallSingletonWithOnce() {
for i := 0; i < 10; i++ {
go singleton.GetDBInstanceWithOnce()
}
fmt.Scanln()
}
|
// Copyright © 2020 Weald Technology Trading
// 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 a... |
package main
import (
"fmt"
"os"
"os/exec"
"runtime"
//"time"
//"bufio"
//"log"
//"os"
)
var clear map[string]func()
func init(){
clear = make(map[string]func()) // proses instalasi
clear ["linux"] = func() {
cmd := exec.Command("clear") // contoh di linux, sudah ditest bung
cmd.Stdout = os.Stdout... |
package main
// TODO 交互功能,但是clinet退出会报错
import (
// "bufio"
"fmt"
"net"
"strings"
)
func handleErr(err error) {
if err != nil {
fmt.Println(err)
panic(err.Error())
}
}
func main() {
ls, err := net.Listen("tcp", "0.0.0.0:20000")
handleErr(err)
for {
conn, er... |
package db
import (
"net/url"
"time"
"github.com/go-redis/redis"
"github.com/sirupsen/logrus"
)
type Redis struct {
engine *redis.Client
}
func (r *Redis) Open(_url string) {
redisUrl, err := url.Parse(_url)
if err != nil {
logrus.Error(err)
}
redisPassword, _ := redisUrl.User.Password()
redisOptions :=... |
package config
import (
"github.com/golang/glog"
"gopkg.in/yaml.v2"
"io/ioutil"
"path/filepath"
"time"
)
type Config struct {
Agent struct {
ListenAddr string `yaml:"listen_addr"`
MonitorInterval time.Duration `yaml:"monitor_interval"`
CleanupTimer time.Duration `yaml:"cleanup_t... |
package main
import (
"crd/pkg/apis/crd.com/v1alpha1"
cpclientset "crd/pkg/client/clientset/versioned"
"github.com/tamalsaha/go-oneliners"
crdapi "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
crdclientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
metav1 "k8s.io/apimachiner... |
package inetd
import (
"io"
"time"
)
// Echo (RFC 862)
func Echo(rw io.ReadWriter) {
buf := make([]byte, 1024)
for {
n, _ := rw.Read(buf)
rw.Write(buf[:n])
}
}
// Discard (RFC 863)
func Discard(rw io.ReadWriter) {
buf := make([]byte, 1024)
for {
rw.Read(buf)
}
}
// Daytime (RFC 867)
func Daytime(rw io... |
package list
// Stack 栈
type Stack struct {
l []interface{}
}
// NewStack 创建栈
func NewStack(cap int) *Stack {
l := make([]interface{}, 0, cap)
return &Stack{l}
}
// Destory 销毁
func (s *Stack) Destory() {
s.l = nil
}
// Len 栈长
func (s *Stack) Len() int {
return len(s.l)
}
// Top 返回栈顶
func (s *Stack) Top() inte... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.