text stringlengths 11 4.05M |
|---|
/*
Different Asserts
Statement
Using Testify/assert pkg, execute different functions and validate the expected result. You can create as many cases as you want
Equal | NotEqual | Nil | NotNil
Topics to Practice:
testing, multiple cases, testify
*/
/*
Installation:
sudo apt install git
go get github.com/stretchr/tes... |
package service
import (
"context"
"fmt"
"github.com/go-ocf/kit/strings"
"google.golang.org/grpc/codes"
pbRS "github.com/go-ocf/cloud/resource-directory/pb/resource-shadow"
)
func toResourceValue(m *resourceCtx) pbRS.ResourceValue {
return pbRS.ResourceValue{
ResourceId: m.snapshot.GetResource().GetId(),
... |
package agent
import (
"bytes"
"encoding/json"
"net/http"
"net/url"
"time"
log "github.com/Sirupsen/logrus"
"github.com/bryanl/dolb/firewall"
"github.com/bryanl/dolb/kvs"
"github.com/bryanl/dolb/server"
"github.com/bryanl/dolb/service"
)
var (
haproxyDiscoverKey = "/haproxy-discover/services"
pingRate ... |
package mint
import (
"github.com/irisnet/irishub/app/v1/bank"
"github.com/irisnet/irishub/app/v1/params"
"github.com/irisnet/irishub/codec"
sdk "github.com/irisnet/irishub/types"
)
// keeper of the stake store
type Keeper struct {
storeKey sdk.StoreKey
cdc *codec.Codec
paramSpace params.Subspace
bk ... |
package parse_test
import (
"fmt"
"log"
"os"
"strings"
"testing"
"time"
"github.com/tmc/parse"
)
type GameScore struct {
parse.ParseObject
CheatMode bool `json:"cheatMode,omitempty"`
PlayerName string `json:"playerName,omitempty"`
Score float64 `json:"score,omitempty"`
}
func mkclient(t *testin... |
// Copyright 2019 Leandro Akira Omiya Takagi. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package unio
import (
"reflect"
)
// Format query=filter content to MongoDB pattern
func (s *Search) FormatFilters(f interface{}, rule RequestFor... |
package coda
import (
"fmt"
"github.com/stretchr/testify/assert"
"testing"
)
func TestListRows(t *testing.T) {
docId := "abc"
tableId := "123"
expectedPath := fmt.Sprintf("/docs/%s/tables/%s/rows?query=colId%%3A131231&sortBy=&useColumnNames=false&valueFormat=&visibleOnly=true", docId, tableId)
server := buildT... |
package v1alpha4
import (
"github.com/devspace-cloud/devspace/pkg/devspace/config/versions/config"
"github.com/devspace-cloud/devspace/pkg/devspace/config/versions/util"
next "github.com/devspace-cloud/devspace/pkg/devspace/config/versions/v1beta1"
"github.com/devspace-cloud/devspace/pkg/util/log"
)
// Upgrade up... |
package mosql
import (
//"fmt"
"testing"
)
func TestNewCol(t *testing.T) {
col := NewCol("abc")
if x := col.Name(); x != "abc" {
t.Errorf("Incorrect col name: %v!", x)
}
fld := col.NewStringFld("def")
if x := fld.FldName(); x != "def" {
t.Errorf("Incorrect fld name: %v!", x)
}
}
func TestGetSet(t *testin... |
package memphis
import (
"context"
"encoding/json"
"strings"
"time"
"github.com/memphisdev/memphis.go"
"github.com/pkg/errors"
uuid "github.com/satori/go.uuid"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"github.com/batchcorp/plumber-schemas/build/go/protos/records"
"github.com/batchcorp/p... |
package main
import (
"fmt"
"until"
)
// 累加就是由大到小 将中序遍历反过来 得到的就是由大到小
var sum int
func convertBST(root *until.TreeNode) *until.TreeNode {
//先右子树,再求根节点的值,之后将根节点的值加到左子树上
sum = 0
helper(root)
return root
}
func helper(root *until.TreeNode) {
if root == nil {
return
}
helper(root.Right)
sum += root.Val
root... |
package robotmsg
import (
"fmt"
"github.com/grearter/rpa-agent/api"
"github.com/sirupsen/logrus"
"reflect"
"strings"
)
// Add 新增RobotMessage
func Add(messageAPI *api.RobotMessage) (err error) {
t := reflect.TypeOf(*messageAPI)
v := reflect.ValueOf(*messageAPI)
fieldNum := t.NumField()
fields := make([]strin... |
package server
import (
"bufio"
"crypto/md5"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
log "github.com/sirupsen/logrus"
)
// ReqInfo describes a proxied request
type ReqInfo struct {
Time int64 `json:"time"`
Duratio... |
package solution
import (
"testing"
)
func TestSol(t *testing.T) {
testcases := []struct {
s string
numRows int
ans string
}{
{
s: "PAYPALISHIRING",
numRows: 4,
ans: "PINALSIGYAHRPI",
},
{
s: "PAYPALISHIRING",
numRows: 3,
ans: "PAHNAPLSIIGYIR",
},
{
... |
package storage
type AWS struct {
AccessKeyID string `json:"accessKeyId,omitempty"`
SecretAccessKey string `json:"secretAccessKey,omitempty"`
Region string `json:"region"`
}
|
package workspace
import (
"log"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
// Workspace model.
type Workspace struct {
Name string
DisplayName string
OwnerID string
Members []interface{}
}
// GetWorkspace finds a taskworld workspace matching @pattern
func GetWorkspace(session *mgo.Session, pa... |
package main
import (
"practice/http/testSpider"
"log"
"github.com/astaxie/beego/logs"
"sync"
"lesson/gorm/beegoOrm"
)
var chTask = make(chan beegoOrm.FictionOneOfList)
// 入口函数
func main() {
var wg sync.WaitGroup
listUrl := "https://www.biduo.cc/biquge/17_17308"
//url := "https://www.biduo.cc/biquge/17_1730... |
package api
import (
"main/db"
"github.com/gin-gonic/gin"
)
func Setup(router *gin.Engine) {
db.SetupDB()
setupAuthenAPI(router)
setupUserAPI(router)
}
|
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"testing"
)
func TestOriginator(t *testing.T) {
t.Run("Sending Sales order to Originator", func(t *testing.T) {
salesOrder := SalesOrder{}
uuid1 := NewUuid()
salesItem := SalesItem{uuid1, "computer table", 2, 150.00, "", ""}
... |
package Services_Crawler
import (
// "encoding/json"
. "Framework_Definitions"
"JSON_Saver"
. "Utilities"
"github.com/kardianos/osext"
"io/ioutil"
"net/http"
// "strings"
// "os"
// "path/filepath"
)
// ------------------------------------------- Public ------------------------------------------- //
type C... |
package email
import (
"crypto/tls"
"encoding/base64"
"fmt"
"net"
"net/smtp"
"strings"
"github.com/cloudfly/ecenter/pkg/sender"
)
func init() {
sender.Register(Name, New)
}
// 发送器名称
const (
Name = "email"
)
// Sender represents a email sender
type Sender struct {
addr string
username string
secret ... |
package http_client
import (
"github.com/kataras/iris/context"
"gocherry-api-gateway/proxy/enum"
"io/ioutil"
"net/http"
"time"
)
/**
http get
*/
func Get(url string, timeRequest time.Duration, headers []string, ctx context.Context) (res string, statusCode int, errMsg string) {
client := &http.Client{
Timeout:... |
package main
import (
"fmt"
"github.com/PuerkitoBio/goquery"
// "io/ioutil"
iconv "github.com/djimenez/iconv-go"
"net/http"
)
const (
baseUrl = "http://www.biquzi.com"
)
func main() {
url := "http://www.biquzi.com/14_14297/"
resp, err := http.Get(url)
if err != nil {
fmt.Println(err)
return
}
defer re... |
package demo
import (
"fmt"
"log"
"reflect"
)
type Student struct {
Name string `json:"name" db:"NAME"`
Age int `json:"age" db:"AGE"`
Score float32 `json:"score" db:"SCORE"`
}
func (s *Student) SetName(name string) {
s.Name = name
}
func (s *Student) Print() {
fmt.Printf("Print 方法:%#v \n", s)
}
fun... |
package server
import (
"sync"
"time"
"github.com/tidwall/tile38/internal/collection"
"github.com/tidwall/tile38/internal/log"
"github.com/tidwall/tile38/internal/object"
)
const bgExpireDelay = time.Second / 10
// backgroundExpiring deletes expired items from the database.
// It's executes every 1/10 of a sec... |
package p08
func uniqueMorseRepresentations(words []string) int {
table := []string{".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}
if words == nil || len(words) == 0 {
return ... |
package paste
import (
"bytes"
"database/sql"
"encoding/json"
"fmt"
"html/template"
"io"
"math/rand"
"net/http"
"os"
"pastebin/config"
"strconv"
"time"
_ "github.com/go-sql-driver/mysql"
)
const (
ACCEPT = iota
ERROR
NONEXISTENT
WRONGPASSWORD
)
func Paste(w http.ResponseWriter, r *http.Request) {
... |
package handler
import (
"encoding/json"
"net/http"
"k8s.io/apiserver/pkg/authentication/authenticator"
)
type userInfo struct {
Username string `json:"username"`
UID string `json:"uid"`
Groups []string `json:"groups"`
Extra map[string][]string `json:"extra"`
}
... |
package handlers
import (
"github.com/krix38/gophotogallery/web/controller"
"github.com/krix38/gophotogallery/model/dao"
"github.com/krix38/gophotogallery/model"
"github.com/krix38/gophotogallery/properties"
"regexp"
"net/http"
"errors"
"strconv"
"log"
)
func AddGallery(w http.ResponseWriter, r *http.Reques... |
package tsmt
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document00600103 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:tsmt.006.001.03 Document"`
Message *AmendmentAcceptanceNotificationV03 `xml:"AmdmntAccptncNtfctn"`
}
func... |
package main
import (
"fmt"
"net/http"
"strings"
"github.com/mattermost/mattermost-server/v5/model"
)
type peerPostUsecase struct {
plugin *Plugin
}
const (
commandPeerUsage = "** ピア投稿 Slash Command Help **\n\n /peer @ユーザ名\n\n - 自身は指定できません。\n\n - 複数人を指すメンションは指定できません。(ex: @all, @channel, @here)\n\n - チーム内の... |
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
var (
semver = "0.1.0"
githash = "HEAD"
)
var versionCmd = &cobra.Command{
Use: "version",
Short: "Display tankerctl version",
Run: version,
}
func init() {
RootCmd.AddCommand(versionCmd)
}
func version(cmd *cobra.Command, args []string) {
fmt.Pr... |
package main
import "golang.org/x/net/html"
html := `
<a href="/dog">
<span>Something in a span</span>
Text not in a span
<b>Bold text!</b>
</a>
`
type Link struct {
Href string
Text string
}
func main() {
html.NewTokenizer()
}
|
package main
import (
"encoding/json"
"fmt"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"github.com/gogo/protobuf/proto"
"github.com/golang/protobuf/ptypes/any"
empty "github.com/golang/protobuf/ptypes/empty"
"github.com/influxdata/influxdb/client/v2"
pb "github.com/iochti/point-service/... |
package config
import (
// "app/src/domain"
"github.com/jinzhu/gorm"
"log"
// "time"
)
// DBMigrate will create & migrate the tables, then make the some relationships if necessary
func DBMigrate() (*gorm.DB, error) {
log.Println("Migration start")
conn, err := ConnectDB()
if err != nil {
return nil, err
}
... |
package handlers
var AddNewWordTranslation = addNewWordTranslation
var AddNewSentenceTranslation = addNewSentenceTranslation
var ValidateRequestBody = validateRequestBody |
package main
import (
"fmt"
"math"
"github.com/jackytck/projecteuler/tools"
)
func count(limit int) int {
visited := make([]int, limit+1)
mBound := int(math.Sqrt(float64(limit) / 2))
for m := 1; m < mBound; m++ {
for n := 1; n < m; n++ {
if (m%2 == 1 && n%2 == 1) || tools.GCD(m, n) != 1 {
continue
... |
//Question 7
//Write a function that tests whether a string is a palindrome. A palindrome is a string that reads the same in reverse, e.g. radar.
//Code addapted from the following links
//https://github.com/jdxcode/programming-in-go/blob/master/05-procedural/palindrome.go
//https://play.golang.org/p/5FUOzjBa-o
... |
package terradex
import (
"log"
"github.com/spf13/cobra"
)
// VersionCmd for getting Version information
var VersionCmd = &cobra.Command{
Use: "terradex",
Short: "Terradex is a HTTP backend for Terraform state configuration and visualization.",
Long: `Terradex is a Terraform Support Tool for storing remote st... |
package controller
import (
"fmt"
"html/template"
"log"
"net/http"
"github.com/kenigbolo/go-web-app/model"
"github.com/kenigbolo/go-web-app/viewmodel"
)
type authentication struct {
loginTemplate *template.Template
signupTemplate *template.Template
}
func (auth authentication) registerRoutes() {
http.Hand... |
package main
import (
"github.com/gin-gonic/gin"
"net/http"
. "test/apis"
)
func initRouter() *gin.Engine{
router := gin.Default()
router.LoadHTMLGlob("tpl/html/*")
router.StaticFS("/staticfile", http.Dir("./static/res/static"))
router.StaticFS("/layui", http.Dir("./static/res/layui"))
router.StaticFS("/sta... |
package kucoin
import "net/http"
// HfAccountInnerTransfer Users can transfer funds between their main account,
// trading account, and high-frequency trading account free of charge.
func (as *ApiService) HfAccountInnerTransfer(params map[string]string) (*ApiResponse, error) {
req := NewRequest(http.MethodPost, "/ap... |
package ionic
import (
"fmt"
"testing"
"github.com/franela/goblin"
"github.com/ion-channel/ionic/pagination"
. "github.com/onsi/gomega"
)
func TestClient(t *testing.T) {
g := goblin.Goblin(t)
RegisterFailHandler(func(m string, _ ...int) { g.Fail(m) })
g.Describe("Client", func() {
g.It("should return a ne... |
// Copyright 2021 Clivern. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package service
import (
"context"
"encoding/json"
"fmt"
)
// DockerHubAPI const
const DockerHubAPI = "https://registry.hub.docker.com/v2/"
// DockerHub struct
type ... |
package main
import (
"bufio"
"fmt"
"net"
"os"
"strconv"
"strings"
)
var secret string = "qwerty"
func main() {
sAddr := "192.168.0.52:55442"
serverAddr, err := net.ResolveUDPAddr("udp", sAddr)
listener, err := net.DialUDP("udp", nil, serverAddr)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf... |
package dushengchen
/*
Submission:
https://leetcode.com/submissions/detail/270874219/
*/
func searchInsert(nums []int, target int) int {
insert := 0
for idx, v := range nums {
if v >= target {
break
} else {
insert = idx+1
}
}
return insert;
} |
package netease
import (
"fmt"
"ncm-dl/common"
"regexp"
"strconv"
)
const (
UrlPattern = "/(song|artist|album|playlist)\\?id=(\\d+)"
)
func Parse(url string) (req common.MusicRequest, err error) {
re := regexp.MustCompile(UrlPattern)
matched, ok := re.FindStringSubmatch(url), re.MatchString(url)
if !ok || le... |
package main
import (
"log"
"github.com/xr-hui/raspi-center/brain"
_ "github.com/xr-hui/raspi-center/diagnose"
)
func init() {
log.Println("Raspi center starting...")
}
func main() {
brain.HandleForever()
}
|
/* For license and copyright information please see LEGAL file in repository */
package uip
// packetStructure is represent protocol structure!
// It is just to show protocol in better way, we never use this type!
type packetStructure struct {
DestinationXP [4]byte // Mutable
DestinationRouter [4]byt... |
// Copyright (c) 2020 Blockwatch Data Inc.
// Author: alex@blockwatch.cc
package puller
import (
"bytes"
"context"
"fmt"
"github.com/cespare/xxhash"
"github.com/jinzhu/gorm"
"github.com/zyjblockchain/sandy_log/log"
"tezos_index/chain"
"tezos_index/micheline"
"tezos_index/puller/index"
"tezos_index/puller/mo... |
/*
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, softw... |
package positions
import (
"core/sessions"
"fmt"
"net/http"
"qutils/basehandlers"
"qutils/coder"
)
func AccountHomeHandler(resp http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
session, ok := sessions.GetSessionByRequest(req)
if !ok {
basehandlers.UnauthorizedRequest(resp, req)
return
}
... |
package main
import (
"context"
"fmt"
"os"
"os/exec"
"time"
)
// for sh -c
const cmdline = `x=0; while true; do echo "hello $x"; x=$(( x + 1 )); sleep 1; done`
func graceful() {
ctx, cancel := context.WithCancel(context.Background())
cmd := exec.CommandContext(ctx, "sh", "-c", cmdline)
cmd.Stdout = os.Stdout... |
package api
import (
"crypto/md5"
"easyurl/infra/db/mysql"
"easyurl/model"
"encoding/base64"
"fmt"
"io"
"log"
"net/http"
"strconv"
"time"
sq "github.com/Masterminds/squirrel"
)
func CreateHandler(w http.ResponseWriter, r *http.Request) {
apiDevKey := r.FormValue("api_dev_key")
originalUrl := r.FormValue(... |
// 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... |
// Copyright 2015 The Chromium 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 lhttp
import (
"errors"
"testing"
"github.com/maruel/ut"
)
func TestCheckURL(t *testing.T) {
const onlyHttpsErr = "Only https:// scheme is ... |
package nsparser
import(
"util"
"strings"
//"fmt"
)
type NSParserBase struct {
}
func (p *NSParserBase) Parse(mapData map[string] string) {
}
//key format as: id_000000_yyyyMM
func (p *NSParserBase) ParseKey(key string) (id, date string) {
keys := strings.Split(key, "_")
if len(keys) != 3 {... |
package models
import (
"time"
"github.com/jinzhu/gorm"
"github.com/JacksonGariety/cetch/app/utils"
)
type Competition struct {
gorm.Model
Name string
Description string
Position int
Date time.Time
Solution float64
Entries []Entry
}
type Competitions []Competition
func... |
package main
import "fmt"
func main() {
var messages chan string = make(chan string)
go func(message string) {
messages <- message
}("ping ping ")
fmt.Println(<-messages)
} |
package inadapters
type InPort interface {
RunServer()
}
|
package server
import (
"context"
"io"
"pancakebasspanda/grpc-message-service/protos"
log "github.com/sirupsen/logrus"
)
// rpc Connection(stream ConnectionRequest) returns (stream ConnectionRequest); // database
// rpc SendMessage(SendMessageRequest) returns (SendMessageResponse);
func (s *MessageServiceServer... |
package main
import "fmt"
type Cave struct {
Rocks []*RockStructure
Graph *Graph
Limits Limits
}
func NewCave(input []string) *Cave {
limits := NewLimits()
rocks := []*RockStructure{}
for _, line := range input {
rock := NewRockStructure(line)
limits.Analyze(rock.Vectors)
rocks = append(rocks, rock)
... |
package cw
import "fmt"
func ShapeArea() {
fmt.Println(shapeArea(1))
}
/**
Below we will define an n-interesting polygon.
Your task is to find the area of a polygon for a given n.
For n = 2, the output should be
shapeArea(n) = 5;
For n = 3, the output should be
shapeArea(n) = 13.
*/
func shapeArea(n int) int {
c... |
package webauthnutil
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestEnrollmentToken(t *testing.T) {
key := []byte{1, 2, 3}
deviceEnrollmentID := "19be0131-184e-4873-acab-2be79321c30b"
token, err := NewEnrollmentToken(key, time.Second*30, deviceEnrollmentID)
assert.NoError(t, err)
i... |
package main
import "fmt"
func main() {
fmt.Println(isValid("aabcbc"))
}
func isValid(s string) bool {
st := make([]rune, 0)
for _, v := range s {
if len(st) < 2 {
st = append(st, v) // 长度小于 2 ,直接塞进去
} else if v == 'c' && st[len(st)-1] == 'b' && st[len(st)-2] == 'a' {
// 如果当前字符为 c,前面有个 ab,则出站
st = ... |
// Copyright 2022 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 repository
import (
"github.com/citrus-tart/certificate-aggregator/certificate"
)
type Repository struct {
Certs map[string]certificate.Certificate
}
func (r Repository) GetById(id string) certificate.Certificate {
return r.Certs[id]
}
func (r Repository) Save(c certificate.Certificate) certificate.Certi... |
package lbaas_v2
import (
"fmt"
"strings"
"testing"
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/acceptance/tools"
"github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/lbaas_v2/listeners"
"github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/lbaas_... |
package handler
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"github.com/microsoft/azure-databricks-operator/mockapi/middleware"
)
// Config is used to represent the mock api config
type Config struct {
LatencySlowRequestMax *int `json:"DATABRICKS_MOCK_API_LATENCY_M... |
package main
import (
"reflect"
)
type ObjectJSON struct {
Builder BuilderJSON `json:"Builder"`
Executable CommonBuildJSON `json:"Executable"`
StaticLib CommonBuildJSON `json:"StaticLib"`
SharedLib CommonBuildJSON `json:"SharedLib"`
}
type BuilderJSON struct {
Os string ... |
package vault
import (
"bytes"
_ "embed"
"encoding/json"
"fmt"
"html/template"
"io"
"mime"
"net/http"
"time"
"github.com/cinus-ue/securekit/common/pathutil"
"github.com/cinus-ue/securekit/internal/image"
)
type asset struct {
contentType string
readSeeker io.ReadSeeker
}
var (
//go:embed assets/index... |
package main
import (
"bufio"
"fmt"
"log"
"os"
"github.com/oanaOM/auction-tracker/house"
)
//bids stores all the auction of type bid
var bids []house.Auction
//store all items that are for sold
var sellItems []house.Item
func main() {
//Open the input file
file, err := os.Open("input.txt")
if err != nil {... |
package spdx
type Review struct {
Reviewer ValueCreator // mandatory
Date ValueDate // mandatory
Comment ValueStr // optional
*Meta
}
func (r *Review) M() *Meta { return r.Meta }
func (a *Review) Equal(b *Review) bool {
return a.Reviewer.V() == b.Reviewer.V() && a.Date.V() == b.Date.V() && a.Comment... |
// Copyright 2021 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... |
// Copyright (c) Facebook, Inc. and its affiliates.
// All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
package main
import (
"flag"
"fmt"
"github.com/facebookexperimental/GOAR/confighandler"
"github.com/gola... |
package main
import "fmt"
func main() {
i := 64
for {
i++
if(i >= 91) {
break
}
fmt.Println(i)
for j := 0 ; j < 3; j++ {
fmt.Printf("\t%#U\n", i)
}
}
} |
package httpmanager
import (
"errors"
"net/http"
"github.com/JointFaaS/Manager/env"
"github.com/JointFaaS/Manager/function"
"github.com/JointFaaS/Manager/provider/aliyun"
"github.com/JointFaaS/Manager/provider/aws"
"github.com/JointFaaS/Manager/scheduler"
"github.com/JointFaaS/Manager/worker"
)
// HTTPConfig... |
package link
import (
"strings"
"testing"
)
func compareLinks(a, b []Link) bool {
if len(a) != len(b) {
return false
}
for i, v := range a {
if v.Href != b[i].Href {
return false
}
if v.Text != b[i].Text {
return false
}
}
return true
}
func parseFile(pathfile string) ([]Link, error) {
htmlfi... |
//TODO 사용할 때는 코드 수정이 필요
package smallNet
import (
"fmt"
"net"
"scommon"
"time"
)
type remoteSession struct {
tcpSession
_remoteServerName string
_remoteServerAddress string
_maxConnectTryCount int
_maxPacketSize int16
_maxReceiveBufferSize int
_sockReadbuf, _sockWritebuf int // 소켓 ... |
/*
Description
A sequence of n > 0 integers is called a jolly jumper if the absolute values of the differences between successive elements take on all possible values through n - 1 (which may include negative numbers). For instance,
1 4 2 3
is a jolly jumper, because the absolute differences are 3, 2, and 1, respec... |
package x_ioutil
import (
"io/ioutil"
"os"
"path/filepath"
"testing"
"github.com/guoyao/gogo/x_testing"
)
func TestTempFile(t *testing.T) {
funcName := "TempFile"
content := "hello"
f, err := TempFile("", "", []byte(content))
if err != nil {
t.Error(x_testing.Error(funcName, err, nil))
} else {
defer f... |
package main
import (
"fmt"
)
func main() {
s := "hello, World!"
r := []rune(s)
r[0] = 'H'
s2 := string(r)
fmt.Println(s2)
}
|
package stylei
import (
"database/sql"
"errors"
"fmt"
"time"
"github.com/wgyuuu/storage/stylei/pb"
"github.com/wgyuuu/storage_key"
)
// 结构体方法
func (this *Tes) GetUserId() uint64 {
return this.UserId
}
func (this *Tes) SetUserId(userId uint64) {
this.UserId = userId
}
func (this *Tes) GetLevel() int32 {
ret... |
package netSource
import (
"fmt"
"html/template"
"log"
"net/http"
"testing"
)
var p = &a
var a = 9
const HOST = "0.0.0.0"
const PORT = "8000"
func Test6(tt *testing.T) {
fmt.Println(p, `----------'`)
createHttpServer()
fmt.Println(p, `---777777777777777777-------'`)
}
func createHttpServer() {
http.Han... |
package yahoo
import "net/url"
type client struct {
apiURL url.URL
}
type tick struct {
YesterdayPrice float64 `json:"regularMarketPreviousClose"`
Time int64 `json:"regularMarketTime"`
Price float64 `json:"regularMarketPrice"`
}
type quoteResponse struct {
Result []tick `json:"result"`
}
... |
package controller
import (
"github.com/therecipe/qt/core"
"github.com/therecipe/qt/gui"
"github.com/therecipe/qt/widgets"
)
var colorDialog *widgets.QMainWindow
func initColorDialog() {
colorDialog = widgets.NewQMainWindow(nil, 0)
colorDialog.SetWindowTitle("Dev Color Dialog")
centralWidget := ... |
package utils
import (
i18n2 "github.com/IcanFun/utils/i18n"
"github.com/IcanFun/utils/middleware"
"github.com/IcanFun/utils/utils"
"github.com/IcanFun/utils/utils/log"
)
func InitUtils(s *log.LogSettings, jwtSecret string, api middleware.CheckApiKeyFunc, i18n ...utils.I18n) {
for _, value := range i18n {
i18n... |
package helloworld
import (
"fmt"
"net/http"
)
type API struct {
}
func (a *API) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if len(r.URL.Path) > 9 {
http.Error(w, "Path too long", http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Hello "+r.URL.Path)
}
|
package main
import (
"fmt"
"time"
)
func makeTimestamp() int64 {
return time.Now().UnixNano() / int64(time.Millisecond)
}
func main() {
var t int
var n int
a := []int{1, 3, 5, 11, 19, 100000}
t = 6
t1 := makeTimestamp()
// fmt.Scanf("%d", &t)
for i := 0; i < t; i++ {
// fmt.Scanf("%d", &n)
n = a[i]
... |
func containsDuplicate(nums []int) bool {
memo := make(map[int]bool)
for _, n := range nums {
if _, ok := memo[n]; ok {
return true
}
memo[n] = true
}
return false
}
|
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
// A function returning a channel
c := boring("boring!")
for i:=0; i<5; i++ {
// Read a string from the channel and print it
fmt.Printf("You say: %q\n", <-c)
}
fmt.Println("You're boring; I am leaving.")
}
// A generator function that retur... |
package squares
import "fmt"
func ExampleTrivialSquare() {
g := Game{
board: board{
[SIZE]Piece{RED, 0, RED, 0, 0},
[SIZE]Piece{0, 0, 0, 0, 0},
[SIZE]Piece{RED, 0, RED, 0, 0},
[SIZE]Piece{0, 0, 0, 0, 0},
},
current: RED,
winner: NILPIECE,
}
fmt.Println(g.lostFromPosition(Position{0, 0}))
fmt... |
package main
import (
"fmt"
"io/ioutil"
)
func main() {
path := "C:/Users/hasee/Desktop/文档"
allFile, _ := GetAllFile(path)
dir := dirTras(allFile)
for _, p := range dir {
fmt.Println(p)
}
}
func GetAllFile(pathname string) ([]string, error) {
var res []string
// var allDir string
rd, err := ioutil... |
package 一维数组
// maxSlidingWindow 获取数组在每个窗口的最大值。滑动窗口大小为k,每次向右移动一格。
func maxSlidingWindow(nums []int, k int) []int {
// 1. 初始化。
indexQueue := make([]int, 0) // 双端单调递减队列,存放元素索引。
result := make([]int, 0) // 结果集。
// 2. 获取结果集。
for i := 0; i < len(nums); i++ {
// 2.1 窗口容积优先,如果窗口已满,弹出最先加入窗口的元素。
// (不能使用 k == len... |
package ircbot
import (
"testing"
)
func TestCreation(t *testing.T) {
bot := New("johnny")
if bot == nil {
t.Fatal("bot == nil, want !nil")
}
}
|
package controller
import (
"github.com/reef-pi/reef-pi/controller/storage"
"github.com/reef-pi/reef-pi/controller/telemetry"
)
type controller struct {
t telemetry.Telemetry
s storage.Store
logError telemetry.ErrorLogger
subFn func(s string) (Subsystem, error)
}
func NewController(
t telemet... |
// Copyright 2019 Yunion
//
// 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 writi... |
package main
import (
"fmt"
)
func main() {
s := []int{3, 2, 6, 4, 5}
fmt.Println(productExceptSelf(s))
}
func productExceptSelf(nums []int) []int {
n := len(nums)
res := make([]int, n)
res[0] = 1
for i := 1; i < n; i++ {
res[i] = nums[i-1] * res[i-1]
}
r := 1
for j := n - 1; j >= 0; j-- {
res[j] = ... |
package main
import (
"flag"
"fmt"
"log"
"net"
"os"
"github.com/chenliu1993/SimpleStrike/utils"
)
func main() {
Host := flag.String("host", utils.Host, "server addr")
remotePort := flag.Int("RemotePort", utils.RemotePort, "transfer server addr")
localPort := flag.Int("LocalPort", utils.LocalPort, "local ser... |
package main
import (
"fmt"
"os"
)
const EXIT_FAILURE = 1
func usage() {
fmt.Println("Usage: proxy <port-number>")
os.Exit(EXIT_FAILURE)
}
func main() {
if len(os.Args) != 2 {
usage()
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.