text stringlengths 11 4.05M |
|---|
package patch
// Operation 对资源的操作类型
// 使用 JsonPatchType 进行描述
// 参考: https://jsonpatch.com/
type Operation string
// JsonPatch 中支持的操作
const (
Add Operation = "add"
Remove Operation = "remove"
Replace Operation = "replace"
Copy Operation = "copy"
Move Operation = "move"
Test Operation = "test"
)
//... |
package utils
//
// rand.go
// Copyright (C) 2020 light <light@1870499383@qq.com>
//
// Distributed under terms of the MIT license.
//
import (
"math/rand"
"time"
"unsafe"
)
var letters = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
var size = int32(len(letters))
var seed = rand.New(ra... |
package ravendb
// Note: IndexQueryWithParameters is part of IndexQuery in index_query.go
|
package kus
import (
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
"log"
"mhsykongzhiqi/moxings"
)
func Charuyinpinmimajiu(moxing *moxings.Yinpinmimajius) bool {
cr := Jichucaozuo().Create(moxing)
if cr.Error != nil {
log.Println("Yinpinmimajius----cr.Error---", cr.Error)
return false
}
retu... |
package main
import (
"assist/db"
assist_db "assist/db"
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"sync"
"time"
gorilla_context "github.com/gorilla/context"
"github.com/gorilla/mux"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type AuthenticatedLevel uint8
const (
myself Aut... |
package main
import (
"encoding/json"
"io"
"net/http"
"net/url"
"path"
"github.com/pkg/errors"
"go.uber.org/zap"
)
// Colors is response of api
type Colors struct {
Colors []struct {
Value string `json:"value"`
} `json:"colors"`
}
func decodeBody(body io.Reader, out interface{}) error {
decoder := json.... |
package main
import (
"fmt"
"sort"
"strings"
"github.com/liblxn/lxnc/internal/cldr"
)
type locale struct {
packageName string
tags *tagLookupVar
parentTags *parentTagLookupVar
regionContainment *regionContainmentLookupVar
}
func newLocale(packageName string, tags *tagLookupVar, par... |
package lambdaevent
import (
"encoding/json"
"fmt"
"strings"
)
/*
This file contains functions and types to create data structures from lambda
function input received from lambda. You need to use the associated template
to map values into the structure
*/
type lambdaEvent struct {
m map[string]string
}
// Decod... |
package builder
import (
. "openreplay/backend/pkg/messages"
)
const CLICK_RELATION_TIME = 1400
type deadClickDetector struct {
lastMouseClick *MouseClick
lastTimestamp uint64
lastMessageID uint64
inputIDSet map[uint64]bool
}
func (d *deadClickDetector) HandleReaction(timestamp uint64) *IssueEvent {
var ... |
package model
import (
"github.com/caos/zitadel/internal/model"
"time"
)
type ProjectGrantMemberView struct {
UserID string
GrantID string
ProjectID string
UserName string
Email string
FirstName string
LastName string
DisplayName string
Roles []string
CreationDate t... |
package main
import (
"fmt"
"io"
"net"
"os"
//"bufio"
"bytes"
//"ioutil"
)
func main() {
fmt.Println(os.Args)
if len(os.Args) != 4 {
fmt.Println("prog listen_port remote_host, remote_port")
os.Exit(3)
}
listen_port := os.Args[1]
rmt_host := os.Args[2]
rmt_port := os.Args[3]
fmt.Println("loc... |
package states
import (
"bytes"
"io"
"matrixchain/common/serialization"
"github.com/zhaohaijun/blockchain-crypto/keypair"
)
type BookkeeperState struct {
StateBase
CurrBookkeeper []keypair.PublicKey
NextBookkeeper []keypair.PublicKey
}
func (this *BookkeeperState) Serialize(w io.Writer) error {
this.StateBa... |
package main
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/gameontext/a8-room/pkg/gameon"
)
var exits = map[string]string{
"N": "An old wooden door with a large arrow carved on its center",
"S": "A heavy metal door with signs of rust",
"W": "A gray, plain looking door",
"E": "A door surrou... |
package log
import (
log "github.com/sirupsen/logrus"
)
var logPath string
func init() {
//pwd, _ := os.Getwd()
//path := filepath.Dir(pwd)
//logPath = filepath.Join(path, "log.txt")
//fmt.Println(logPath)
//f, err := os.OpenFile("log.txt", os.O_WRONLY|os.O_CREATE|os.O_APPEND, os.ModePerm)
//if err != ... |
package sliding_window
import "testing"
func TestMaxProfit(t *testing.T) {
subTests := []struct {
input []int
result int
}{
{
input: []int{7, 1, 5, 3, 6, 4},
result: 5,
},
}
for _, test := range subTests {
if s := maxProfit(test.input); s != test.result {
t.Errorf("wanted %v, got %v", test.r... |
package lib
import (
"fmt"
"io/ioutil"
"net/http"
"regexp"
"strconv"
"os"
"strings"
)
type Handler struct {
Conf Config
}
func (slf Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cdn-Source","gocdn")
path := r.URL.Path
//分析path
///bucket/version/filename
// /hashmap/v.1/tes... |
package main
import "fmt"
func main() {
var i, j, length int
//i,j는 두 개의 반복문에 쓰일 변수
fmt.Scanln(&length)
for i = 0; i < length; i++ {
for j = 0; j < i; j++ {
fmt.Print("o ")
}
fmt.Println("* ")
}
} |
package utils
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
)
// Match type
type Match struct {
LeftTeam string `json:"LeftTeam"`
RightTeam string `json:"RightTeam"`
TimeStamp string `json:"TimeStamp"`
}
func getDataFromFile... |
package httpserver
import (
"github.com/gin-gonic/gin"
"xj_web_server/httpserver/activity"
"xj_web_server/httpserver/agent"
"xj_web_server/httpserver/exchange"
"xj_web_server/httpserver/game"
"xj_web_server/httpserver/handle"
"xj_web_server/httpserver/index"
"xj_web_server/httpserver/news"
"xj_web_server/http... |
package utils
import "github.com/pkg/errors"
type AppError struct {
Code int
Err error
}
func (appError *AppError) Error() string {
return appError.Err.Error()
}
func GetAppError(err error, errMsg string, code int) *AppError {
return &AppError{
Code: code,
Err: errors.Wrap(err, errMsg),
}
}
|
package news
import (
"github.com/yogaagungk/newsupdate/model"
)
//Service digunakan sebagai contract
type Service interface {
Save(data *model.News) (model.News, error)
FetchAll(page int) ([]model.News, error)
}
|
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
package prometheusscrape
import (
"testing"
apicommon "github.com/Dat... |
package convert
import (
"fmt"
"strconv"
)
// ToString convert to string
func ToString(str interface{}) string {
switch str.(type) {
case int:
return strconv.Itoa(str.(int))
case int64:
return fmt.Sprintf("%v", str.(int64))
case string:
return str.(string)
case float64:
return fmt.Sprintf("%v", str.(fl... |
package follower
import (
"fmt"
userModel "go_simpleweibo/app/models/user"
"go_simpleweibo/database"
)
// Followers 获取粉丝列表
func Followers(userID, offset, limit int) (followers []*userModel.User, err error) {
followers = make([]*userModel.User, 0)
joinSQL := fmt.Sprintf("inner join %s on users.id = followers.foll... |
package cmd
import (
"fmt"
"io/ioutil"
"os"
log "github.com/Sirupsen/logrus"
qre "github.com/skip2/go-qrcode"
"github.com/spf13/cobra"
qri "github.com/tuotoo/qrcode"
)
var dockerfile, qrfile string
func init() {
dockerqr.AddCommand(qrbuild)
dockerqr.AddCommand(qrimport)
qrbuild.Flags().StringVarP(&dockerf... |
package wkbcommon
import (
"io"
"github.com/paulmach/orb"
)
func readCollection(r io.Reader, order byteOrder, buf []byte) (orb.Collection, error) {
num, err := readUint32(r, order, buf[:4])
if err != nil {
return nil, err
}
alloc := num
if alloc > MaxMultiAlloc {
// invalid data can come in here and allo... |
package main
import "fmt"
func main() {
type vehicle struct {
doors string
color string
}
type truck struct {
vehicle
fourWheel bool
}
type sedan struct {
vehicle
luxury bool
}
t := truck{
vehicle: vehicle{
doors: "conventional",
color: "red"},
fourWheel: true,
}
s := sedan{
vehi... |
package eventchannel
import (
"bytes"
"compress/gzip"
"io"
"math"
"sync"
"testing"
"time"
"github.com/benbjohnson/clock"
"github.com/stretchr/testify/assert"
)
var largeBufferSize = int64(math.MaxInt64)
var largeEventCount = int64(math.MaxInt64)
var maxTime = 2 * time.Hour
func readGz(encoded []byte) strin... |
package parser
import (
"fmt"
"github.com/bingo-lang/bingo/ast"
)
func (p *Parser) parseExpression(precedence Precedence) (expression ast.Expression, err error) {
switch {
case p.tokenIsInteger():
expression, err = p.parseExpressionInteger()
case p.tokenIsBoolean():
expression, err = p.parseExpressionBoolean... |
/*
Copyright 2021 The Skaffold 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, sof... |
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
var a, b int
fmt.Scanf("%d %d", &a, &b)
buffer := bufio.NewReader(os.Stdin)
s, _ := buffer.ReadString('\n')
words, _ := buffer.ReadString('\n')
tokens := strings.Split(words, " ")
w1, w2 := tokens[0], tokens[1]
if a+b == len(strings.Trim... |
package controllers
import (
"github.com/pkg/errors"
kube_core "k8s.io/api/core/v1"
kube_ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"github.com/kumahq/kuma/pkg/core/resources/manage... |
// 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 controller
import (
"fmt"
"strconv"
"github.com/achimonchi/belajar_restapi_mux/src/modules/profile/model"
"github.com/achimonchi/belajar_restapi_mux/src/modules/profile/repository"
)
func GetAll(repo repository.BookRepository) (model.Books, error) {
books, err := repo.FindAll()
if err != nil {
retur... |
/*
* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
*
*/
package dfc_test
import (
"sync"
"sync/atomic"
"testing"
"time"
"runtime/debug"
"github.com/NVIDIA/dfcpub/dfc"
"github.com/NVIDIA/dfcpub/pkg/client"
)
type repFile struct {
repetitions int
filename string
}
type metadata struct ... |
package workspaces
import (
"path/filepath"
"github.com/jenkins-x/jx-helpers/v3/pkg/yamls"
"github.com/jenkins-x/octant-jx/pkg/common/files"
)
type Octants struct {
Octants []Octant
fileName string
}
type Octant struct {
Name string `json:"name"`
Dir string `json:"dir"`
KubeConfigPath ... |
package main
import (
"fmt"
)
func greetings(name string, callback func(string)) {
callback(name)
}
func main() {
greetings("Bryan", func(s string) {
fmt.Println("Greetings!", s)
})
filtered := filter([]int{1, 2, 3, 4, 5}, func(n int) bool {
return n != 5 // change this for testing!
})
fmt.Println(filtere... |
/*
* MinIO Cloud Storage, (C) 2019 MinIO, 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 la... |
package util
import (
"crypto/rand"
"fmt"
"io"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
)
// Store - secure cookie store
var Store = sessions.NewCookieStore(
[]byte(securecookie.GenerateRandomKey(64)), //Signing key
[]byte(securecookie.GenerateRandomKey(32)))
func init() {
Store.Opti... |
// Given a non-empty array of digits representing a non-negative integer, increment one to the integer.
//
// The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
//
// You may assume the integer does not contain any leading zero, ... |
package repository
import (
"editorApi/commons"
"editorApi/init/mgdb"
"editorApi/requests"
"editorApi/responses"
"editorApi/tools/helpers"
"github.com/gin-gonic/gin"
uuid "github.com/satori/go.uuid"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/m... |
package main
import (
"strconv"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
func Limiter (rs *RedisServer) gin.HandlerFunc {
return func(c *gin.Context) {
ip := c.ClientIP()
if err := rs.Lock(); err != nil {
log.Fatalf("database server lock error: %v", err)
}
if !rs.CheckExist(ip... |
package cc
import (
"testing"
)
var threateningTests = []struct {
c uint8 // columns on board
r uint8 // rows on board
p Piece // piece to test
x uint8 // column to place piece
y uint8 // row to place piece
out int // Number of threatened cells
}{
{1, 1, King, 0, 0, 0},
{2, 2, King, 0, 0, 3},
{1... |
package main
import (
"fmt"
"github.com/jmoiron/sqlx"
"strings"
)
type Adapter struct {
*sqlx.DB
CREATE_VERSION_TABLE string
SELECT_VERSIONS string
INSERT_VERSION string
}
var adapters = map[string]func(string) (*Adapter, error){
"postgres": open_postgres,
}
func Open(u string) (*Adapter, error) ... |
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package inputs
import (
"context"
"strings"
"time"
"chromiumos/tast/local/apps"
"chromiumos/tast/local/bundles/cros/inputs/fixture"
"chromiumos/tast/local/bundles/cro... |
package pkg
import (
"testing"
"github.com/mrahbar/kubernetes-inspector/types"
"github.com/stretchr/testify/assert"
"github.com/bouk/monkey"
"os"
"io/ioutil"
"fmt"
"path/filepath"
"path"
)
func TestScp_DirectionUnknown(t *testing.T) {
_, outBuffer, context := defaultContext()
... |
package resolvers
import (
"strconv"
graphql "github.com/graph-gophers/graphql-go"
"github.com/GibJob-ai/GObjob/model"
)
// file response type
type FileResponse struct {
f *model.File
}
func (r *FileResponse) ID() graphql.ID {
id := strconv.Itoa(int(r.f.ID))
return graphql.ID(id)
}
func (r *FileResponse) Ur... |
package address
// import (
// util "github.com/filecoin-project/specs/util"
// )
// Addresses for singleton system actors
var (
InitActorAddr = &Address_I{} // TODO
CronActorAddr = &Address_I{} // TODO
StoragePowerActorAddr = &Address_I{} // TODO
StorageMarketActorAddr = &Address_I{} // T... |
package types
import (
"fmt"
"strings"
log "github.com/sirupsen/logrus"
)
// merge merge string elements together, keeping
// other elements intact
func merge(elements ...interface{}) []interface{} {
result := make([]interface{}, 0, len(elements))
buf := &strings.Builder{}
for _, element := range elements {
... |
// +build windows darwin linux,!arm
package gpio
import (
"time"
)
const (
maxIncremenation = 200000
)
//PulseDuration Duration of a pulse on one pin
func PulseDuration(pin uint8, state uint8) (time.Duration, error) {
startTime := time.Now() // Record time when ECHO goes high
return time.Since(startTime), nil... |
package build
import (
"github.com/zouyx/gopt/input"
"fmt"
"os"
"github.com/zouyx/gopt/message"
"bufio"
)
type StructureBuilder interface {
Build(param *input.Params)
}
const (
SRC_PATH ="%v/src"
FULL_PATH =SRC_PATH+"/main"
)
// based input params get project full path
func getFullPath(params *input.Params... |
package main
import (
"fmt"
"net"
"time"
_ "bytes"
_ "io/ioutil"
_ "bufio"
)
func handleConnection(conn net.Conn) {
fmt.Println("conn handle")
}
func main() {
ln, err := net.Listen("tcp", ":8888")
if err != nil {
fmt.Println("listen err:", err)
}
count := 1
for {
conn, err := ln.Accept()
if err != ... |
package errors
import (
"bytes"
"encoding/json"
"fmt"
"path"
"runtime"
"sync"
)
// Expose additional information for error.
type CustomError interface {
Error() string
GetCode() uint32
GetInner() error
StackAddrs() string
StackFrames() []StackFrame
GetStack() string
GetStackAsJSON() interface{}
GetFullM... |
package main
import (
"fmt"
"net"
"os"
"strings"
"sync"
)
type User struct {
Username string
OtherUsername string
Msg string
ServerMsg string
}
var (
user = new(User)
wg sync.WaitGroup
)
func main() {
wg.Add(1)
fmt.Println("请登陆, 输入用户名: ")
fmt.Scanln(&user.Username)
fmt.Println("请... |
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
//
//+build e2e
package pkg
import (
"path/filepath"
"k8s.io/client-go/kubernetes"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
)
// GetK8s... |
/*
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
distributed under the License ... |
package openstack
import (
"fmt"
"github.com/gophercloud/gophercloud/openstack/imageservice/v2/images"
"github.com/gophercloud/gophercloud/pagination"
)
//go:generate faux --interface imageAPI --output fakes/image_api.go
type imageAPI interface {
GetImagesPager() pagination.Pager
PagerToPage(pager pagination.Pa... |
package productCategoryController
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/thoas/go-funk"
"hd-mall-ed/packages/admin/models/productCategoryModel"
"hd-mall-ed/packages/common/pkg/adminApp"
"hd-mall-ed/packages/common/pkg/e"
"log"
"strconv"
)
func GetList(c *gin.Context) {
api := adminApp.ApiIn... |
package main
import "encoding/binary"
import "io"
import "log"
import "net"
import "math/rand"
import "sync"
import "time"
// Connections object abstracts message sending code for ldr, cas clients
type PacketHeader struct {
PacketID byte
Sequence uint32
Client uint32
KeyLength uint8
DataLength uint16
}
type Pa... |
package main
import (
"fmt"
"math/rand"
"os"
"time"
"github.com/go-mysql-org/go-mysql/canal"
"github.com/go-mysql-org/go-mysql/mysql"
"github.com/go-mysql-org/go-mysql/replication"
)
type MyEventHandler struct {
}
func (h *MyEventHandler) OnRotate(header *replication.EventHeader, rotateEvent *replication.Rot... |
package svrtest
import (
"errors"
"fmt"
"github.com/devwarrior777/atomicswap/libs"
bnd "github.com/devwarrior777/atomicswap/libs/protobind"
"google.golang.org/grpc/status"
)
func testXZC(testnet bool) error {
// Store and re-use:
// - the address from NewAddress
// - contract and contract-tx from Initiate
... |
package eval
// stop go build from complaining about "no non-test Go files" in directory
|
package main
import (
"encoding/json"
"fmt"
"log"
// "net/url"
"os"
"strings"
"net/http"
"bufio"
"strconv"
"bytes"
)
const serverURL = "http://localhost:8080/"
var in *bufio.Reader
type Torrent struct {
Title string
Description string
MagnetLink string
Size string
Downloads int
Seeder... |
package main
import "fmt"
type hotdog int
var x hotdog
func main() {
fmt.Println(x) //zero value
fmt.Printf("%T\n",x) //Printf() %T = type of variable x
x = 42 //equal operator
fmt.Println(x) //value stored in variable
}
//printf = use to print a "type of variable" which this is %T
//UNDERLYING TYPE - s... |
package main
import (
"strconv"
"strings"
"fmt"
)
/*
Additive number is a string whose digits can form additive sequence.
A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.
Given... |
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package encryption
import (
"bytes"
"context"
"io"
"strings"
"testing"
"storj.io/common/ranger"
)
func TestPad(t *testing.T) {
for examplenum, example := range []struct {
data string
blockSize int
padding int
}{
{"... |
package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
sw "github.com/sah4ez/go-bitbucket"
"github.com/urfave/cli"
)
func Review(client *sw.APIClient) cli.Command {
return cli.Command{
Name: "review",
Aliases: []string{"r"},
Description: "start review",
Action: func(c *cli.Context) error... |
package todo
import (
"errors"
"github.com/t-ash0410/tdd-sample/backend/internal/api/todo/entities"
"github.com/t-ash0410/tdd-sample/backend/internal/api/todo/interfaces"
"github.com/t-ash0410/tdd-sample/backend/test/mock"
)
type Repository struct {
ctx *mock.InMemoryContext
}
func NewRepository(ctx *mock.InMe... |
package lloyd
const (
defaultServerName = "red"
XRequestIDHeader = "X-Request-ID"
)
|
package main
import (
"fmt"
"github.com/danjac/go-angular-demo/api"
"log"
"net/http"
"os"
)
func getEnvOrDie(name string) string {
value := os.Getenv(name)
if value == "" {
log.Fatal(fmt.Sprintf("%s is missing", name))
}
return value
}
func getEnvOrDefault(name string, defaultValue string) string {
value... |
// 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 user
import (
"encoding/binary"
"math"
"math/big"
"... |
package worker
import (
"time"
gocontext "context"
"github.com/cenk/backoff"
"github.com/mitchellh/multistep"
"github.com/travis-ci/worker/context"
"go.opencensus.io/trace"
)
type stepGenerateScript struct {
generator BuildScriptGenerator
}
func (s *stepGenerateScript) Run(state multistep.StateBag) multiste... |
package rest
import (
"fmt"
"net/http"
"go/types"
"github.com/json-iterator/go"
)
type IController interface {
IBean
RegisterRoutes() map[string]func(writer http.ResponseWriter,request *http.Request)
HandleRoutes(writer http.ResponseWriter, request *http.Request)(func(writer http.ResponseWriter, request *http.R... |
// Copyright 2017 Walter Schulze
//
// 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 common
import (
"net/http"
"os"
"strings"
)
//GetRequestURL 获取请求的URL
func GetRequestURL(request *http.Request) string {
scheme := "http://"
if request.TLS != nil {
scheme = "https://"
}
return strings.Join([]string{scheme, request.Host, request.RequestURI}, "")
}
//PathExist 路径是否存在
func PathExist(p... |
// Copyright 2020 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, ... |
// 155.Hands-on exercise#2 此练习将加强我们对方法集的理解 method
// A繼續往下走因為沒通行證human所以不能過
// B回源頭指向human 因為有碰到所以判定可以過(interface有type OR 能用func***()就算)?
// receiver = 接收器
package main
import (
"fmt"
)
type Person struct {
First string
}
type Human interface {
say()
}
func main() {
p1 := Person{
First: "p1a",
}
//因為往回指... |
package main
import (
"net/http"
"fabulous-fox/controllers"
"fabulous-fox/db"
"fabulous-fox/utility"
"github.com/gorilla/mux"
)
func main() {
router := mux.NewRouter()
router.Use(CommonMiddleware())
apiSubrouter := router.PathPrefix("/api").Subrouter()
v1Subrouter := apiSubrouter.PathPrefix("/v1").Subroute... |
package main
import (
"bufio"
"fmt"
"log"
"math"
"os"
"strconv"
"time"
)
func main() {
partOne()
partTwo()
}
func calcFuel(fuel float64, total float64) float64 {
div := math.Floor(float64(fuel)/3.0) - 2.0
if div <= 0.0 {
return total
} else {
total += div
return calcFuel(div, total)
}
}
func part... |
// Copyright 2016 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, ... |
package chanPool
// 工作
type Job func()
|
package libp2p
import "github.com/libp2p/go-libp2p-core/protocol"
const (
// PandoProtocolID is the libp2p protocol that pando API uses
PandoProtocolID protocol.ID = "/Pando/libp2p/0.0.1"
)
|
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
"os"
"strconv"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/api/{x}/add/{y}", addHandler).Methods("GET")
r.HandleFunc("/api/{x}/sub/{y}", subHandler).Methods("GET")
r.HandleFunc("/api/{x}/mult/{y}", multHandler).Me... |
package run
import (
"context"
"math/rand"
"time"
)
// WithRetry enables an application to handle transient failures by transparently retrying a failed operation.
func WithRetry(backoffs []time.Duration, classifier func(error) Result, fn func(context.Context) error) func(context.Context) error {
rnd := rand.New(r... |
// Copyright (C) 2018 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 users
import (
"github.com/BalkanTech/goilerplate/config"
db "github.com/BalkanTech/goilerplate/databases"
"testing"
"strconv"
"gopkg.in/mgo.v2/bson"
"github.com/jinzhu/gorm"
"gopkg.in/mgo.v2"
)
const testOK = "\u2714"
const testFailed = "\u2718"
var GormConfig = &config.Config{
Database: config.Dat... |
package main
import "fmt"
func main() {
// Go has type inference
x := "string"
// The + operator also does concatenation.
x += "string"
// Constants:
const i int = 0
// Multiple variables:
var (
a = 0
b = 1
c = 2
)
// Multiple constants:
const (
d = 3
e = 4
)
}
|
// 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 main
type course struct {
jsonobj map[string]interface{}
name string
constraints *constraints
}
type lecture struct {
coursejsonobj map[string]interface{}
course *course
jsonobj map[string]interface{}
constraints *constraints
assignedInstructor *instructor
instructorCandi... |
package builder_test
import (
"testing"
"time"
"github.com/sohaha/zlsgo"
"github.com/zlsgo/zdb"
"github.com/zlsgo/zdb/builder"
"github.com/zlsgo/zdb/driver"
"github.com/zlsgo/zdb/driver/mssql"
"github.com/zlsgo/zdb/driver/mysql"
"github.com/zlsgo/zdb/driver/postgres"
"github.com/zlsgo/zdb/driver/sqlite3"
"... |
package shoppingCartController
import (
"github.com/gin-gonic/gin"
"hd-mall-ed/packages/client/models/shoppingCartModel"
"hd-mall-ed/packages/common/pkg/app"
"hd-mall-ed/packages/common/pkg/e"
)
/*
参数 idList 就行
*/
func Delete(c *gin.Context) {
api := app.ApiFunction{C: c}
model := &shoppingCartModel.ShoppingCa... |
package main
import (
"fmt"
"strconv"
"strings"
"unicode"
)
func main() {
fmt.Println(myAtoi((" ")))
}
func myAtoi(s string) int {
// s should begin with number or sign
// 1. Trim spaces
sFormatted := strings.TrimLeft(s, " ")
sign := 1
startingInd := -1
endingInd := -1
signed := false
// 2. Search a... |
package odoo
import (
"fmt"
)
// StockChangeProductQty represents stock.change.product.qty model.
type StockChangeProductQty struct {
LastUpdate *Time `xmlrpc:"__last_update,omptempty"`
CreateDate *Time `xmlrpc:"create_date,omptempty"`
CreateUid *Many2One `xmlrpc:"create_uid,om... |
package main
import (
"fmt"
"math"
"strconv"
)
func reverseStr(str string) string {
length := len(str)
var reversedStr string
for charIdx := 0; charIdx < length; charIdx++ {
reversedStr = string(str[charIdx]) + reversedStr
}
return reversedStr
}
func binaryToDecimal(bits string) float64 {
var base float64... |
package HashCashProject
import (
"encoding/json"
"encoding/xml"
// "fmt"
zmq4 "github.com/pebbe/zmq4"
"io/ioutil"
"os"
"strconv"
"strings"
//"image/gif"
)
type sendString struct {
Pid int
MsgId int
Msg string
}
type sendint struct {
Pid int
MsgId int
Msg int
}
//to store info written in JSon ... |
package main
import (
"log"
"net/http"
)
func homePage(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello World!!"))
}
func usersPage(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Load users page!!"))
}
func main() {
//HTTP é um protocolo de comunicação
//Cliente (Faz requisição) - Se... |
package helpers
type ParsedParam struct {
ParamType `json:",inline"`
Line int `json:"linenumber"`
Loc []int `json:"location"`
Default string `json:"default"`
}
type ParamType struct {
Category string `json:"category"`
Name string `json:"name"`
}
type Template struct {
Name string ... |
// Copyright 2020 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, ... |
package linqo
import "testing"
func TestSelect(t *testing.T) {
const expected = `SELECT firstName,lastName FROM customers WHERE ((totalSpending BETWEEN 100 AND 1000) OR (totalSpending >= 10000)) ORDER BY lastName DESC,firstName DESC;`
stmt := Select("firstName", "lastName").
From("customers").
Where(Or(
Bet... |
package v1_test
import (
"testing"
knewer "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
/*kolder "github.com/GoogleCloudPlatform/kubernetes/pkg/api/v1"*/
newer "github.com/openshift/origin/pkg/build/api"
older "github.com/openshift/origin/pkg/build/api/v1"
)
var Convert = knewer.Scheme.Convert
func Test... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.