text stringlengths 11 4.05M |
|---|
package pair
import (
"log"
"testing"
)
const url = "tcp://127.0.0.1:600"
var tGlobal *testing.T
var messages chan string
var messages2 chan string
func TestPair(t *testing.T) {
tGlobal = t
messages = make(chan string)
messages2 = make(chan string)
var nodePairListener Node
var nodePairConnection Node
err... |
package pathways
import (
"fmt"
"html/template"
"net/http"
"path"
"strings"
)
type Service struct {
root string
routes []*Route
defaultAction http.Handler
templateRoot string
}
func NewService(root string) *Service {
root = strings.TrimRight(root, "/") + "/"
return &Service{
root: ... |
package routehandlers
type RedisAppHandler struct {
statsHandler *StatsHandler
}
type StatsHandler struct {
genderRoleHandler *GenderRoleHandler
studentCountHandler *StudentCountHandler
graduatesCountHandler *GraduatesCountHandler
programCostHandler *ProgramCostHandler
employersHandler ... |
package http
import (
"net/http"
"github.com/anfelo/bookstore_oauth-api/src/services"
"github.com/anfelo/bookstore_utils/errors"
"github.com/anfelo/bookstore_oauth-api/src/domain/accesstoken"
"github.com/gin-gonic/gin"
)
// AccessTokenHandler access token http handler interface
type AccessTokenHandler interfac... |
package main
import "fmt"
import "time"
func worker(id int, jobs <-chan int, results chan<- int) {
// waiting for job
for job := range jobs {
fmt.Println("worker ", id, "start job ", job)
time.Sleep(time.Second)
fmt.Println("worker ", id, "finish job", job)
results <- job
}
}
func main() {
jobs := make(... |
package word
import (
"fmt"
"testing"
"github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/02/02-code-finished/quote"
)
func TestCount (t *testing.T) {
n := Count("One two three four five six")
if n != 6 {
t.Error("Got", n , "expected 6")
}
}
func TestUseCount(t *testing.T) {
m := ... |
package robo
import "context"
// DFSer is used to perform and hold the state of a Depth First Search with an optional Robot which will follow the path generated
type DFSer struct {
r Robot
visited VisitMap
scanner Scanner
}
// recursiveDFS performs a recursive Depth-first search while moving the robot aroun... |
package main
import (
"reader/Reader-Golang/APP/ui"
"reader/Reader-Golang/APP/init"
"reader/Reader-Golang/APP/Model"
)
func main() {
StartTable()
defer initdb.MYSQLORM.Close()
//api_server.New().Start()
ui.New().Start()
}
func StartTable() {
initdb.MYSQLORM.AutoMigrate(&Model.Reader{})
} |
package introspectionfilter
import (
"context"
"sort"
"strings"
"github.com/99designs/gqlgen/graphql"
"github.com/99designs/gqlgen/graphql/introspection"
)
type SortPlugin struct{}
func (SortPlugin) ExtensionName() string {
return "IntrospectionSort"
}
func (SortPlugin) Validate(schema graphql.ExecutableSchem... |
package ironmq
import (
"fmt"
"strings"
"time"
"github.com/iron-io/iron_go3/api"
"github.com/iron-io/iron_go3/mq"
"gopkg.in/queue.v1"
"gopkg.in/queue.v1/internal"
"gopkg.in/queue.v1/memqueue"
"gopkg.in/queue.v1/processor"
)
type Queue struct {
q mq.Queue
opt *queue.Options
memqueue *memqueue... |
// Copyright 2011 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package sharded_counter
// [START struct]
type Counter struct {
Count int
}
// [END struct]
|
package _5_Longest_Palindromic_Substring
var location, maxLength int
func longestPalindrome(s string) string {
location, maxLength = 0, 0
l := len(s)
if l < 2 {
return s
}
for i := 0; i < l-1; i++ {
extendPalindrome(s, i, i)
extendPalindrome(s, i, i+1)
}
return string(s[location : location+maxLength])
}
... |
package util
import (
"io/ioutil"
"os"
"path/filepath"
"runtime"
"github.com/inconshreveable/log15"
"github.com/k0kubun/pp"
)
// GenWorkers generate workders
func GenWorkers(num int) chan<- func() {
tasks := make(chan func())
for i := 0; i < num; i++ {
go func() {
for f := range tasks {
f()
}
}... |
package load_balance
import (
"fmt"
"testing"
"time"
)
func TestRoundRobin(t *testing.T) {
lb := NewRoundRobin([]*Server{
{"10.11.0.1", 2233}, {"10.11.0.5", 2233}, {"10.11.0.9", 2235},
})
for i := 0; i < 10; i++ {
go func() {
s := lb.GetServer()
fmt.Pri... |
package codec
import (
"fmt"
"github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/address"
"github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/balance"
"github.com/iotaledger/wasp/packages/coretypes"
"github.com/iotaledger/wasp/packages/hashing"
)
func Encode(v interface{}) []byte {
switch... |
package main
import ()
type Player struct {
Id int `json:"id"`
Nick string `json:"nick"`
}
/**
* Data access interface for the player.
*/
type PlayerService interface {
Create(nick string) *Player
Update(id int, nick string) *Player
List() []*Player
Find(nick string) *Player
Get(id int) *Player
}
/**
... |
/*
Package socks provides SOCKS server framework.
Features:
* SOCKS4, SOCS4a, SOCKS5 protocols.
* Username/password authentication.
* CONNECT command (BIND and UDP ASSOCIATE is not supported).
* Graceful stop (thanks to github.com/cybozu-go/well package).
*/
package socks
|
package glog
import (
"fmt"
"os"
)
func Example() {
// Remove any existing backends
ClearBackends()
// Add a backend
SetBackend("default", // Backend name
NewWriterBackend(
os.Stderr, // Write to stderr
"", // Empty/unspecified module
Debug, // Debug-level and above records will be logge... |
package main
import (
"fmt"
"sort"
)
const processing int = 4
func walkNodes2(chosen node, nodemap *map[string]int, nodes map[string]*node) {
//array of workers, with how long until they are free..
//for example scenario
timeTillWorkerFree := []int{0, 0}
//for real data
//timeTillWorkerFree := []int{0, 0, 0... |
package lib
import "fmt"
func Sum(a float64, b float64) float64 {
var total = a + b
fmt.Printf("Sum(%v, %v) = %v\n", a, b, total)
return total
}
|
package pgsql
import (
"database/sql"
"database/sql/driver"
"strconv"
)
// Int2ArrayFromIntSlice returns a driver.Valuer that produces a PostgreSQL int2[] from the given Go []int.
func Int2ArrayFromIntSlice(val []int) driver.Valuer {
return int2ArrayFromIntSlice{val: val}
}
// Int2ArrayToIntSlice returns an sql.... |
package common
import (
"crypto/tls"
"fmt"
"net"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/root-gg/utils"
"github.com/BurntSushi/toml"
"github.com/dustin/go-humanize"
"github.com/iancoleman/strcase"
str2duration "github.com/xhit/go-str2duration/v2"
"github.com/root-gg/logger"
)
const envP... |
package kata
import "strings"
func replace(str string) string{
target:=str
target = strings.ReplaceAll(target,"()","")
target = strings.ReplaceAll(target,"[]","")
target = strings.ReplaceAll(target,"{}","")
return target
}
func ValidBraces(str string) bool {
target := str
for i:=0;i<len(str)/2;i++{
ta... |
package main
import "time"
type Event struct {
Id int `json:"id"`
FieldData []map[string]string `json:"fieldData"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type Events []Event
|
package service
import (
"bytes"
"html/template"
"math/rand"
"strconv"
"strings"
"tesou.io/platform/brush-parent/brush-api/common/base"
vo2 "tesou.io/platform/brush-parent/brush-api/module/suggest/vo"
"tesou.io/platform/brush-parent/brush-core/common/utils"
"tesou.io/platform/brush-parent/brush-core/module/le... |
package bundle
import (
"context"
"reflect"
"testing"
)
func TestServerEndpoints(t *testing.T) {
tests := []struct {
c FlowerCode
want getResponse
}{
{
c: Roses,
want: getResponse{
[]Bundle{
{"Roses", Roses, 5, 6.99},
{"Roses", Roses, 10, 12.99},
},
nil,
},
},
{
c: ... |
package entities
import (
"time"
)
type MetricKafkaTopicCurrentOffset struct {
DatahubEntity `scope:"metric" category:"kafka" type:"topic" measurement:"kafka_topic_partition_current_offset" metric:"current_offset" boundary:"undefined" quota:"undefined"`
Time *time.Time `json:"time" required:"false... |
package main
import (
"context"
"flag"
"fmt"
"log"
"strings"
"time"
"github.com/sdeoras/token/proto"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
)
func main() {
t := time.Now()
host := flag.String("host", "0.0.0.0:7001", "host")
action := flag.String("action", "reset",
"action to perform: res... |
package mongomodel
import (
"time"
)
type ErrorModel struct {
View *DailyErrorView
Typemap map[int]int
}
func NewErrorModel(date time.Time) *ErrorModel {
model := ErrorModel{
View: newDailyErrorView(date),
Typemap: make(map[int]int),
}
model.Typemap[255] = 0
model.Typemap[256] = 1
model.Typemap[25... |
// Copyright 2019 Kuei-chun Chen. All rights reserved.
package atlas
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"github.com/simagix/gox"
)
// AlertsDo execute a command
func (api *API) AlertsDo(method string, data string) (string, error) {
var err error
var resp *http.Response
var doc m... |
/**
* Copyright 2019 Comcast Cable Communications Management, LLC
*
* 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 requir... |
package main
import (
"log"
"net/http"
"net/url"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type DeviceToken struct {
Id bson.ObjectId `bson:"_id" json:"id"`
DeviceTokenStr string `bson:"devicetoken" json:"devicetoken"`
UserId string `bson:"userid" json:"userid"`
}
func ini... |
package main
import (
"bufio"
"fmt"
"github.com/balrogsxt/xtbot-go/app"
_ "github.com/balrogsxt/xtbot-go/util/logger"
"os"
)
func main() {
defer func() {
if err := recover(); err != nil {
fmt.Printf("运行发生异常: 【%s】请输入任意字符退出...\n", err)
bufio.NewScanner(os.Stdin).Scan()
}
}()
app.AppLinkStart()
}
|
package slack
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestNewSectionBlock(t *testing.T) {
textInfo := NewTextBlockObject("mrkdwn", "*<fakeLink.toHotelPage.com|The Ritz-Carlton New Orleans>*\n★★★★★\n$340 per night\nRated: 9.1 - Excellent", false, false)
sectionBlock := NewSectionBlock(tex... |
package ruffe
type Middleware struct {
h Handler
OnError func(Context, error) error
}
func NewMiddleware(h Handler) *Middleware {
return &Middleware{
h: h,
}
}
func NewMiddlewareFunc(f func(Context) error) *Middleware {
return NewMiddleware(HandlerFunc(f))
}
// Before create middleware which call Middl... |
// Package p2pV1 is the v1 of XuperChain p2p network.
package p2pv1
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"strconv"
"sync"
"github.com/pkg/errors"
log "github.com/xuperchain/log15"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org... |
package dockerfile
import (
"bytes"
"io/ioutil"
"regexp"
"strconv"
"strings"
)
var findExposePortsRegEx = regexp.MustCompile("^EXPOSE\\s(.*)$")
// GetPorts retrieves all the exported ports from a dockerfile
func GetPorts(filename string) ([]int, error) {
data, err := ioutil.ReadFile(filename)
if err != nil {
... |
package day05
/*
参见
1.https://golang.org/cmd/go/
2.Ctrl + F 搜索test
1.Test packages
2.Testing flags
3.Testing functions
Demo
1.go test -v -bench=. -benchtime=3s -benchmem
*/
|
package main
import (
"github.com/miekg/dns"
"os"
"log"
"fmt"
"io/ioutil"
"net"
"net/http"
"strconv"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
// use Consul DNS to resolve
func Resolve(q string) (ip net.IP, port uint16, target string, err error) {
c := new(dns.C... |
// weight
package main
import (
"fmt"
"github.com/captaingit/datfile"
"github.com/captaingit/dynhtml"
"net/http"
"os"
"sort"
"strconv"
"time"
)
// PageWeightEntry displays the capture form for entering new
// weight entries. It also handles the post data
func PageWeightEntry(w http.ResponseWriter, r *http.Req... |
package main
import (
"fmt"
"io/ioutil"
"runtime"
)
func checkErr(error error) {
if error != nil {
panic(error)
}
}
func getFileContent(path string) string {
_, currentPath, _, _ := runtime.Caller(1)
dat, err := ioutil.ReadFile(currentPath + path)
checkErr(err)
return string(dat[:])
}
func main() {
va... |
package main
import (
"flag"
"fmt"
"io/ioutil"
"net/http"
"github.com/alde/plexsorter/parser"
"github.com/alde/plexsorter/sorter"
"github.com/sirupsen/logrus"
)
// Command-line Flags
var (
token = flag.String("token", "", "API token for plex")
host = flag.String("host", "localhost", "Plex server ... |
package sdl
type SDL_DisplayMode struct {
Format uint32
W int32
H int32
Refresh_rate int32
Driverdata *byte
}
/**
* \brief The flags on a window
*
* \sa SDL_GetWindowFlags()
*/
const (
/* !!! FIXME: change this to name = (1<<x). */
SDL_WINDOW_FULLSCREEN = 0x00000001 ... |
package dynamic_programming
import "testing"
func Test_minPathSum(t *testing.T) {
nums := [][]int{
{1, 3, 1},
{1, 5, 1},
{4, 2, 1},
}
res := minPathSum(nums)
if res != 7 {
t.Error(res)
}
}
|
package main
import (
"bufio"
"errors"
"net"
"os"
"strings"
"sync"
"time"
"awesome-dragon.science/go/goGoGameBot/internal/process"
"awesome-dragon.science/go/goGoGameBot/internal/transport/network"
"awesome-dragon.science/go/goGoGameBot/internal/transport/network/protocol"
"awesome-dragon.science/go/goGoGa... |
package nsentity
type NSPmiCommon struct{
Date string
Pmi float32
NewOrder float32
NewExportOrder float32
InHandOrder float32
Inventory float32
Employees float32
SupplierDeliveryTime float32
}
type NSMfgPmi struct{
NSPmiCommon
Production float32
PurchasingVolume float32
... |
/*
Write a regular expression that matches a string if it contains at least one digit.
Examples
hasDigit("c8") ➞ true
hasDigit("23cc4") ➞ true
hasDigit("abwekz") ➞ false
hasDigit("sdfkxi") ➞ false
Notes
This challenge is designed to use RegEx only.
*/
package main
import "regexp"
func main() {
assert(hasdi... |
package main
import "fmt"
func main() {
fmt.Println(minPathSum([][]int{
{1, 3, 1}, {1, 5, 1}, {4, 2, 1},
}))
}
func minPathSum(grid [][]int) int {
m := len(grid)
n := len(grid[0])
dp := make([][]int, m)
for i := range dp {
dp[i] = make([]int, n)
}
min := func(a, b int) int {
if a < b {
return a
... |
// Helper functions for creating modules from static screens
package static
import (
"github.com/I82Much/rogue/event"
"github.com/I82Much/rogue/render"
termbox "github.com/nsf/termbox-go"
)
type Module struct {
contents string
// The event that should be published if the given rune is pressed
keyMap map[rune... |
// Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
package dashboard
import (
"context"
"errors"
"net/http"
"time"
"github.com/iotaledger/hive.go/daemon"
"github.com/iotaledger/hive.go/logger"
"github.com/iotaledger/hive.go/node"
"github.com/iotaledger/wasp/packages/dashboard"
"github.co... |
package public
import (
b64 "encoding/base64"
"errors"
"math/rand"
"strconv"
"time"
log "github.com/go-kit/kit/log"
"github.com/jinzhu/gorm"
uuid "github.com/satori/go.uuid"
"github.com/syedomair/plan-api/models"
)
type PublicRepositoryInterface interface {
IsEmailUnique(email string) error
CreateUser(inp... |
package main
import (
"context"
"log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)
// Helper to check if user is able to make submission to contest
func canUserSubmit(
userId primitive.ObjectID,
contestId primitive.ObjectID,
contestEnt... |
// Copyright 2018 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.Static("/file", "./dir")
r.StaticFS("/s", http.Dir("s"))
r.StaticFile("/f", "./f")
r.Run()
}
|
package testing
import (
"os"
"path"
"runtime"
)
// make sure we hop to the project root when imported. This is to make life easier for tests so they can include files from testdata
// without needing to know its relative location in the tree
func init() {
_, filename, _, _ := runtime.Caller(0)
// hop back 2 dir... |
// Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
// Package encodedargs implements special encoding of the dict.Dict which alows
// optimized transfer of big data through SC request. It encodes big data chunks
// as hashes, whihc later can be decoded (solidified) into the original form
package re... |
package task
import (
"DataApi.Go/database/orm"
"DataApi.Go/lib/common"
"github.com/jinzhu/gorm"
)
func QueryYnaReportList(db *gorm.DB, StartDate int, EndDate int, adUnitIds []int) []common.JSON {
result := orm.SelectYnaReportList(db, adUnitIds, StartDate, EndDate)
return result
}
|
package main
import "fmt"
import "time"
func main() {
c1 := make(chan string)
go func() {
time.Sleep(time.Second * 3)
c1 <- "result 1"
}()
select {
case msg := <-c1:
fmt.Println("get ", msg)
case <-time.After(time.Second * 2):
// https://golang.org/pkg/time/#After After return a channel : <-chan Tim... |
package commands
import (
"github.com/pengsrc/go-shared/pid"
"github.com/sirupsen/logrus"
"github.com/yunify/qscamel/config"
"github.com/yunify/qscamel/contexts"
)
func init() {
RunCmd.Flags().StringVarP(&taskPath, "task", "t", "", "task path")
}
func initContext(configFile string) error {
c := &config.Config... |
package _4_variable
import (
"testing"
)
func TestVariableInitialValue(t *testing.T) {
// 变量初始值
var (
a int = 10
b string = "mark"
c []float64 = []float64{3.14}
d func() bool = func() bool {
return true
}
e struct {
name string
age int
} = struct {
name string
age int
... |
// -------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// -----------------------------------------------------------------... |
// Copyright 2016 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.
package keybase
import (
"fmt"
"os"
"os/user"
"path/filepath"
"strings"
"time"
"github.com/kardianos/osext"
"github.com/keybase/go-updater"
"github.com/keybase/go-updater/command"
"githu... |
/*****************************************************************
* Copyright©,2020-2022, email: 279197148@qq.com
* Version: 1.0.0
* @Author: yangtxiang
* @Date: 2020-08-18 14:57
* Description:
*****************************************************************/
package rpcPoint
import (
"fmt"
"github.com/go-xe2/x/t... |
/*
Copyright © 2020-2021 The k3d Author(s)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distri... |
package mongo
import (
"logger"
"gopkg.in/mgo.v2/bson"
)
func (this *MongoManager) IsExist(db string, coll string, query bson.M) bool {
c := this.GetDB(db).C(coll)
count, err := c.Find(query).Count()
if err != nil || count == 0 {
logger.LOGLINE(err)
return false
}
return true
}
func (this *MongoManager) ... |
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"github.com/mooncaker816/gophercises/urlshort"
)
func main() {
filetype := os.Args[1]
var filename string
var myhandler http.HandlerFunc
switch filetype {
case "json":
filename = "urls.json"
urls, err := getfile(filename)
if err != nil {
fmt.... |
package main
import (
"fmt"
"net/http"
"html/template"
"time"
"log"
)
func sayhelloName(w http.ResponseWriter, r *http.Request) {
r.ParseForm() //解析参数,默认是不会解析的
var goos = time.Now().Format("2006-01-02 15:04:05")
fmt.Printf("——————————————————%s————————————————————\n", goos)
fmt.Printf("the ... |
package inmem
import (
"github.com/smilga/analyzer/api"
)
type PatternStore struct {
patterns []*api.Pattern
}
func (s *PatternStore) Save(target *api.Pattern) error {
if target.ID == 0 {
var last int64
for _, n := range s.patterns {
if int64(n.ID) > last {
last = int64(n.ID)
}
}
target.ID = api... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//593. Valid Square
//Given the coordinates of four points in 2D space, return whether the four points could construct a square.
//The coordinate (x,y)... |
package main
import (
"fmt"
"strconv"
)
func main() {
num1 := 123456789
num2 := 100
ans := num1 / num2
ansStr := strconv.Itoa(ans)
if len(ansStr) <= 3 {
fmt.Println(ansStr)
return
}
revStr := ""
for i := len(ansStr) - 1; i >= 0; i-- {
revStr += string(ansStr[i])
}
buildStr := ""
for i := 0;... |
package micro
import (
"context"
"github.com/iGoogle-ink/gotil/xlog"
"github.com/micro/go-micro/v2/client"
"github.com/micro/go-micro/v2/server"
)
func LogWrapper(fn server.HandlerFunc) server.HandlerFunc {
return func(ctx context.Context, req server.Request, rsp interface{}) error {
xlog.Infof("server[%s], m... |
// +build windows
package lfile
import (
"errors"
"syscall"
"unsafe"
)
var (
K32 = syscall.NewLazyDLL("kernel32.dll")
LockFileEx = K32.NewProc("LockFileEx")
UnlockFileEx = K32.NewProc("UnlockFileEx")
)
const (
LOCKFILE_FAIL_IMMEDIATELY = 0x00000001
LOCKFILE_EXCLUSIVE_LOCK = 0x00000002
LOCK_CON... |
package config
import (
"github.com/gofiber/fiber/v2"
)
func (config *Config) GetFiberConfig() fiber.Config {
return fiber.Config{
Prefork: config.GetBool("FIBER_PREFORK"),
ServerHeader: config.GetString("APP_NAME"),
UnescapePath: config.GetBool("FIBER_UNESCAPEPATH"),
BodyLim... |
package controllers
import (
"fmt"
"myproject/models"
"github.com/astaxie/beego"
)
/**
该控制器处理页面错误请求
*/
type ErrorController struct {
beego.Controller
}
func (c *ErrorController) Error401() {
c.Data["content"] = "未经授权,请求要求验证身份"
c.TplName = "error/404.tpl"
}
func (c *ErrorController) Error403() {
c.Data["c... |
package problems
import "math"
var M, N int
var Pos [4][2]int
func LongestIncreasingPath(matrix [][]int) int {
M = len(matrix)
if M == 0 {
return 0
}
N = len(matrix[0])
if N == 0 {
return 0
}
Pos = [4][2]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}
nmatrix := make([][]int, M)
for i := 0; i < M; i++ {
nmatrix[i]... |
package routers
import (
"encoding/json"
"net/http"
"github.com/rodzy/flash/db"
"github.com/rodzy/flash/jwt"
"github.com/rodzy/flash/models"
)
//Login func for the http endpoint
func Login(w http.ResponseWriter, r *http.Request) {
w.Header().Add("content-type", "application/json")
var user models.User
err :=... |
package app
import (
"github.com/10gen/realm-cli/internal/cli"
"github.com/10gen/realm-cli/internal/cli/user"
"github.com/10gen/realm-cli/internal/terminal"
"github.com/10gen/realm-cli/internal/utils/flags"
)
// CommandMetaDescribe is the command meta for the `app describe` command
var CommandMetaDescribe = cli.C... |
package templates
import (
"html/template"
"net/http"
)
func RenderTOTPTemplate(w http.ResponseWriter, r *http.Request) {
data := struct {
CameFrom string
}{
CameFrom: getPath(r),
}
templates := template.Must(
template.Must(
template.New("Show").
ParseGlob("web/templates/layout/*.tmpl")).
Pars... |
package rpcd
import (
"io"
"github.com/Cloud-Foundations/Dominator/lib/srpc"
proto "github.com/Cloud-Foundations/Dominator/proto/imageunpacker"
)
func (t *srpcType) GetRaw(conn *srpc.Conn) error {
var request proto.GetRawRequest
if err := conn.Decode(&request); err != nil {
return err
}
var reply proto.GetR... |
package 简单递归
// 简单递归
func integerReplacement(n int) int {
return integerReplacementExec(n)
}
func integerReplacementExec(n int) int {
if n == 1 {
return 0
}
ans := 0
if n&1 == 1 {
a, b := integerReplacementExec(n+1), integerReplacementExec(n-1)
ans = min(a, b) + 1
} else {
ans = integerReplacementExec(n>... |
package cbnet
// HostNetworkInformation represents the network information of VM, such as public IP and private networks
type HostNetworkInformation struct {
PublicIP string `json:"publicIPAddress"`
PrivateNetworkCIDRBlocks []string `json:"privateNetworkCIDRBlocks"`
}
|
package _91_Decode_Ways
func numDecodings(s string) int {
return numDecodingsWithDP(s)
}
// DP 解法
func numDecodingsWithDP(s string) int {
if len(s) == 0 || s[0] == '0' {
return 0
}
var dp = make([]int, len(s)+1)
dp[0] = 1 // 开始时只有1种
dp[1] = 1 // 到达第一位只有1种方法
for i := 2; i <= len(s); i++ {
x := s[i-1]
if x... |
// Copyright (c) 2019 Aiven, Helsinki, Finland. https://aiven.io/
package aiven
import (
"github.com/aiven/aiven-go-client"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func datasourceDatabase() *schema.Resource {
return &schema.Resource{
Read: datasourceDatabaseRead,
Schema: resourceSchemaAsD... |
package main
import "fmt"
//学生管理系统
//1.保存了一些数据 --->结构体的字段
//2.它有三个功能 --->结构体的方法
var index int64
var (
allstudent map[int64]student
)
type student struct{
id int64
name string
}
//造一个学生的管理者
type stumanager struct{
allstudent map[int64]student
}
//方法
func (s stumanager)showstudent(){
for _,stu:=range s.al... |
package utils_test
import (
utils "github.com/Azure/application-gateway-kubernetes-ingress/pkg/utils"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Utils", func() {
Describe("Testing `UnorderedSets`", func() {
var testSet utils.UnorderedSet
BeforeEach(func() {
testSet = utils.Ne... |
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"sort"
"strings"
)
var (
filterChats = []string{",", ".", "...", "-", "—", "?", "!", "\"", "(", ")", "[", "]", ":", ";", "«", "'", "*", "»"}
file = flag.String("file", "", "Path to text file")
line = flag.String("line", "", "String with value... |
package service
// ServiceCreateRequest is a request to create a service.
type ServiceCreateRequest struct {
Name string `json:"service_name"`
Port int `json:"port"`
Domain string `json:"domain"`
Regex string `json:"url_regex"`
}
// ServiceCreateResponse is a response to create a service.
type ServiceCrea... |
package bean
type Redis struct {
Host string `json:"host"`
Port string `json:"port"`
Password string `json:"password omitempty"`
}
|
package errors
var ErrNoFile = New("file with this id not found", 404)
|
package s3
import (
"log"
"strconv"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
func GetFilesModificationDate(S3Bucket string) (map[string]*time.Time, error) {
sess, _ := session.NewSession(&aws.Config{})
svc := s3.New(sess)
var obj... |
package nats
import (
"context"
"crypto/tls"
"net/url"
"github.com/nats-io/nats.go"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/batchcorp/plumber-schemas/build/go/protos/args"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"github.com/batchcorp/plumber/types"
"github.com/... |
package tmpl
import "reflect"
func IsTrue(o interface{}) bool {
typ := reflect.TypeOf(o).Kind()
val := reflect.ValueOf(o)
switch typ {
case reflect.Int, reflect.Float64:
return val.Int() != 0
case reflect.String:
return val.String() != ""
case reflect.Bool:
return val.Bool()
}
return false
}
|
package hamming
import "errors"
const testVersion = 5
// Distance returns hamming distance between DNA
func Distance(a, b string) (int, error) {
dis := 0
if len(a) != len(b) {
return dis, errors.New("invalid input size")
}
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
dis++
}
}
return dis, nil
}
|
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"github.com/aaron7/go-oauth2webflow"
"golang.org/x/oauth2"
)
func main() {
// Setup oauth2 config
ctx := context.Background()
conf := &oauth2.Config{
ClientID: os.Getenv("SPOTIFY_CLIENT_ID"),
ClientSecret: os.... |
package main
import (
"fmt"
"log"
"net"
)
func Server() {
l, err := net.Listen("tcp", "127.0.0.1:8888")
if err != nil {
log.Fatal(err)
}
defer l.Close()
//循环等待客户端访问
for {
conn, err := l.Accept()
if err != nil {
log.Fatal(err)
}
fmt.Printf("访问客户端信息: con=%v 客户端ip=%v\n", conn, conn.RemoteAddr().S... |
package osm
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"time"
"github.com/stamm/wheely/apis/distance/services"
"github.com/stamm/wheely/apis/distance/types"
)
type Service struct {
token string
}
var (
_ services.Service = Service{}
)
func New(token string) Service {
return Serv... |
package component
import (
"github.com/kirillrdy/nadeshiko/html"
"github.com/sparkymat/webdsl/css"
"github.com/sparkymat/webdsl/css/size"
)
type View interface {
Style() css.CssContainer
Html() html.Node
Width() size.Size
Height() size.Size
}
|
package dynamic
import (
"runtime"
"strings"
)
func CallerName(short bool) string {
return CallerNameSkip(1, short)
}
func CallerNameSkip(skip int, short bool) string {
pc, _, _, _ := runtime.Caller(skip + 1)
fn := runtime.FuncForPC(pc)
name := fn.Name()
if short {
idx := strings.LastIndex(name, `.`)
if i... |
package types
// TrafficAccidents holds the data for the traffic accidents.
type TrafficAccidents struct {
Year int `json:"year" fake:"{year}"`
DeadlyAccidents int `json:"deadly_accidents" fake:"{number:0,100}"`
Deaths int `json:"deaths" fake:"{number:0,100}"`
Jurisdiction strin... |
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestParseConfigFromYaml(t *testing.T) {
config := parseConfigFromYaml("./.bldr.yml")
assert.NotNil(t, config, "Config should exist")
assert.Equal(t, len(config.Config), 2, "Config map should have two entries")
assert.Equal(t, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.