text stringlengths 11 4.05M |
|---|
//+build wireinject
package os
import (
"github.com/google/wire"
"github.com/raba-jp/primus/pkg/backend"
"github.com/raba-jp/primus/pkg/operations/os/starlarkfn"
"github.com/raba-jp/primus/pkg/starlark"
)
func IsDarwin() starlark.Fn {
wire.Build(
backend.NewExecInterface,
starlarkfn.IsDarwin,
)
return nil... |
package gobucket
import (
"fmt"
"net/http"
"reflect"
"testing"
)
func TestPullRequestsService_GetAll(t *testing.T) {
setUp()
defer tearDown()
mux.HandleFunc("/2.0/repositories/batman/batcave/pullrequests/", func(w http.ResponseWriter, r *http.Request) {
if m := "GET"; m != r.Method {
t.Errorf("Request me... |
package system
import "github.com/fanda-org/postmasters/database/models"
// Contact model
type Contact struct {
models.Base
Salutation *string `gorm:"size:5"`
FirstName *string `gorm:"size:50;index:ix_contact_firstname"`
LastName *string `gorm:"size:50"`
Email *string `gorm:"size:100;index:ix_contact... |
package main
import (
"io"
"mime"
"net/http"
"path/filepath"
)
func main() {
http.HandleFunc(`/`, serveFile)
if err := http.ListenAndServe(`:80`, nil); err != nil {
panic(err)
}
}
func serveFile(w http.ResponseWriter, r *http.Request) {
fileMime := mime.TypeByExtension(filepath.Ext(r.URL.Path))
w.Header(... |
/*
Package file implements an output module for logging to a file using rlog.
*/
package file
import (
"fmt"
"github.com/rightscale/rlog/common"
"os"
"path/filepath"
)
//Configuration of file logging module
type fileLogger struct {
removeNewlines bool
fileHandle *os.File
loggedError bool
}
//NewFileLog... |
package filedb
import (
"bufio"
"bytes"
"encoding/json"
"log"
"os"
"github.com/josetom/go-chain/db/types"
)
type FileDbIterator struct {
db *os.File
start []byte
limit []byte
scanner *bufio.Scanner
hasSeeked bool
key []byte
value []byte
}
func newFileDbIterator(dbPath string, start []byte, limit... |
package main
import (
"bytes"
"encoding/base64"
"fmt"
"io/ioutil"
"log"
)
// 实现了base64编码
func main() {
// 声明内容
var origin = []byte("Hello World!")
// 声明buffer
var buf bytes.Buffer
// 自定一个64字节的字符串
var customEncode = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
// 使用给出的字符集生成一个*base64... |
package main
import (
"fmt"
"os"
"github.com/lorenzoranucci/bookmark-search-backend/internal/pkg/infrastructure/cli"
)
var version = "dev"
var app = cli.GetApp(version)
func main() {
err := app.Run(os.Args)
if err != nil {
fmt.Println(err.Error())
}
}
|
package TestPerformance
import (
"fmt"
"reflect"
"testing"
"unsafe"
)
func Test_append(t *testing.T) {
arr1 := [5]int{1, 2, 3, 4, 5}
fmt.Printf("2th of arr1 addr: %x\n", unsafe.Pointer(&arr1[1]))
slice1 := arr1[1:2]
fmt.Printf("slice1: len is %d, cap is %d\n", len(slice1), cap(slice1))
fmt.Printf("slice1 dat... |
package public
import (
"github.com/go-on/app"
"net/http"
)
type Public struct {
*app.Dispatcher
}
func (p *Public) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
p.Dispatcher.ServeHTTP(rw, r)
}
// the empty mountpath is the fallback for every path
func (p Public) MountPath() app.MountPath {
return app.M... |
package tracks
import (
"errors"
"fmt"
"math/rand"
"time"
)
var (
ErrTrackNotExists = errors.New("Track not exists")
ErrGenerateFailed = errors.New("Fail to generate UUID")
)
type Tracks map[string]*Track
// track结构中现在只有一个path, 之后还会添加信息
type Track struct {
path string
playlist string
}
func (tk Track)... |
package ch2
//调用独立的c代码,这种情况适用于调用复杂的C代码
//下面的代码前两行告诉了go程序在哪里找callC.h和callC.a
//#cgo CFLAGS: -I${SRCDIR}/clib
//#cgo LDFLAGS: ${SRCDIR}/clib/callC.a
//#include <stdlib.h>
//#include <callC.h>
import "C"
import (
"fmt"
"unsafe"
)
func callSeparateCCode() {
fmt.Println("Going to call a C function!")
C.cHello()
fmt.... |
package typecheck
import (
"fmt"
"github.com/stephens2424/php/ast"
)
// Walker is a walker
type Walker struct {
ast.DefaultWalker
}
func (w *Walker) Walk(node ast.Node) {
switch n := node.(type) {
case ast.Block:
for _, stmt := range n.Statements {
w.Walk(stmt)
}
case *ast.IfStmt:
for _, branch := ra... |
package mongo
import (
"2C_vehicle_ms/pkg"
"log"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"github.com/night-codes/mgo-ai"
//"reflect"
)
type VehicleService struct {
collection *mgo.Collection
//hash root.Hash
}
func NewVehicleService(session *Session, dbName string, collectionName string) *VehicleServi... |
package main
import (
"os"
"strconv"
"strings"
"time"
logging "github.com/op/go-logging"
)
// Logger
var log = logging.MustGetLogger("libivrt-app")
var app appState
// Main function
func main() {
app.started = time.Now()
format := logging.MustStringFormatter(
"%{color}%{time:15:04:05.000} %{shortfunc} ▶ \t... |
package main
type specialForm func(args []interface{}, env map[string]interface{}) (interface{}, error)
type variadicProc struct {
param string
body func(env map[string]interface{}) (interface{}, error)
}
type proc struct {
params []string
body func(env map[string]interface{}) (interface{}, error)
}
|
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package encryption
import (
"bytes"
"io"
"testing"
"storj.io/common/testrand"
)
func TestAesGcm(t *testing.T) {
key := testrand.Key()
var firstNonce AESGCMNonce
testrand.Read(firstNonce[:])
encrypter, err := NewAESGCMEncrypter(&... |
//nolint:unparam // we don't care about these linters in test cases
package backoff
import (
"context"
"errors"
"math"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
var errTest = errors.New("test")
const (
intervalDelta = 100 * time.Millisecond // allowed deviation to pass the test
retryCo... |
package main
import (
"bufio"
"fmt"
"os"
"sort"
)
var writer = bufio.NewWriter(os.Stdout)
var reader = bufio.NewReader(os.Stdin)
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{}) { fmt.Fscanf(reader, f, a...) }
type Person struct {
age int
order... |
// date: 2019-03-18
package broker
|
/*
Copyright 2018 The Tilt Dev Authors
Copyright 2023 Docker Compose CLI 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
... |
package ch07
// Stack
func trap(height []int) int {
result := 0
stack := []int{}
for i, h := range height {
for len(stack) > 0 && height[stack[len(stack)-1]] < h {
top := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if len(stack) == 0 {
break
}
leftHeight := height[stack[len(stack)-1]]
... |
package iafon
import (
"net/http"
)
type Context struct {
Rsp http.ResponseWriter
Req *http.Request
Param map[string]string
Udata map[string]interface{}
}
|
// 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, ... |
/*
Copyright 2019 The Kubernetes 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, ... |
package etherscan
import (
"github.com/gin-gonic/gin"
"github.com/trustwallet/blockatlas/pkg/logger"
"net/http"
)
func (p *Platform) getBalance(c *gin.Context) {
token := c.Query("token")
address := c.Param("address")
var err error
var balance string
if token != "" {
//srcPage, err = p.client.GetTokenBalan... |
package utils
import (
"os"
"strings"
jsoniter "github.com/json-iterator/go"
)
// PrintAsJSON prints the provided value as YAML document to the console
func PrintAsJSON(data any) error {
j, err := ConvertToJSON(data)
if err != nil {
return err
}
PrintMessage(j)
return nil
}
// WriteToFileAsJSON converts t... |
package main
import "fmt"
// Action represents a move made by a player over the course of a game.
type Action struct {
mark rune
row, col int
}
func (a Action) String() string {
return fmt.Sprintf("%q in (%d, %d)", a.mark, a.row, a.col)
}
|
package main
import (
"flag"
"log"
"os"
"github.com/gongo/go-airplay"
)
var opts struct {
position float64
showHelpFlag bool
}
func init() {
flag.Float64Var(&opts.position, "p", 0.0, "Number of seconds to move (second)")
flag.BoolVar(&opts.showHelpFlag, "h", false, "Show this message")
flag.Parse()
i... |
package main
import (
"fmt"
// "fmt"
"github.com/gorilla/websocket"
"log"
"math/rand"
"net/http"
"regexp"
"strings"
"time"
)
const (
f_date = "2006-01-02" //长日期格式
f_shortdate = "06-01-02" //短日期格式
f_times = "15:04:05" //长时间格式
f_shorttime = "15:04" ... |
package main
import (
"fmt"
"math"
)
const min = 2
func main() {
primeNum := []int{}
// * The Channel is how to communicate between main() function and GoRoutine.
// * It's How to Communicate by putting Channel as a Parameter instead of returning Something.
channel := make(chan int)
// * This is the GoRouti... |
package main
// 1. 使用 make 创建 map 变量时可以指定第二个参数,不过会被忽略。
// 2. cap() 函数适用于数组、数组指针、slice 和 channel,不适用于 map,可以使用 len() 返回map的元素个数。
func main() {
m := make(map[string]int, 2)
cap(m)
}
|
package main
import (
"fmt"
)
type Point struct {
Lat float64
Long float64
}
type Coordinate struct {
X float64
Y float64
}
func main() {
a := Point{
Lat: 35.677568,
Long: 139.717064,
}
b := Point{
Lat: 35.677542,
Long: 139.716965,
}
fmt.Println(direction(a, b))
fmt.Println(direction(b, a))
... |
package controllers
import (
"html/template"
"net/http"
"appengine"
"appengine/datastore"
"time"
"fmt"
"github.com/gorilla/mux"
"github.com/gorilla/securecookie"
"models"
"tools"
)
var wikiSecret []byte = securecookie.GenerateRandomKey(32)
var wikiUserIdCookie *securecookie.SecureCookie
var currentUser *mo... |
package util
import (
"fmt"
"os"
"time"
)
var (
pid = os.Getpid()
)
// NewTraceID 创建追踪ID
func NewTraceID() string {
return fmt.Sprintf("trace-id-%d-%s",
pid,
time.Now().Format("2006.01.02.15.04.05.999999"))
}
|
// Copyright 2018 The gVisor 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 agree... |
package content
import (
"bytes"
"compress/gzip"
"encoding/base64"
"io"
"strings"
)
func GUnzip(content []byte) ([]byte, error) {
r, err := gzip.NewReader(bytes.NewBuffer(content))
if err != nil {
return nil, err
}
return io.ReadAll(r)
}
func Base64GZ(data []byte) (string, error) {
gz, err := Gzip(data)
... |
package telegram
import (
"fmt"
"log"
"os"
"syscall"
"github.com/c0re100/RadioBot/config"
"github.com/c0re100/go-tdlib"
"golang.org/x/crypto/ssh/terminal"
)
var (
bot *tdlib.Client
botID int32
userBot *tdlib.Client
userBotID int32
)
// New create telegram session
func New() (*tdlib.Client, *t... |
package lastfm
import (
"bufio"
"bytes"
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"log"
"net/url"
"os"
"sort"
"time"
"github.com/spf13/viper"
)
var (
token, sk string
tokenExpired int64
)
// Authentication Guide:
// https://www.last.fm/api/desktopauth
// Step 1. GetToken
// Step 2. Authenti... |
func swapPairs(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
// h(1)
// l r n
// 1->2->3->4->
// l(1) r(2) h(3)
// l(1)->(3); r(2)->(1); p(1)
// l(3) r(4) h(5)
// l(3)->(5); r(4)->(3); p(1)->(4); p(3)
newHead := head.Next
var prev *ListNode
for {
if head == nil || hea... |
package main
import (
"bufio"
"fmt"
"net"
"os"
"runtime"
"sync/atomic"
"time"
)
var connCount int64
func connect() {
defer func() {
atomic.AddInt64(&connCount, -1)
}()
atomic.AddInt64(&connCount, 1)
conn, err := net.Dial("tcp", "127.0.0.1:8080")
if err != nil {
fmt.Printf("err:%s\n", err)
return
... |
package router
import (
"belajar/reservation/pkg/v1/header"
"belajar/reservation/pkg/v1/utils/errors"
"context"
"fmt"
"github.com/kenshaw/envcfg"
"github.com/gorilla/handlers"
"github.com/sirupsen/logrus"
gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime"
"google.golang.org/grpc"
"log"
"net/http"
"... |
package main_test
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_Something(t *testing.T) {
assert.Equal(t, "string", "string")
}
func Test_SomethingElse(t *testing.T) {
assert.Equal(t, "string", "string")
}
func Test_EvenMore(t *testing.T) {
assert.Equal(t, "string", "string")
}
|
//line sql.y:6
package sqlparser
import __yyfmt__ "fmt"
//line sql.y:6
import "strings"
func setParseTree(yylex interface{}, stmt Statement) {
yylex.(*Tokenizer).ParseTree = stmt
}
func setAllowComments(yylex interface{}, allow bool) {
yylex.(*Tokenizer).AllowComments = allow
}
func incNesting(yylex interface{})... |
package main
import (
"flag"
"github.com/michaelvlaar/etcd-endpointer/examples/echoservice/api/protos"
"golang.org/x/net/context"
"google.golang.org/grpc"
"gopkg.in/inconshreveable/log15.v2"
"time"
)
var (
endpoint = flag.String("endpoint", ":9090", "GeneralsView API endpoint. Usage <host>:<port>.")
userID ... |
// Copyright 2014 Joseph Hager. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package engi
import (
"math"
"time"
)
type Clock struct {
elapsed float64
elapsedStep float64
step float64
numStep uint32
delta floa... |
// Tomato static website generator
// Copyright Quentin Ribac, 2018
// Free software license can be found in the LICENSE file.
package main
import (
"fmt"
"reflect"
"testing"
)
func TestSiteinfo_MainAuthorHelper(t *testing.T) {
testCases := []struct {
siteinfo Siteinfo
want string
}{
{Siteinfo{Authors... |
package handlers_test
import (
"bosh-dns/dns/server/handlers"
"bosh-dns/dns/server/handlers/handlersfakes"
"bosh-dns/dns/server/internal/internalfakes"
"bosh-dns/dns/server/monitoring/monitoringfakes"
"github.com/miekg/dns"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ bool = Describe("metrics... |
package core
import (
"gonum.org/v1/gonum/floats"
"gonum.org/v1/gonum/stat"
"math"
)
/* Table */
// DataTable is an array of (userId, itemId, rating).
type DataTable struct {
Ratings []float64
Users []int
Items []int
}
// NewDataTable creates a new raw data set.
func NewDataTable(users, items []int, ratin... |
package main
import (
"fmt"
m "math"
"github.com/MaxHalford/gago"
)
func simulate(start, end int) []float64 {
data := []float64{}
for x := start; x <= end; x++ {
value := 1 * m.Pow(float64(x), 2)
data = append(data, value)
}
return data
}
var (
data = simulate(1, 20)
)
func leastSquares(X []float64) fl... |
package main
import "fmt"
type person struct {
first string
last string
flavor string
}
func main() {
p1 := person{
first: "Jonathan",
last: "Thompson",
flavor: "chocolate",
}
p2 := person{
first: "Nicole",
last: "Thompson",
flavor: "vanilla",
}
fmt.Println(p1, p2)
for _, v := range ... |
// Copyright 2020 The gVisor 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 agree... |
package main
import "github.com/newmizanur/forumapi/api"
func main() {
api.Run()
}
|
package optional
import (
"errors"
"reflect"
)
type Optional interface {
Map(func(o interface{}) interface{}) Optional
OrElse(interface{}) interface{}
IsPresent() bool
Get() (interface{}, error)
}
type OptionalImpl struct {
value interface{}
}
func (op *OptionalImpl) Map(fn func(o interface{}) interface{}) O... |
// 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 phonehub
import (
"context"
"regexp"
"time"
"chromiumos/tast/ctxutil"
"chromiumos/tast/local/chrome/ash"
"chromiumos/tast/local/chrome/crossdevice"
"chromium... |
package slices
import "fmt"
func main() {
simpleSlice := make([]string, 3)
fmt.Println("empty slice: ", simpleSlice)
// adds values to slice
simpleSlice[0] = "a"
simpleSlice[1] = "b"
simpleSlice[2] = "c"
fmt.Println("set:", simpleSlice)
fmt.Println("get:", simpleSlice[2])
fmt.Println("length:", len(simpleSli... |
package multirun
import (
"errors"
"math/rand"
"sync"
"testing"
"time"
)
var globalMutex sync.Mutex
var isNotReady bool
var errorNewRun = errors.New("A new run method was started before we were ready")
type SimpleRunnable struct {
t *testing.T
RunnableReady
sync.Mutex
closed bool
c chan (struct{})
... |
// Copyright 2017 Baidu, 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 in writing... |
package middleware
import (
"github.com/gin-gonic/gin"
"github.com/Charelyz/gin-mgo-demo/db"
"net/http"
"strings"
)
// 数据库连接中间件:克隆每一个数据库会话,并且确保 `db` 属性在每一个 handler 里均有效
func Connect (context *gin.Context){
s := db.Session.Clone()
defer s.Clone()
context.Set("db",s.DB(db.Mongo.Database))
context.Next()
}
c... |
package api
import (
"net/http"
"github.com/thetogi/YReserve2/api/wrapper"
"github.com/thetogi/YReserve2/model"
)
func (a *API) InitUser() {
// swagger:operation POST /user user users
// ---
// summary: Create new user
// description: Send email with other user details to create new user. Email must be unique... |
package order
import (
"context"
"time"
"github.com/benkim0414/bundle/bundle"
"github.com/go-kit/kit/endpoint"
"github.com/go-kit/kit/log"
)
type Endpoints struct {
OrderEndpoint endpoint.Endpoint
}
// MakeServerEndpoints returns an Endpoints struct where each endpoint invokes
// the corresponding method on t... |
// Copyright 2015 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, ... |
// Copyright 2019 Red Hat, Inc. and/or its affiliates
//
// 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 applic... |
package main
import (
"cloud.google.com/go/compute/metadata"
"cloud.google.com/go/profiler"
"context"
"contrib.go.opencensus.io/exporter/stackdriver"
"contrib.go.opencensus.io/exporter/stackdriver/propagation"
"fmt"
"github.com/gin-gonic/gin"
"go.opencensus.io/plugin/ochttp"
"go.opencensus.io/trace"
"io/iout... |
package user
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"log"
)
type UserRepository interface {
Create(*User, *mongo.Database) error
MultiInsert([]interface{}, *mongo.Database) error
MultiDelete(interface{}, *mongo.Dat... |
package air
import (
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/BurntSushi/toml"
"github.com/integrii/flaggy"
)
// AppName is the name of the current web application.
//
// It is called "app_name" in the configuration file.
var AppName = "air"
// MaintainerEmail is t... |
package main
type X struct {
Xa int
Xb int
Xy Y
}
type Y struct {
Ya int
Yb int
}
func main() {
x := X{
Xy: Y{
}
|
// GOG
package main
var a string
func main() {
a = "G"
print(a)
f1()
}
func f1() {
a := "O"
print(a)
f2()
}
func f2() {
// 注意, 这里 f2 定义的位置的作用域获得的 a 是全局的
// 而不是 f1 中调用时使用 f1 的 a
// 这个值在编译时已经决定好了
print(a)
}
|
package main
import "fmt"
func main() {
cards := newDeck()
cards.shuffle()
hand1, _ := deal(cards, 5)
hand2, _ := deal(cards, 5)
fmt.Println(hand1, hand2)
}
|
package tests
import (
"testing"
ravendb "github.com/ravendb/ravendb-go-client"
"github.com/stretchr/testify/assert"
)
func NewUsersInvalidIndex() *ravendb.IndexCreationTask {
res := ravendb.NewIndexCreationTask("UsersInvalidIndex")
res.Map = "from u in docs.Users select new { a = 5 / u.Age }"
return res
}
fu... |
// Copyright 2015 Apcera Inc. All rights reserved.
// Package aws provides a standard way to create a virtual machine on AWS.
package aws
import (
"errors"
"fmt"
"net"
"time"
"github.com/apcera/libretto/ssh"
"github.com/apcera/libretto/util"
"github.com/apcera/libretto/virtualmachine"
"github.com/aws/aws-sdk... |
package main
import (
"encoding/csv"
"fmt"
"io"
"os"
"regexp"
"strings"
)
func readCsvCn(srcStr string, fp *os.File, outfile string) {
f, err := os.Create(outfile + ".txt")
checkErr(err)
db := csv.NewReader(fp)
for {
db, err := db.Read()
if err == io.EOF {
break
}
matchedCn, err := regexp.Matc... |
package main
import (
"bufio"
"bytes"
"fmt"
"github.com/Yprolic/TomlConfiguration"
"io"
"io/ioutil"
"log"
"math"
"net/http"
"os"
"sort"
"strings"
"sync"
"time"
)
//Config 全局配置类
type Config struct {
Input string
ErrorLog string
User int
Timeout int
Url string
}
//Conf 全局配置
var (
Conf ... |
package packer
import (
"bytes"
"crypto/rand"
"fmt"
"io"
"io/ioutil"
"log"
rand2 "math/rand"
"os"
"path/filepath"
"reflect"
"sync"
"testing"
"time"
)
func TestMarshalUnMarshal(t *testing.T) {
var fromBin = func(data []byte) (*fileHeader, error) {
r := bytes.NewReader(data)
return unMarshallBinary(r... |
package rigger
import (
"github.com/AsynkronIT/protoactor-go/actor"
"github.com/sirupsen/logrus"
"time"
)
const allApplicationTopSupName = "@rg$0"
func init() {
Register(allApplicationTopSupName, SupervisorBehaviourProducer(func() SupervisorBehaviour {
return &applicationTopSup{}
}))
}
type applicationTopSup ... |
package main
func main() {}
func bonus(sales []int) int {
minSaleValue := 10_000
for _, sale := range sales {
if sale >= minSaleValue {
percent := 100
bonusValue := 5
managerBonus := (sale / percent) * bonusValue
return managerBonus
}
}
return 0
}
|
package sort
func Merge(list []int) {
if len(list) <= 1 {
return
}
msort(list, 0, len(list)-1)
}
func msort(list []int, start, end int) {
if start == end {
return
}
min := (end-start)/2 + start
msort(list, start, min)
msort(list, min+1, end)
merge(list, start, min, end)
}
func merge(list []int, start... |
package ravendb
// Note: Java's IAttachmentsSessionOperations is DocumentSessionAttachments
// TODO: make a unique wrapper type
type AttachmentsSessionOperations = DocumentSessionAttachments
type DocumentSessionAttachments struct {
*DocumentSessionAttachmentsBase
}
func NewDocumentSessionAttachments(session *InMem... |
package main
import (
"fmt"
"gopkg.in/ldap.v2"
)
// getBaseDN construct the baseDN out of the baseDNTemplate containing %s
// that would be replaced by username
func getBaseDN(dnTemplate, username string) string {
return fmt.Sprintf(dnTemplate, username)
}
func ldapChangePassword(cfg *config, username, userdn, p... |
package controllers
import (
"github.com/gin-gonic/gin"
)
//Register register API routes
func Register(group gin.IRouter) {
group.GET("/health-check", HealthCheck)
planets := group.Group("/planets")
planets.GET("/", Planets)
planets.POST("/", Planet)
planets.GET("/:id", Planet)
planets.DELETE("/:id", Planet)
... |
// See License for license information.
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
package main
import (
"fmt"
"net/http"
"net/url"
"github.com/pkg/errors"
"github.com/mattermost/mattermost-server/v6/model"
"github.com/mattermost/mattermost-plugin-jira/server/utils/types"
)
const (
... |
package server
import (
"2C_vehicle_ms/pkg"
"log"
"net/http"
"os"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
type Server struct {
router *mux.Router
}
func NewServer(v root.VehicleService, f root.FavrouteService) *Server {
s := Server{router: mux.NewRouter()}
NewVehicleRouter(v, s.newSubroute... |
package version
import "fmt"
var (
APPNAME = "Unknown"
BRANCH = "Unknown"
TAG = "Unknown"
REVISION = "Unknown"
BUILDTIME = "Unknown"
GOVERSION = "Unknown"
BINDVERSION = "Unknown"
)
func String() string {
return fmt.Sprintf(`-----------------------------------------
-------------------------------------... |
package ru_test
import (
"testing"
"time"
"github.com/olebedev/when"
"github.com/olebedev/when/rules"
"github.com/olebedev/when/rules/ru"
)
func TestHourMinute(t *testing.T) {
w := when.New(nil)
w.Add(ru.HourMinute(rules.Override))
fixtok := []Fixture{
{"5:30вечера", 0, "5:30вечера", (17 * time.Hour) + (3... |
package sorts
// QuickSort sort
func QuickSort(a []int, p, r int) {
if p < r {
i := partitionHoare(a, p, r)
QuickSort(a, p, i-1)
QuickSort(a, i+1, r)
}
}
// SortK get kth ordered element, kth will be the final index,
// the array will be partitioned for kth element
func SortK(a []int, k int) int {
n := len(a... |
// Showcase the usage of strings in Go.
package main
import (
"fmt"
"strings"
)
func hasSuffix() {
s := "Hello, World!"
fmt.Printf("s: %v\n", s)
suffix := "World"
fmt.Printf("Has suffix \"%v\": %v\n", suffix, strings.HasSuffix(s, suffix))
suffix = "World!"
fmt.Printf("Has suffix \"%v\": %v\n", suffix, s... |
package main
import (
"testing"
"github.com/monax/peptide/cmd/protoc-gen-go-peptide/testdata/gogo"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
)
func TestGogo(t *testing.T) {
t.Run("Test gogogo", func(t *testing.T) {
msg := &gogo.TestMessage{
WithMoreTags: "tagly",
WithJsonT... |
// 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 bluetooth
import (
"context"
"time"
"chromiumos/tast/remote/bluetooth"
"chromiumos/tast/testing"
)
func init() {
testing.AddTest(&testing.Test{
Func: ... |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may ... |
package main
import (
"fmt"
"os"
"golang.org/x/net/html"
)
func forEachNode(n *html.Node, pre, post func(n *html.Node) bool) *html.Node {
if pre != nil {
if !pre(n) {
return n
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
if res := forEachNode(c, pre, post); res != nil {
return res
}
... |
package rest_grab
// A Receiver is a type that performs its own logic related to
// receiving data from a request. This is useful for password types
// (to automatically hash the value) or anything that needs to perform
// some type of validation.
type Puller interface {
// Receive takes a value (as would be sent in... |
package goinstagrab
import (
"encoding/json"
"io/ioutil"
"log"
"os"
"github.com/iveronanomi/goinstagrab/crawler"
)
// Dump ...
var Dump *dump
type dump struct {
Users map[string]string `json:"users"`
Media map[string]map[string]map[string]bool `json:"scanned"`
Conversatio... |
package main
import (
"github.com/gorilla/context"
"log"
"net/http"
"strconv"
)
func main() {
//http.Handle("/",context.ClearHandler(http.HandlerFunc(myHander)))
// 自动清除
http.HandleFunc("/", myHander)
log.Fatal(http.ListenAndServe(":9999", nil))
}
func myHander(rw http.ResponseWriter, r *http.Request) {
con... |
package wasmvm
import (
"bytes"
"github.com/zhaohaijun/matrixchain/common"
"github.com/zhaohaijun/matrixchain/core/states"
scommon "github.com/zhaohaijun/matrixchain/core/store/common"
"github.com/zhaohaijun/matrixchain/errors"
"github.com/zhaohaijun/matrixchain/vm/wasmvm/exec"
"github.com/zhaohaijun/matrixcha... |
package main
import (
"log"
"net/http"
"net/http/httputil"
"net/url"
"flag"
"strings"
"path/filepath"
"os"
)
type handle struct {
reverseProxy string
}
func substring(source string, start int, end int) string {
var r = []rune(source)
length := len(r)
if start < 0 || end > length || start > end {
retur... |
package main
import (
"io"
)
type ByteCounter int
func (b *ByteCounter) Write(bytes []byte) (int, error) {
*b += ByteCounter(len(bytes)) // 转换类型
return len(bytes), nil
}
type Writer interface {
Write([]byte) (int, error)
}
type Reader interface {
Read([]byte) (int, error)
}
type Closer interface {
Close() er... |
// Tomato static website generator
// Copyright Quentin Ribac, 2018
// Free software license can be found in the LICENSE file.
package main
import (
"fmt"
"os"
)
// FileExists returns whether a given name exists and is a regular file.
func FileExists(name string) bool {
if fi, err := os.Stat(name); err == nil && ... |
package main
// Leetcode 5891. (medium)
func missingRolls(rolls []int, mean int, n int) (res []int) {
sum := 0
for _, num := range rolls {
sum += num
}
sum = (len(rolls)+n)*mean - sum
if sum < n || sum > 6*n {
return
}
redundancy := sum % n
val := sum / n
i := 0
for i < redundancy {
res = append(res, ... |
package mssql
import "time"
type DBAttachment struct {
AttachmentId int32 `gorm:"column:AttachmentId;primaryKey"`
FileName string `gorm:"column:FileName"`
FileStoreId int32 `gorm:"column:FileStoreId"`
DocumentId int32 `gorm:"column:DocumentId"`
Fi... |
// Copyright 2018 The gVisor 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 agree... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.