text stringlengths 11 4.05M |
|---|
/*
Tencent is pleased to support the open source community by making Basic Service Configuration Platform available.
Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except
in compliance with the License. You may obtain... |
package sqlite
import (
"database/sql"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/elitah/utils/logs"
"github.com/mattn/go-sqlite3"
)
const (
FlagStatus = iota // 当前计划状态
PlanAutoBackup
FlagMax
)
type options struct {
flag_groups [FlagMax]uint32
backup_path string
... |
package main
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/koalacxr/nodescan"
)
const ConstNodeScanLogo = `
$$\ $$\ $$\ $$$$$$\
$$$\ $$ | $$ | $$ __$$\ ... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//312. Burst Balloons
//Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked t... |
package main
import (
"math/rand"
"testing"
"time"
)
var tests = []struct {
Name string
Program Memory
Sequence []Intcode
Expected Intcode
}{
{
Name: "part1 first example",
Program: Memory{3, 15, 3, 16, 1002, 16, 10, 16, 1, 16, 15, 15, 4, 15, 99, 0, 0},
Sequence: []Intcode{4, 3, 2, 1, 0},
Ex... |
package helper
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strconv"
"gopx.io/gopx-common/log"
errorCtrl "gopx.io/gopx-vcs-api/pkg/controller/error"
"gopx.io/gopx-vcs-api/pkg/controller/helper"
)
func setBasicHeaders(headers http.Header) {
headers.Set("Server", "GoPx.io")
headers.Set("Access-Control-... |
package models
import (
"fmt"
"github.com/f03lipe/ygut/conf"
)
func Setup() {
fmt.Printf("%+v", conf.C)
}
|
package auth
import (
"backend/structs"
"errors"
"github.com/dgrijalva/jwt-go"
"strconv"
"time"
)
type Claims struct {
Email string `json:"em"`
jwt.StandardClaims
}
// TODO: handle errors more appropriately
func VerifyAndParseToken(token string) (Claims, error) {
claims := Claims{}
parser := jwt.Parser{Vali... |
package messenger
// GenericTemplateReply represents a generic template response
type GenericTemplateReply struct {
Recipient Participant `json:"recipient"`
Message struct {
Attachment struct {
Type string `json:"type"`
Payload struct {
TemplateType string `json:"template_type"`
... |
package kissrpc
import (
"bytes"
"encoding/gob"
"fmt"
"log"
"net/http"
"reflect"
)
type Client struct {
serverUrl string
}
func SingleCall(address string, name string, args ...interface{}) ([]interface{}, error) {
client, err := NewClient(address)
if err != nil {
return []interface{}{}, err
}
return cli... |
// Copyright 2019 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 handler
import (
"context"
"path/filepath"
"testing"
"time"
"github.com/golang/protobuf/ptypes"
jinmuidpb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/user/v1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)
// UserProfileTestSuite 用户档案测试
type UserProfileTestS... |
// Copyright 2023 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 cells
import (
"image"
"image/color"
"github.com/jessemillar/gautomata/tools"
)
func Rule30(m image.RGBA, w int, h int, palette []color.RGBA) {
background := palette[0]
foreground := palette[1]
tools.RandTopLine(m, w, foreground)
// Loop through the canvas
for y := 1; y < h; y++ {
for x := 0; x <... |
package fourchan
import (
"fmt"
)
const (
BoardsURL = "a.4cdn.org"
ImagesURL = "i.4cdn.org"
ThumbsURL = "t.4cdn.org"
)
type Post struct {
Thread *Thread
Data PostData
}
type PostData struct {
PostNumber int `json:"no"`
Resto int `json:"resto"`
Sticky int `json... |
package ports
import (
domain "github.com/awesome-demo-app/todolist-api/core/domain"
)
type ToDoRepository interface {
GetAll() ([]domain.ToDo, error)
Create(domain.ToDo) domain.ToDo
Delete(uint)
}
type ToDoService interface {
GetAll() ([]domain.ToDo, error)
Create(string) domain.ToDo
Delete(uint)
}
|
package main
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"net"
"os"
"strings"
"text/template"
"github.com/containernetworking/plugins/plugins/ipam/host-local/backend/disk"
"github.com/coreos/go-iptables/iptables"
"github.com/sirupsen/logrus"
)
// dnsNameLock embeds the CNI disk lock so we can hang methods ... |
package main
import (
"encoding/json"
"log"
"math/rand"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
//Book Struct (Model)
type Book struct {
ID string `json:"id"`
Isbn string `json:"isbn"`
Title string `json:"title"`
Author *Author `json:"author"`
Year int `json:"year"`
}
//Author Str... |
package handlers
import (
"blockchain"
"blockchain/block"
"data"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"node"
"strconv"
"github.com/gorilla/mux"
)
var Bc = blockchain.InitBlockchain()
var Miner node.Node
var PeerList data.PeerList
// FOR SERVER
func HandleGetBlockchain(w http.ResponseWriter, ... |
package home
import (
"github.com/alehano/gobootstrap/sys/tpl"
)
func init() {
tpl.RegisterMulti("views/home/tpl/", map[string]string{
"home.index": "index.tpl",
})
}
|
package main
import (
"fmt"
)
type primeGenerator struct {
ch chan int
done chan struct{}
}
func (p *primeGenerator) Close() {
close(p.done)
}
func (p *primeGenerator) Next() int {
return <-p.ch
}
func newPrimeGenerator() *primeGenerator {
ch := make(chan int)
done := make(chan struct{})
go func() {
de... |
package structure
// Tag ...
type Tag struct {
ID int64
Name []byte
Slug string
}
|
package hostsfile_test
import (
"net/netip"
"strings"
"testing"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/hostsfile"
"github.com/AdguardTeam/golibs/netutil"
"github.com/AdguardTeam/golibs/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// va... |
package scheduler
import (
"types"
"github.com/golang/glog"
)
var (
allocatedResource map[string]types.Resource
contributedResource map[string]types.Resource
clustersShare map[string]float64
)
func init() {
allocatedResource = make(map[string]types.Resource)
contributedResource = make(map[string]type... |
package golibs
import (
"net"
"os"
)
//检查文件是否存在
func CheckFileIsExist(filename string) bool {
var exist = true
if _, err := os.Stat(filename); os.IsNotExist(err) {
exist = false
}
return exist
}
//获得本机一张网卡的地址
func GetHostIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
}
for _... |
// 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... |
package handler
import (
"fmt"
"log"
"net/http"
"github.com/labstack/echo/v4"
"github.com/vanWezel/to-do/internal/model"
)
func (h *Handler) CommentDelete(c echo.Context) error {
id := fmt.Sprintf("%v", c.Param("id"))
if id == "" {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Errorf("id is missing")... |
package main
import "fmt"
func main() {
// short declaration operator
name := "Ansar"
fmt.Println("Hello ", name)
name = "Something else"
fmt.Println("Hello ", name)
// using var to declare variable
var x bool // initializes to its 0 value
fmt.Println(x)
// String can also use back ticks to preserve multi... |
package web_service
import (
"2021/yunsongcailu/yunsong_server/web/web_dao"
"2021/yunsongcailu/yunsong_server/web/web_model"
)
type MenuServer interface {
// 获取所有菜单
FindMenuAll() (menus []web_model.MenuModel,err error)
// 获取所有激活菜单
FindMenu() (menus []web_model.MenuModel,err error)
// 修改菜单
EditMenu(menu web_mo... |
// Sample program to show how unexported fields from an exported
// struct type can't be accessed directly.
package main
import (
"fmt"
"github.com/lovexiaoe/golangpros/types/exportUnexport/exportUnexport2/entities"
)
// main is the entry point for the application.
func main() {
// Create a value of type Admin fr... |
package main
import (
"gopkg.in/Shopify/sarama.v1"
)
type Msg struct {
*sarama.ConsumerMessage
}
func CreateMsg(cMessage *sarama.ConsumerMessage) *Msg {
msg := new(Msg)
msg.ConsumerMessage = cMessage
return msg
}
|
package functions
// Abs is a function which returns the absolute value of all the
// elements in the slice.
func (ss SliceType) Abs() SliceType {
result := make(SliceType, len(ss))
for i, val := range ss {
if val < 0 {
result[i] = -val
} else {
result[i] = val
}
}
return result
}
|
package usecase
import (
"context"
"go.uber.org/zap"
"github.com/silverspase/todo/internal/modules/todo"
"github.com/silverspase/todo/internal/modules/todo/model"
)
type itemUseCase struct {
repo todo.Repository
logger *zap.Logger
}
func NewItemUseCase(logger *zap.Logger, repo todo.Repository) todo.UseCase... |
package accounts
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
)
const statusHealthyJSON = `
{
"status": "up"
}
`
const errorHealthyJSON = `
{
"status": "down"
}
`
func healthReqAliveHandler() MockHandler {
return func(req *http.Request) (*http.Resp... |
package libvirt
// Metadata contains libvirt metadata (e.g. for uninstalling the cluster).
type Metadata struct {
URI string `json:"uri"`
}
|
package negotiate
import (
"encoding/xml"
"net/http"
)
// Payload defines it's layout in xml and json
type Payload struct {
XMLName xml.Name `xml:"payload" json:"-"`
Status string `xml:"status" json:"status"`
}
// Handler gets a negotiator using the request,
// then renders a Payload
func Handler(w http.Respo... |
package main
import (
"flag"
"os"
"github.com/moorara/flax/cmd/config"
"github.com/moorara/flax/cmd/server"
"github.com/moorara/flax/internal/service"
"github.com/moorara/flax/internal/spec"
"github.com/moorara/flax/version"
"github.com/moorara/konfig"
"github.com/moorara/log"
)
const (
specErr = 10
)
fun... |
package main
import (
"encoding/json"
"io/ioutil"
"fmt"
"os"
)
type Etls struct {
Etls []struct {
ID string `json:"id"`
Filename string `json:"filename"`
Incomingfilepath string `json:"incomingfilepath"`
Intermediatefilepath string `json:"intermediatefilepath"`
Destinationpath string `json:"destination... |
/* For license and copyright information please see LEGAL file in repository */
package approuter
// GetStreamsID : Due MaxConcurrentStreams, peer can get knowledge about all active StreamID on other party.
func GetStreamsID() {}
|
package check
import (
"fmt"
"github.com/MintegralTech/juno/datastruct"
"github.com/MintegralTech/juno/debug"
"github.com/MintegralTech/juno/document"
"github.com/MintegralTech/juno/helpers"
"github.com/MintegralTech/juno/index"
"github.com/MintegralTech/juno/marshal"
"github.com/MintegralTech/juno/operation"
... |
// Copyright 2019, Oath Inc.
// Licensed under the terms of the Apache License 2.0. Please see LICENSE file in project root for terms.
package sshcert
import (
"io/ioutil"
"reflect"
"testing"
"github.com/yahoo/crypki"
"github.com/yahoo/crypki/proto"
"golang.org/x/crypto/ssh"
)
func TestDecodeRequest(t *testin... |
package messages
import "time"
type AuthRequest struct {
RId int64 `json:"r_id"`
UserId int64 `json:"user_id"`
Token string `json:token`
Ip string `json:"ip"`
Port string `json:"port"`
Device string `json:"device"`
}
func NewAuthRequest(userId int64, token, ip, port, device string) *AuthRequest {
... |
// Copyright (c) 2016, M Bogus.
// This source file is part of the AMQP-RPC open source project
// Licensed under Apache License v2.0
// See LICENSE file for license information
package amqprpc
import (
"errors"
"fmt"
"os"
"runtime"
"time"
"context"
"github.com/streadway/amqp"
)
var (
// ReconnectCount max ... |
package main
import (
"flag"
"fmt"
"os"
)
const Usage = `
createChain --address ADDRESS "create block Chain"
addBlock --data DATA "add a block to block chain"
printChain "print all blocks"
getBalance --address ADDRESS "get balance"
`
type CLI struct {
//bc *BlockChian
... |
package http
import "net/http"
type PersonHandler interface {
GetById(http.ResponseWriter, *http.Request)
Create(http.ResponseWriter, *http.Request)
GetAll(http.ResponseWriter, *http.Request)
}
|
package main
import (
"time"
"github.com/jinzhu/gorm"
)
type Task struct {
Id int `gorm"id"`
Text string `gorm:"text"`
Done bool `gorm:"done"`
Location string `gorm:"location"`
CreatedAt time.Time `gorm:"created_at"`
}
func NewRepository(db *gorm.DB) *Repository {
return &... |
package main
import (
"appengine"
"appengine/mail"
"fmt"
"github.com/aws/aws-sdk-go/service/ec2"
"net/http"
)
func init() {
http.HandleFunc("/instances", handleInstances)
http.HandleFunc("/cron/instances", handleCronInstances)
}
func getInstanceStates(r *http.Request) map[string]int {
svc := ec2.New(GetAwsCo... |
package users
import (
"github.com/google/uuid"
"2019_2_IBAT/pkg/app/notifs/notifsproto"
"2019_2_IBAT/pkg/app/recommends/recomsproto"
"2019_2_IBAT/pkg/app/users"
. "2019_2_IBAT/pkg/pkg/models"
)
type UserService struct {
Storage users.Repository
RecomService recomsproto.ServiceClient
NotifService notifs... |
// Copyright 2016 The G3N 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 logger
import (
"os"
)
// Ansi terminal color codes
const (
csi = "\x1B["
black = "30m"
red = "31m"
green = "32m"... |
package body
import (
"encoding/base64"
"fmt"
"image"
"io/ioutil"
"net/url"
"os"
"strconv"
"time"
"github.com/funxdata/baidu/core"
"github.com/sirupsen/logrus"
)
const (
urlBodyTracking = "/rest/2.0/image-classify/v1/body_tracking"
)
type BaiduBody struct {
*core.Core
}
type Location struct {
Left in... |
package http
import (
"hade/app/http/module/demo"
"hade/framework/gin"
)
func Routes(r *gin.Engine) {
r.Static("/dist/", "./dist/")
demo.Register(r)
}
|
package ctyutil
import (
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/gocty"
)
func Convert(v interface{}) (cty.Value, error) {
var err error
if vv, ok := v.(map[string]interface{}); ok {
ret := make(map[string]cty.Value)
for k, v := range vv {
ret[k], err = Convert(v)
if err != nil {... |
package intercom
import (
"io/ioutil"
"testing"
)
func TestAdminAPIList(t *testing.T) {
http := TestAdminHTTPClient{fixtureFilename: "fixtures/admins.json", expectedURI: "/admins", t: t}
api := AdminAPI{httpClient: &http}
adminList, _ := api.list()
if adminList.Admins[0].ID != "1" {
t.Errorf("ID was %s, expec... |
package main
import "math"
func isValidBST(root *TreeNode) bool {
if root == nil {
return true
}
return dfs_left(root.Left, root.Val) && dfs_right(root.Right, root.Val) && isValidBST(root.Left) && isValidBST(root.Right)
}
func dfs_left(root *TreeNode, root_val int) bool {
if root == nil {
return true
}
if... |
package operatorlister
import (
"fmt"
"sync"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
corev1 "k8s.io/client-go/listers/core/v1"
)
type UnionSecretLister struct {
secretListers map[string]corev1.SecretLister
secretL... |
// slice.
package main
import "fmt"
func main() {
i := 0
lc := func(ss []string) {
fmt.Printf("%d len:%d cap:%d %+q\n", i, len(ss), cap(ss), ss)
i++
}
ss := []string{"hello", "world"}
lc(ss)
lc(ss[0:])
lc(ss[:0])
}
|
package installconfig
import (
survey "github.com/AlecAivazis/survey/v2"
"github.com/pkg/errors"
"github.com/openshift/installer/pkg/asset"
"github.com/openshift/installer/pkg/types"
"github.com/openshift/installer/pkg/validate"
)
type clusterName struct {
ClusterName string
}
var _ asset.Asset = (*clusterNam... |
package web
import (
"bytes"
"container/list"
"encoding/json"
"fmt"
q "github.com/streadway/amqp"
"html/template"
"log"
"net/http"
"regexp"
"strings"
"time"
)
const (
addrTemp = `amqp://{{.Username}}:{{.Password}}@{{.Host}}:{{.Port}}/{{.VirtualHost}}`
)
func FailOnError(err error, msg string) {
if err !... |
package webauthnutil
import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestGetEffectiveDomain(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
in string
expect string
}{
{"https://www.example.com/some/path", "example.com"},
{"... |
package blevedb
import (
"fmt"
"time"
"github.com/blevesearch/bleve/v2"
"github.com/blevesearch/bleve/v2/analysis/analyzer/keyword"
"github.com/blevesearch/bleve/v2/analysis/analyzer/simple"
log "github.com/sirupsen/logrus"
)
const (
batchSize = 1000
)
type eventType int
const (
upsertType eventType = iota... |
package services
import r "github.com/davelaursen/idealogue-go/Godeps/_workspace/src/github.com/dancannon/gorethink"
// TagSvc represents a service that provides read/write access to tag data.
type TagSvc interface {
GetAll() ([]string, *Error)
Save(tag string) *Error
Delete(tag string) *Error
}
type tag struct {... |
package chunk_test
import (
"bytes"
"io"
"testing"
"github.com/tombell/go-serato/serato/chunk"
)
func TestNewHeader(t *testing.T) {
data := generateBytes(t, "7672736E0000003C")
buf := bytes.NewBuffer(data)
hdr, err := chunk.NewHeader(buf)
if err != nil {
t.Fatal("expected NewHeader err to be nil")
}
ex... |
//+build amd64,!noasm
package assembler
func Sclean(X []float32)
|
//Package geom вычисляет расстояние между двумя точками.
package geom
import (
"math"
)
// Distance вычисляет расстояние между точками с координатами x1, y1 и x2, y2.
func Distance(x1, y1, x2, y2 float64) float64 {
return math.Sqrt(math.Pow(x2 - x1, 2) + math.Pow(y2 - y1, 2))
}
|
package main
import (
"encoding/json"
"errors"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"strings"
"time"
"os"
"github.com/gorilla/mux"
)
var templates *template.Template
type woeidResponse []struct {
Title string `json:"title"`
LocationType string `json:"location_type"`
Woeid i... |
package webwx
import (
"fmt"
"github.com/cihub/seelog"
)
/*
* global log object
*/
var log = &mLogger{nil, seelog.Off}
/*
* Custom Logger
*
* 1. use "fmt.Sprintln" underline
* 2. use a min-max dispatcher
* 3. can adjust loglevel
*/
type mLogger struct {
innerLogger seelog.LoggerInterface
logLevel seel... |
package gorpc
import (
"bytes"
"fmt"
"log"
"sync"
"testing"
)
func Benchmark_EchoInt_1_Worker(b *testing.B) {
benchEchoInt(b, 1, false)
}
func Benchmark_EchoInt_10_Workers(b *testing.B) {
benchEchoInt(b, 10, false)
}
func Benchmark_EchoInt_100_Workers(b *testing.B) {
benchEchoInt(b, 100, false)
}
func Benc... |
package conf
import (
"fmt"
"github.com/gin-gonic/gin"
"os"
)
const (
APPNAME = "开发框架测试"
JWTTOKEN = "123123"
REDIS_NETWORK = "tcp"
REDIS_ADDRESS = "redis:6379"
REDIS_PASS = "123456"
REDIS_MAXIDLE = 10
REDIS_MAXACTIVE = 10
RED... |
package main
func TakeCircle(x int, y int, step int) bool {
/* Аль нэг шонгийн цагираг дууссан бол
хожил/хожигдолыг тооцоход хялбархан */
if x == 0 || y == 0 {
return ((x + y) % 2 == step % 2)
} else { /* эсрэг тохиолдолд рекурсивээр цагираг авах үйлдлийг давтана */
if step % 2 == 0 {
// A тоглог... |
package pattern
import (
"math"
"github.com/calbim/ray-tracer/src/color"
"github.com/calbim/ray-tracer/src/matrix"
"github.com/calbim/ray-tracer/src/tuple"
)
//Pattern interface
type Pattern interface {
GetTransform() *matrix.Matrix
SetTransform(m *matrix.Matrix)
PatternAt(point tuple.Tuple) *color.Color
}
... |
package cmd
import (
"fmt"
"net/http"
"strconv"
"strings"
"github.com/golang/protobuf/ptypes"
"github.com/textileio/go-textile/pb"
)
func InviteCreate(threadID string, address string, wait int) error {
if address != "" {
contact, _, _ := getContact(address)
if contact != nil {
return createInvite(threa... |
package treemap
import (
"github.com/hnnyzyf/go-stl/container/pair"
"github.com/hnnyzyf/go-stl/container/rbtree"
"github.com/hnnyzyf/go-stl/container/value"
)
//TreeMap is a RBTree
type TreeMap struct {
r *rbtree.RBTree
}
func New() *TreeMap {
return &TreeMap{
r: rbtree.New(),
}
}
//Insert will add a key in... |
package error
import "fmt"
// ResourceNotFoundError indicates missing resource
type ResourceNotFoundError struct {
Resource string
}
func (rnf *ResourceNotFoundError) Error() string {
return fmt.Sprintf("%s not found", rnf.Resource)
}
|
package ipam
import (
"fmt"
"net"
"strings"
"k8s.io/klog"
)
// Manager - handles the addresses for each namespace/vip
var Manager []ipManager
// ipManager defines the mapping to a namespace and address pool
type ipManager struct {
namespace string
cidr string
ipRange string
addressMana... |
package transdsl
type Optional struct {
Spec Specification
IfFrag Fragment
ElseFrag Fragment
ifFlag bool
elseFlag bool
}
func (this *Optional) Exec(transInfo *TransInfo) error {
if this.Spec.Ok(transInfo) {
this.ifFlag = true
return this.IfFrag.Exec(transInfo)
}
if this.ElseFrag != nil {
this.el... |
package texthash_test
import (
"testing"
"github.com/ibraimgm/jolly-crane/texthash"
)
func TestInsertAndFind(t *testing.T) {
repo := texthash.NewInMemRepository()
toInsert := []texthash.TextHash{
{Token: "foo", Hash: "001", CreatedAt: "xxxx"},
{Token: "bar", Hash: "002", CreatedAt: "xxxx"},
{Token: "baz",... |
package ircbot
import (
"bufio"
"fmt"
"net"
"strings"
)
// BotFunc is a function that can be plugged in to handle commands.
type BotFunc func([]string) string
// Bot is a struct representing a bot.
type Bot struct {
// Nick used by the bot.
Nick string
// ChannelNames is slice of names of channels that bot
... |
package main
import (
"fmt"
)
func swap(m1, m2 *int) {
var temp int
temp = *m2
*m2 = *m1
*m1 = temp
}
func main() {
m1 := 2
ptr := &m1 //Get Value Address
val := *ptr //Get Value
fmt.Println(val)
//Declar multiple init
m2, m3 := 2, 3
fmt.Println(m2, m3)
swap(&m2, &m3)
fmt.Println(m2, m3)
}
|
package dto
type CreateSubtitleRequestDto struct {
VideoId string `json:"videoId"`
Parts []SubtitlePartDto `json:"items"`
}
type SubtitlePartDto struct {
SubtitleId int `json:"subtitleId"`
Start int `json:"start"`
End int `json:"end"`
Text string `json:"text"`
}
|
// Package mongo interfaces with MongoDb for us.
package mongo
import (
"log"
root "go.jlucktay.dev/golang-workbench/go_rest_api/pkg"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
// UserService holds a MongoDb collection.
type UserService struct {
collection *mgo.Collection
}
// NewUserService initialises and re... |
func twoSum(numbers []int, target int) []int {
left, right := 0, len(numbers) - 1
for left < right{
v := numbers[left] + numbers[right]
if v == target{
return []int{left+1, right+1}
} else if v < target{
left += 1
} else{
right -= 1
}
... |
package main
import (
"context"
"log"
"os"
"strconv"
pb "github.com/robinjmurphy/go-grpc-example/server/proto"
"google.golang.org/grpc"
)
const (
address = "localhost:50051"
)
func argsToInput(args []string) ([]int32, error) {
var ret []int32
for _, a := range args {
i, err := strconv.Atoi(a)
if err !=... |
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
fmt.Println("starting up...")
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {})
server := http.Server{
Addr: ":80",
Handler: mux,
}
// Listen for SIGTERM and shutdown the server.
done := make(c... |
// 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... |
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
)
func main() {
var j bytes.Buffer
io.Copy(&j, os.Stdin)
var dst bytes.Buffer
if e := json.Indent(&dst, j.Bytes(), "", " "); e != nil {
fmt.Fprintf(os.Stderr, "pretty: %v\n", e)
}
fmt.Println(dst.String())
}
|
// Copyright (c) 2017-2020 Zededa, Inc.
// SPDX-License-Identifier: Apache-2.0
// Look for address changes
package devicenetwork
import (
"github.com/lf-edge/eve/pkg/pillar/base"
"github.com/vishvananda/netlink"
)
// Returns a channel for link updates
// Caller then does this in select loop:
//
// case change := ... |
package eventbus
import (
"sync"
"testing"
"github.com/stretchr/testify/suite"
)
func TestEventBus(t *testing.T) {
eb, err := Setup(1)
if err != nil {
panic(err.Error())
}
defer eb.Release()
suite.Run(t, &eventBusSuite{})
}
type eventBusSuite struct {
suite.Suite
}
func (s *eventBusSuite) SetupTest() {
... |
package expr
import (
"go/ast"
"github.com/sky0621/go-testcode-autogen/inspect/result"
"fmt"
)
type ArrayTypeInspector struct{}
func (i *ArrayTypeInspector) IsTarget(node ast.Node) bool {
switch node.(type) {
case *ast.ArrayType:
return true
}
return false
}
func (i *ArrayTypeInspector) Inspect(node ast.... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-08-16 14:07
# @File : shell_sort.go
# @Description :
# @Attention :
*/
package sort
func ShellSort(data []int) {
stride := len(data)
for stride != 1 {
stride >>= 1
// 分为了stride个组,则需要对着stride进行排序
for i := 0; i < stride; i++ {
// 进行插入排序
for j ... |
package models
import (
"github.com/jinzhu/gorm"
)
type TweetRegistered struct {
gorm.Model
MessageId int
FetchSuccess bool
FetchStatus string
}
|
// Source : https://oj.leetcode.com/problems/search-in-rotated-sorted-array/
// Author : Austin Vern Songer
// Date : 2016-04-28
/**********************************************************************************
*
* Suppose a sorted array is rotated at some pivot unknown to you beforehand.
*
* (i.e., 0 1 2 4 5 6 7 ... |
package slack
import (
"encoding/json"
"fmt"
"strconv"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// Slack consts
const (
TypeMessage = "message"
UserInviteLimit = 30
)
const (
postMessageURL = "https://slack.com/api/chat.postMessage"
conversationsCreateURL = "https://slack.com/ap... |
package decorator
import "net/http"
//TransportFunc 는 RoundTripper 인터페이스를 구현한다.
type TransportFunc func(r *http.Request) (*http.Response, error)
//RoundTrip 은 원래 함수를 호출한다.
func (tf TransportFunc) RoundTrip(r *http.Request) (*http.Response, error) {
return tf(r)
}
//Decorator 는 미들웨어 내부의 함수(middleware inner function... |
package log
import "fmt"
type LogLevel int
const (
LogLevelDebug LogLevel = iota
LogLevelInfo
LogLevelWarn
LogLevelError
LogLevelFatal
)
var defaultLoggerLevel = LogLevelDebug
type (
Logger interface {
Debug(args ...interface{})
Info(args ...interface{})
Warn(args ...interface{})
Error(args ...interf... |
../main_test.go |
package boil
import (
"database/sql"
"testing"
)
func TestGetSetDB(t *testing.T) {
t.Parallel()
SetDB(&sql.DB{})
if GetDB() == nil {
t.Errorf("Expected GetDB to return a database handle, got nil")
}
}
|
package models
import (
"encoding/json"
"github.com/astaxie/beego/orm"
)
type Log struct {
Model
Id int `orm:"column(id);" json:"id"`
Agent string `orm:"column(agent);size(64);" json:"agent"`
Type int `orm:"column(type);" json:"type"`
Message string `orm:"column(message);size(4096);" json:"mes... |
package entity
import "time"
// Bookmark export
type Bookmark struct {
Novel map[string]*BookmarkEntry `json:"novel" bson:"novel"`
Comic map[string]*BookmarkEntry `json:"comic" bson:"comic"`
}
// BookmarkEntry export
type BookmarkEntry struct {
Type string `json:"type" bson:"type"`
ID ... |
package main
import "testing"
func TestNewArea(t *testing.T) {
area := NewArea(NewPoint(2, 4), NewPoint(4, 8))
if area == nil {
t.Fail()
}
}
func TestAreaWidth(t *testing.T) {
area := NewArea(NewPoint(2, 4), NewPoint(4, 8))
if area.Width() != 2 {
t.Fail()
}
}
func TestAreaHeight(t *testing.T) {
... |
package main
import "fmt"
type data struct {
foo string
bar string
}
func main() {
d := data {
foo: "dataFoo",
bar: "dataBar",
}
fmt.Println(d)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.