text stringlengths 11 4.05M |
|---|
package circuitbreaker
import (
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
func Test_isApplicableRule_valid(t *testing.T) {
type args struct {
rule Rule
}
tests := []struct {
name string
args args
want error
}{
{
name: "rtRule_isApplicable",
args: args{
rule: NewSlowRtRule(... |
package helpers
import "strings"
func SanitizeString(s string) string {
return strings.Trim(s, " ")
}
|
package main
import (
"time"
)
type Emplyee struct {
Id int
Name string
Address string
Dob time.Time
Position string
Salary int
ManagerId int
}
var dilbert Emplyee
func test() {
dilbert.Salary -= 5000
posPtr := &dilbert.Position
*posPtr = "fdfdsfdfd" + *posPtr
// 点号同样可以用在结构体指针上
... |
package common
import (
"bytes"
"fmt"
"strings"
"text/template"
"github.com/werf/werf/pkg/build"
"github.com/werf/werf/pkg/build/stage"
"github.com/werf/werf/pkg/config"
"github.com/werf/werf/pkg/container_runtime"
"github.com/werf/werf/pkg/giterminism_manager"
"github.com/werf/werf/pkg/slug"
"github.com/w... |
package goidc
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)
func TestJWKEndpoint(t *testing.T) {
je := NewJWKEndpoint()
je.AddFromText("my_key_id", `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCzFyUUfVGyMCbG7YIwgo4XdqEj
hhgIZJ4Kr7VKwIc7F+x0DoBniO6uhU6HVxMPibxSDIGQIHoxP9HJP... |
package controller
import (
"Seaman/model"
"Seaman/service"
"Seaman/utils"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/mvc"
"github.com/kataras/iris/v12/sessions"
"strconv"
)
/**
* 组织机构控制器结构体:用来实现处理组织机构模块的接口的请求,并返回给客户端
*/
type OrgController struct {
//上下文对象
Ctx iris.Context
OrgService serv... |
package main
import(
"doubtnut/config"
"doubtnut/pdfGenerator"
"time"
"os"
)
func main() {
config.ReadConfig()
m := make(map[string]string)
for _,questions := range config.SimilarQuestions{
for _,input := range questions{
m[input.Question] = input.VideoLink
}
}
// Creating a channel
received := mak... |
/*
* Copyright © 2018-2022 Software AG, Darmstadt, Germany and/or its licensors
*
* SPDX-License-Identifier: Apache-2.0
*
* 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://... |
package resources
import (
"core/sessions"
"fmt"
"net/http"
"qutils/basehandlers"
"qutils/coder"
)
func PersonageResourcesHandler(resp http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
session, ok := sessions.GetSessionByRequest(req)
if !ok {
basehandlers.UnauthorizedRequest(resp, req)
retu... |
package database
import (
"bufio"
"encoding/json"
"fmt"
"os"
"time"
)
// State is the main business logic of the ledger
type State struct {
Balances map[Account]uint
txMempool []Tx
dbFile *os.File
latestBlockHash Hash
}
// NewStateFromDisk starts the ledger from the genesis
func NewStateFromDisk(... |
package main
import (
"flag"
"io"
"os"
"path/filepath"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
terminal "golang.org/x/term"
"k8s.io/klog"
klogv2 "k8s.io/klog/v2"
)
var (
rootOpts struct {
dir string
logLevel string
}
)
func main() {
// This attempts to con... |
package characters
import (
"Golang-API-Game/pkg/repository"
"database/sql"
"log"
)
type Character struct {
CharacterID string
Name string
Power int
}
// CharacterID条件にレコードを取得する
func SelectByCharacterName(characterID string) (*Character, error) {
row := repository.DB.QueryRow("SELECT * FROM chara... |
package psql
import (
"database/sql"
"time"
)
func str2DateRFC3339(str sql.NullString) (date time.Time, err error) {
if str.Valid {
date, err = time.Parse(time.RFC3339, str.String)
}
return date, err
}
|
package db
import (
"database/sql"
"sync"
"testing"
"time"
"github.com/golang/protobuf/ptypes"
"github.com/textileio/go-textile/pb"
"github.com/textileio/go-textile/repo"
"github.com/textileio/go-textile/util"
)
var cafeRequestStore repo.CafeRequestStore
func init() {
setupCafeRequestDB()
}
func setupCafe... |
package webrtc
import (
"github.com/edaniels/golog"
"github.com/pion/logging"
)
// LoggerFactory wraps a golog.Logger for use with pion's webrtc logging system.
type LoggerFactory struct {
Logger golog.Logger
}
type logger struct {
logger golog.Logger
}
func (l logger) Trace(msg string) {
l.logger.Debug(msg)
}... |
package main
import (
"fmt"
"io"
"log"
"strings"
"github.com/PuerkitoBio/goquery"
)
func decodeRowsHtmlMizrahiCC(r io.Reader) (rows []Row, err error) {
log.Print("mizrahi-cc")
s, err := readUtf16(r)
if err != nil {
return nil, err
}
doc, err := goquery.NewDocumentFromReader(strings.NewReader(s))
if er... |
// +build !ci
package command
import (
"testing"
"gopkg.in/go-playground/assert.v1"
)
func TestRun(t *testing.T) {
err := Run([]string{})
assert.Equal(t, err, nil)
err = Run([]string{"../examples/template.lua"})
assert.Equal(t, err, nil)
err = Run([]string{"notexistant.lua"})
assert.NotEqual(t, err, nil)
... |
package receivers
import (
"encoding/json"
"errors"
"fmt"
"time"
cclog "github.com/ClusterCockpit/cc-metric-collector/pkg/ccLogger"
lp "github.com/ClusterCockpit/cc-metric-collector/pkg/ccMetric"
influx "github.com/influxdata/line-protocol"
nats "github.com/nats-io/nats.go"
)
type NatsReceiverConfig struct {... |
package kissrpc
import (
"encoding/gob"
"fmt"
"log"
"net/http"
"reflect"
"time"
)
const DEBUG = false
var registeredTypes = map[string]struct{}{
"string": {},
"float": {},
"int": {},
"int32": {},
"int64": {},
"error": {},
}
func init() {
RegisterType([]interface{}{})
}
type call struct {
Name ... |
package account
import (
"fmt"
"net/http"
"qutils/basehandlers"
"qutils/coder"
)
//Error handlers
//Use ONLY as enclosed handlers becuse this ones don't close Body
//Respond with JSON with error #1 'This account doesn't exists or password incorrect'
func loginIncorrect(resp http.ResponseWriter, request *http.Req... |
package user
import (
"github.com/jpurdie/authapi"
"net/http"
"github.com/labstack/echo"
)
// Custom errors
var (
ErrIncorrectPassword = echo.NewHTTPError(http.StatusBadRequest, "incorrect old password")
ErrInsecurePassword = echo.NewHTTPError(http.StatusBadRequest, "insecure password")
)
func (u User) Fet... |
package profiler
/*
Time tracker will take two parameters time now and function name in which it is called
*/
import (
"fmt"
"time"
)
func TimeTrack(start time.Time, name string) {
elapsed := time.Since(start)
fmt.Printf("%s took %s\n", name, elapsed)
} |
package util
import (
"io/ioutil"
"fmt"
"encoding/pem"
)
func ReadFromPem(path string) []byte {
bytes, err := ioutil.ReadFile(path)
if err != nil {
fmt.Println(err)
}
//解码私钥
block, _ := pem.Decode(bytes)
if block == nil {
fmt.Println("block is nil")
}
return block.Bytes
}
|
package db
import (
"github.com/op/go-logging"
)
var logger = logging.MustGetLogger("hammer.db")
var logFormat = logging.MustStringFormatter("[db] %{level} %{color}%{message}%{color:reset}")
func init() {
logging.SetFormatter(logFormat)
logging.SetLevel(logging.WARNING, "hammer.db")
}
|
// Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license"... |
package tomltypes
import (
"time"
"github.com/BurntSushi/toml"
)
type Duration time.Duration
var _ toml.TextUnmarshaler = new(Duration)
func (d *Duration) UnmarshalText(text []byte) error {
ud, err := time.ParseDuration(string(text))
if err != nil {
return err
}
*d = Duration(ud)
return nil
}
|
package gbnet
import _ "gober/gbinterface"
type Message struct {
Id uint32 //消息id
DataLen uint32//消息长度
Data []byte//消息内容
}
func NewMsg(msgid uint32,data []byte) *Message {
msg := &Message{
Id: msgid,
DataLen: uint32(len(data)),
Data: data,
}
return msg
}
func (m *Message) GetMsgId() uint32{
re... |
package jsonv
import (
"bytes"
"fmt"
"reflect"
)
/*
Holds infomation to map a JSON object property to a struct field.
Note: Whether or not the value any non-slice, non-ptr field is required
*/
type StructPropInfo struct {
schema SchemaType
def reflect.Value
f field
required bool
}
func Prop(n s... |
// txtkbd2kla project
// Copyright 2018 Philippe Quesnel
// Licensed under the Academic Free License version 3.0
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"github.com/phques/txt2autokey/kbdRdr"
)
type Key struct {
Primary int `json:"primary"`
Shift int `json:"shift"`
AltGr ... |
package terminfo
import (
"encoding/hex"
"os"
"os/user"
"path/filepath"
"strings"
)
type compatEntry struct {
partial string
*Terminfo
}
var (
cache = make(map[string]*Terminfo, 64)
builtins = make(map[string]*Terminfo, 64) // TODO more coverage
compatTable = make([]compatEntry, 0, 64)
)
// KeyCo... |
/*
Copyright 2022 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... |
/*
Copyright 2020 The Qmgo 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 "fmt"
func labelFunc() {
out:
for i := 0; i < 10; i++ {
for j := 0; j < 10; j++ {
if i+j == 20 {
break out
}
}
}
}
func labelFunc2() {
if 1 == 1 {
fmt.Println(1)
goto End
}
fmt.Println(2)
End:
fmt.Println(3)
}
|
package topic
import (
"github.com/htdvisser/pkg/store"
"github.com/htdvisser/pkg/store/stringmap"
)
// Store for topics
type Store struct {
store interface {
store.Interface
Match(filter string) (values []interface{})
}
}
// NewStore returns a new topic store
func NewStore() *Store {
store := stringmap.New... |
package main
import (
"archive/tar"
"bufio"
"bytes"
"compress/gzip"
"embed"
"errors"
"io"
"log"
"os"
"path/filepath"
"github.com/blevesearch/bleve"
)
//go:embed assets
var fs embed.FS
type Location struct {
Name string
Body string
TZ string
Lang string
}
func main() {
wd, err := os.Getwd()
if er... |
package handler
import (
"context"
"errors"
"path/filepath"
"testing"
proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/user/v1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)
type FindUsernameBySecureEmailTestSuite struct {
suite.Suite
JinmuIDService *JinmuIDServic... |
package pathfileops
import (
"fmt"
"os"
"testing"
)
func TestFileHelper_JoinPathsAdjustSeparators_01(t *testing.T) {
fh := FileHelper{}
path1 := fh.AdjustPathSlash("../../../../pathfilego/003_filehelper/common")
file1 := "xt_dirmgr_01_test.go"
expected1 := fh.AdjustPathSlash("../../../../pathfilego/003_... |
package main
import (
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
"hospital/Model"
_ "hospital/Model"
"math/rand"
"net/http"
)
func main() {
r := gin.Default()
//连接数据库
db, err := gorm.Open("mysql", "root:root1234@(127.0.0.1:13306)/db1?charset=utf8mb4&parseTime=True&loc=Local")
if err!= nil{
panic(... |
// Copyright 2021 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 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) 2018 John Dewey
// 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, dist... |
package generator
import (
"board"
"container/heap"
"image"
"rand"
)
type fieldHeapElement struct {
Coords image.Point
Weight int
}
type fieldHeap []fieldHeapElement
func (self *fieldHeap) Push(x interface{}) {
*self = append(*self, x.(fieldHeapElement))
}
func (self *fieldHeap) Pop() interface{} {
last :=... |
package main
import (
"bufio"
"fmt"
"os"
. "strings"
)
func main() {
stdin := bufio.NewReader(os.Stdin)
println("Enter string with 'i', 'a', 'n' : ")
s, err := stdin.ReadString('\n')
if err != nil {
fmt.Printf("Error happened: %s, repeating.", err.Error())
main()
} else {
ss := ToLower(TrimSpace(s))
... |
package common
// import (
// "sync"
// "github.com/0xBahamoot/go-bigcompressor"
// )
// var bigCompress bigcompressor.BigCompressor
// var bigCompresslock sync.Mutex
// const (
// maxPrecompressChunkSize int64 = 104857600
// maxDecompressBufferSize int64 = 104857600
// )
// func CompressDatabase(src string, d... |
package redis
import (
"context"
"time"
"github.com/go-redis/redis/v8"
pomeriumconfig "github.com/pomerium/pomerium/config"
"github.com/pomerium/pomerium/internal/log"
"github.com/pomerium/pomerium/internal/telemetry/metrics"
)
type logger struct {
}
func (l logger) Printf(ctx context.Context, format string,... |
package neatly_test
import (
"github.com/stretchr/testify/assert"
"github.com/viant/neatly"
"github.com/viant/toolbox/url"
"testing"
)
func Test_Tag(t *testing.T) {
var tag = neatly.NewTag("", url.NewResource("test"), "[]Test{1 .. 003}", 1)
assert.True(t, tag.IsArray)
assert.Equal(t, "Test", tag.Name)
assert.... |
package slack15
import "fmt"
// Envelope describes destination and sender (as visiable in Slack).
// Defaults are defined by webhook settings in Slack and this structure
// allows for overwritting these.
// More info at https://api.slack.com/incoming-webhooks
type Envelope struct {
// Destination channel in slack, e... |
package strings
import (
"fmt"
"math"
)
func InchesToFeet(inches interface{}) (string, error) {
float, ok := inches.(float64)
if ok {
ft := math.Floor(float/12)
in := math.Mod(float, 12)
return fmt.Sprintf("%d'%d\"", int(ft), int(in)), nil
}
return "", fmt.Errorf("cannot convert %s to a float... |
package test
import (
"encoding/json"
"fmt"
"os"
"sync"
"testing"
"time"
"github.com/zk"
)
const (
perms = 0x1f
totalPack = 1000
totalCCUeachIns = 320
totalInstance = 3
numGroup = 2
)
var (
acl = []zk.ACL{{perms, "world", "anyone"}}
conns = make([]*zk.Conn, totalInstance) //... |
//go:generate statik -src=./static/dist
package main
import (
"github.com/issummary/issummary/cmd"
_ "github.com/issummary/issummary/statik"
)
func main() {
cmd.Execute()
}
|
// Copyright 2014 The Sporting Exchange Limited. All rights reserved.
// Use of this source code is governed by a free license that can be
// found in the LICENSE file.
// +build windows
package config
const (
DefaultFilePath = "config.xml"
DefaultFilterPath = "filter.exe"
)
|
package main
import (
"github.com/rumpl/nomad-invoc/pkg/nomad"
)
func installAction(n nomad.NomadInvocation, name string) error {
return n.Install(name)
}
|
package skip_list
import (
"math/rand"
)
const (
MaxLevel = 10
cap = 1.0 / 2.0
)
type SkipNode struct {
next []*SkipNode
parent *SkipNode
key int
val int
isRoot bool
isNil bool
// level int
}
type SkipList struct {
keyword string
head *SkipNode
tail *SkipNode
level int
num ... |
package main
import "fmt"
func main() {
var cognome string
for {
var ins string = ""
fmt.Println("Inserisci cognome:")
fmt.Scanln(&ins)
if ins == "" {
break
} else {
if ins > cognome {
cognome = ins
}
}
}
fmt.Println("ultimo cognome: ", cognome)
}
|
package main
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
_ "github.com/mattn/go-sqlite3"
_ "test_proj/chatRoom/routers"
"test_proj/chatRoom/controllers"
)
//自动建表
func createTable() {
name := "default" //数据库别名
force := false //不强制建数据库
... |
package domain
import (
"qipai/enum"
"zero"
)
type ReqLogin struct {
Type enum.UserType `form:"type" json:"type" binding:"required"`
Name string `form:"name" json:"name" binding:"required"`
Pass string `form:"pass" json:"pass" binding:"required"`
Session *zero.Session `json:"-"`
}
type ... |
package git
import (
"errors"
"testing"
"time"
)
func TestCreateTag(t *testing.T) {
t.Parallel()
repo := createTestRepo(t)
defer cleanupTestRepo(t, repo)
commitId, _ := seedTestRepo(t, repo)
commit, err := repo.LookupCommit(commitId)
checkFatal(t, err)
tagId := createTestTag(t, repo, commit)
tag, err :... |
package logs
import (
"encoding/json"
"log"
"os"
)
type ConsoleOutput struct {
lg *log.Logger
Level int `json:"level"`
Prefix string `json:"prefix"`
}
func NewConsoleOutput() LoggerOutputInf {
co := &ConsoleOutput{lg: log.New(os.Stdout, "", log.Ldate|log.Ltime), Level: LevelTrace}
return co
}
func (... |
package grant
import (
"fmt"
"net/http"
"time"
"github.com/lyokato/goidc/id_token"
"github.com/lyokato/goidc/scope"
"github.com/lyokato/goidc/bridge"
"github.com/lyokato/goidc/log"
oer "github.com/lyokato/goidc/oauth_error"
"github.com/lyokato/goidc/pkce"
)
const TypeAuthorizationCode = "authorization_cod... |
package gojson
import (
"encoding/json"
"reflect"
)
func (enc *encoder) marshalStruct(v reflect.Value) ([]byte, error) {
var result string
var err error
rawProps := rawProperties{}
var vUnknownProperties *reflect.Value
if rawProps, vUnknownProperties, err = enc.marshalStructFields(v); err != nil {
return nil... |
package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"log"
"os/exec"
"strings"
)
var (
ErrInvalidTag = errors.New("invalid tag")
)
type Version struct {
Major int
Minor int
Patch int
}
func ParseFromGitTag(t string) (*Version, error) {
splitted := strings.Fields(t)
if len(splitted) < 2 {
return nil, ... |
package port
import (
"github.com/mirzaakhena/danarisan/domain/repository"
"github.com/mirzaakhena/danarisan/domain/service"
)
// JawabUndanganOutport ...
type JawabUndanganOutport interface {
repository.FindOnePesertaRepo
repository.FindOneArisanRepo
repository.SavePesertaRepo
repository.SaveArisanRepo
reposi... |
/*
The package services provides the main implementation of the Comment Parsing service. The object of
this service is to go through all source files of a provided package (eg: "fmt") and going through
all the present comments to find any of the provided tokens/words. All such matches of tokens in comments
will be ... |
package main
import (
"fmt"
"os"
"github.com/alzedd/golb/commands"
"github.com/alzedd/golb/settings"
)
const BUILD_COMMAND = "build"
const DEV_WEBSERVER_COMMAND = "develop"
var availableCommands []string = getAvailableCommands()
func main() {
command := os.Args[1]
if isValidCommand(command) {
defer fmt.Pr... |
package config
const (
//CPU使用量 <= 0 为最大使用量
MAX_CPUS = 0
)
|
package models
import (
"github.com/astaxie/beego/orm"
"time"
)
/*
DROP TABLE IF EXISTS `tokensky_account_bank`;
CREATE TABLE `tokensky_account_bank` (
`key_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`bank_user_name` varchar(50) DEFAULT NULL,
`bank_card_no` varchar(50) DEFAULT NULL,
`bank_name` var... |
// Package filepath implements Go's filepath package with explicit
// operating systems (and for some functions and explicit working
// directory). This allows tools built for one OS to operate on paths
// targeting another OS. For example, a Linux build can determine
// whether a path is absolute on Linux or on Wind... |
package helpers
import (
"context"
"text/template"
"github.com/werf/logboek"
)
func SetupIncludeWrapperFuncs(funcMap template.FuncMap) {
helmIncludeFunc := funcMap["include"].(func(name string, data interface{}) (string, error))
setupIncludeWrapperFunc := func(name string) {
funcMap[name] = func(data interfac... |
// Copyright (c) 2020 Cisco and/or its affiliates.
//
// SPDX-License-Identifier: Apache-2.0
//
// 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/LICE... |
package lua
import (
"testing"
assert "gopkg.in/go-playground/assert.v1"
)
func TestSynth(t *testing.T) {
vm := newVM(t)
defer vm.Close()
err := vm.DoString(`
local synth = require('eolian.synth')
-- Multiple inputs
local osc = synth.Oscillator()
osc:set { pitch = hz(100), detune = hz(1) }
-- Sing... |
package main
import (
"github.com/stretchr/testify/assert"
"testing"
)
func assertSubstitution(t *testing.T, expected, input string) {
out, err := substituteForVars(input)
assert.Nil(t, err)
assert.Equal(t, expected, out)
}
func TestSubstitution(t *testing.T) {
variables = map[string][]string{
"a": {"alpha... |
package mredis
import (
"context"
"github.com/go-redis/redis"
"sync/atomic"
)
// Mysql主从组
type CACHEGroup struct {
mCounter uint64
Master []*CACHEConn
sCounter uint64
Slave []*CACHEConn
}
func newCACHEGroup(groupConf *CACHEGroupConf) (cacheGroup *CACHEGroup, err error) {
//redis实例名字必须设置
if len(groupC... |
package waddrmgr
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"testing"
"time"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcwallet/walletdb"
)
// applyMigration is a helper function that allows us to assert the state of the
// top-level bucke... |
// golrn06 - Learning go
// Various tests
//
// 2016-03-01 PV
package main
import "fmt"
func main() {
// Page 39
value := "hello, world"
value = "\u00f8"
v1, v2 := Split(value, len(value)/2)
fmt.Println("value=", value, " v1=", v1, " v2=", v2)
if Join(Split(value, len(value)/2)) != value {
fmt.Println("test ... |
package main
import "fmt"
func main() {
//切片
//数组的长度是固定并且数组长度属于类型的一部分,所以数组有很多的局限性
//切片是一个拥有相同类型元素的可变长度的序列,它是基于数组类型做的一层封装
//它非常灵活,支持自动扩容
//切片是一个引用类型,它的内部结构包含地址、长度和容量
// var a []int //切片声明
// a = []int{2, 3, 4} //赋值
// fmt.Println(a)
//切片拥有自己的长度和容量,使用内置的len()函数求长度,使用cap()函数求切片的容量
//可以基于数组定义切片
b := [5... |
package wallet
import (
"github.com/iotaledger/wasp/tools/wasp-cli/config"
"github.com/iotaledger/wasp/tools/wasp-cli/log"
)
func requestFundsCmd(args []string) {
address := Load().Address()
// automatically waits for confirmation:
log.Check(config.GoshimmerClient().RequestFunds(&address))
log.Printf("Request f... |
package main
import (
"os"
"os/signal"
"syscall"
"time"
_ "net/http/pprof"
"github.com/etf1/kafka-message-scheduler-admin/server/config"
"github.com/etf1/kafka-message-scheduler-admin/server/runner/kafka"
log "github.com/sirupsen/logrus"
metrics "github.com/tevjef/go-runtime-metrics"
)
var (
app ... |
package types
import (
"github.com/julienschmidt/httprouter"
)
type Server struct {
// db *someDatabase
router *httprouter.Router
// email EmailSender
}
func (s *Server) routes() {
// s.router.HandleFunc()
}
|
package stage
import (
"context"
"github.com/werf/werf/pkg/build/import_server"
"github.com/werf/werf/pkg/giterminism_manager"
"github.com/werf/werf/pkg/storage"
)
type Conveyor interface {
GetImportMetadata(ctx context.Context, projectName, id string) (*storage.ImportMetadata, error)
PutImportMetadata(ctx con... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-07-06 10:06
# @File : _46_Permutations.go
# @Description : 排列组合问题
# @Attention :
*/
package main
func Permute(nums []int) [][]int {
result := [][]int{}
permutateHelper(nums, 0, len(nums), func(arr []int) {
result = append(result, arr)
})
return res... |
package commandrunner
import (
"bytes"
"os/exec"
)
//go:generate counterfeiter . Runner
type Runner interface {
Run(outbuf, errbuff *bytes.Buffer) error
Wait() error
Kill() error
}
type runner struct {
scriptPath string
cmdErrChan chan error
cmd *exec.Cmd
}
func NewRunner(script... |
package cmd
import (
"fmt"
"os"
"github.com/grrtrr/clcv2"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
)
func init() {
Root.AddCommand(&cobra.Command{
Use: "creds [group|server [group|server]...]",
Aliases: []string{"credentials"},
Short: "Print login c... |
package main
import (
"fmt"
)
func main() {
x := 10
fmt.Printf("x is %v and type %T \n",x,x)
s := fmt.Sprintf("%d",x)
fmt.Printf("S is %v and type %T \n",s,s)
fmt.Printf("S is %q and type %T \n",s,s)
}
|
package setr
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document05500102 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:setr.055.001.02 Document"`
Message *SwitchOrderConfirmationCancellationInstructionV02 `xml:... |
package hashid
import (
"time"
)
type HashIdParam struct {
NowTime int64
Rand int64
}
func (p *HashIdParam) GetYearMonth() int64 {
tm := time.Unix(0, p.NowTime)
return int64(tm.Year()*100 + int(tm.Month()))
}
|
package mos6502
const (
amABS = iota
amABX
amABY
amIND
amIMM
amIMP
amIZX
amIZY
amREL
amZP0
amZPX
amZPY
)
func ABS() int {
opAddressMode = amABS
lo := uint16(read(PC))
PC++
hi := uint16(read(PC))
PC++
absoluteAddress = hi<<8 | lo
return 0
}
func ABX() int {
opAddressMode = amABX
lo := uint16(r... |
package streams
/*
Copyright 2018 Bruno Moura <brunotm@gmail.com>
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 ... |
package uaa
import (
"context"
"log"
"net/http"
gctx "github.com/gorilla/context"
"golang.org/x/oauth2"
)
func Callback(oauth *oauth2.Config, session Session, httpClient *http.Client) http.Handler {
return gctx.ClearHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// get state string ... |
package db
import (
"database/sql"
"sync"
"time"
"github.com/textileio/go-textile/pb"
"github.com/textileio/go-textile/repo"
"github.com/textileio/go-textile/util"
)
type CafeClientDB struct {
modelStore
}
func NewCafeClientStore(db *sql.DB, lock *sync.Mutex) repo.CafeClientStore {
return &CafeClientDB{mode... |
package disco
import (
"errors"
"fmt"
"log"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/aws/aws-sdk-go/service/ec2"
)
type amazon struct {
c *AmazonConfig
}
type AmazonConfig struct {
Region string
GroupName str... |
package promotions
var _ Interface = &Service{}
type Service struct {
context Context
}
func (s *Service) New(p Promotion) (Promotion, error) {
}
func (s *Service) Load(id string) (Promotion, error) {
}
func (s *Service) LoadAll() ([]Promotion, error) {
}
func (s *Service) LoadMany(id string, count int) ([... |
package main
import (
"fmt"
"time"
)
type Demo struct {
Name string
}
func main() {
arr := []Demo{
{
Name: "aa",
},
{
Name: "bb",
},
{
Name: "cc",
},
{
Name: "dd",
},
}
for _, v := range arr {
v2 := v
go func(d *Demo) {
fmt.Println(d.Name)
}(&v2)
}
time.Sleep(time.Second)... |
package main
import (
"fmt"
"problemGenerator/lib"
)
func main() {
params := lib.ParseParameter()
gen := new(lib.Generator)
gen.Init(*params.Operator, *params.Range)
for i := 0; i < *params.Count; i++ {
fmt.Println(gen.Generate(*params.Operand))
fmt.Println()
}
}
|
// Copyright 2021 Google 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 required by applicable law or agreed to in ... |
//
// Copyright 2020 The AVFS 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 ag... |
package rpc
import (
"fmt"
"testing"
)
func TestServer_StartStop(t *testing.T) {
server := NewServer(nil)
go func() {
// this is the server side
// it should read message from the consumer channel and reply to them.
rpc := <-server.Consumer()
fmt.Printf("consumer got rpc command %#v\n", rpc.Command)
rpc... |
package cluster
type Term struct {
}
|
package main // import "github.com/inclavare-containers/enclaved"
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"github.com/urfave/cli"
pb "github.com/inclavare-containers/enclaved/proto"
"google.golang.org/grpc"
"log"
"net"
"time"
)
const (
AgentRequestTypeEcho = iota
AgentRequestTypeRemoteAttestati... |
package libio_test
import (
"bufio"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/ywardhana/golib/libio"
)
func TestReadLine(t *testing.T) {
stringtest := "1 1"
reader := bufio.NewReader(strings.NewReader(stringtest + "\n"))
res := libio.ReadLine(reader)
assert.Equal(t, stringtest, r... |
package filehandler
import (
"log"
"os"
)
func MakeFileToByte(textfile string) (data []byte, count int) {
file, err := os.Open(textfile)
if err != nil {
log.Fatal(err)
}
finfo, err := file.Stat()
if err != nil {
log.Fatal(err)
}
sizeOfSlice := finfo.Size()
data = make([]byte, sizeOfSlice)
count, err =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.