text stringlengths 11 4.05M |
|---|
package firewall
import "github.com/stretchr/testify/mock"
type MockExecFactory struct {
mock.Mock
}
func (_m *MockExecFactory) NewCmd(name string, args ...string) Execer {
ret := _m.Called(name, args)
var r0 Execer
if rf, ok := ret.Get(0).(func(string, ...string) Execer); ok {
r0 = rf(name, args...)
} else ... |
package pie
import (
"fmt"
"golang.org/x/exp/constraints"
)
// String transforms a value into a string. Nil values will be treated as empty
// strings.
//
// If the element type implements fmt.Stringer it will be used. Otherwise it
// will fallback to the result of:
//
// fmt.Sprintf("%v")
//
func String[T constr... |
package main
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
func main() {
l1 := ListNode{1, &ListNode{2, &ListNode{5, nil}}}
l2 := ListNode{1, &ListNode{3, &ListNode{4, nil}}}
re := mergeTwoLists(&l1, &l2)
for re != nil {
fmt.Println(re.Val)
re = re.Next
}
}
//迭代法
func mergeTwoLists(l1 *Lis... |
// Copyright 2022 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 tools
import (
_ "github.com/golangci/golangci-lint/cmd/golangci-lint"
_ "github.com/mercari/wrench"
_ "github.com/rakyll/statik"
_ "go.mercari.io/yo"
)
|
package service
import (
"culture/cloud/base/internal/support/api"
"github.com/goava/di"
)
// Error 服务错误码
type Error struct {
Code api.Code
Error error
}
// Container 服务容器
var Container *di.Container
// Resolve 获取服务实例
func Resolve(ptr di.Pointer, options ...di.ResolveOption) error {
return Container.Resolve(p... |
package ionic
import (
"testing"
"github.com/franela/goblin"
"github.com/ion-channel/tools-golang/spdx"
. "github.com/onsi/gomega"
)
func TestSPDX(t *testing.T) {
g := goblin.Goblin(t)
RegisterFailHandler(func(m string, _ ...int) { g.Fail(m) })
g.Describe("SPDX v2.1", func() {
g.It("should return the top-l... |
package my_ldap
import (
"log"
"fmt"
"github.com/go-ldap/ldap/v3"
// "github.com/google/uuid"
"strings"
// "strconv"
"encoding/json"
"net/http"
)
type PkdClinics struct {
PkdAdmId string `json:"pkdAdmId"`
JknName string `json:"jknName"`
PkdName string `json:"pkdName"`
ClinicIds [... |
package main
import "fmt"
// 定义一个结构体,然后给这个结构体一个方法计算面积并返回
type Circle struct {
Radius float64
}
func (c *Circle) area() float64 { // c在这里是一个接收main传来参数的元素,自己的元素自己用~~~~
// 这里是值传递,所以这里运算用的c 是r的考呗,如果变成指针,就变成地址传递,这个时候r是会再area中被修改的
return (*c).Radius * (*c).Radius * 3.14
// 为了提高效率,通常方法和结构体指针类型绑定!!!!
// 实际操作的时候会有部分省... |
package xlog
// A sink which dispatches to zero or more other sinks.
type MultiSink struct {
sinks []Sink
}
func (ms *MultiSink) Add(sink Sink) {
for _, s := range ms.sinks {
if s == sink {
return
}
}
ms.sinks = append(ms.sinks, sink)
}
func (ms *MultiSink) Remove(sink Sink) {
var newSinks []Sink
for _... |
package main
import (
"github.com/gin-gonic/gin"
)
// DefaultStatus is an Enum storing default JSON errors based on the status.
type DefaultStatus int
const (
// Status503 is for service unavailable.
Status503 DefaultStatus = 1 + iota
// Status400 is for a client error.
Status400
// Status401 is for an unautho... |
package data
// 登录信息
type LoginInfo struct {
Account string //用户名或手机号
Password string //密码
}
// 注册信息
type RegisterInfo struct {
Account string //用户名
Mobile string //手机号
Password string //密码
}
|
package main
import (
"context"
"fmt"
"sort"
"strconv"
"github.com/Nerzal/gocloak/v13"
"github.com/pkg/errors"
"github.com/signaux-faibles/keycloakUpdater/v2/logger"
)
func UpdateKeycloak(
kc *KeycloakContext,
clientId string,
realm *gocloak.RealmRepresentation,
clients []*gocloak.Client,
users Users,
c... |
package main
import (
"fmt"
"io"
"log"
"net/http"
"reflect"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
"github.com/karen-irc/popuko/epic"
"github.com/karen-irc/popuko/input"
"github.com/karen-irc/popuko/queue"
"github.com/karen-irc/popuko/setting"
)
// AppServer is just an this applicatio... |
package otpauth
import (
"fmt"
"strconv"
"testing"
"unsafe"
)
func TestZeroPadding(t *testing.T) {
run := func(t *testing.T, fixt Fixture, d int) {
for _, tc := range fixt.TestCases {
tc := tc
val, _ := strconv.ParseInt(tc.Value, 10, 64)
t.Run(fmt.Sprintf("%d to %s", val, tc.Result), func(t *testing.T... |
package sort
// MergeSort 归并排序
// 时间复杂度O(nLogN)
// 与 SelectionSort 一样,不受输入数据影响
func MergeSort(arr []int) []int {
if len(arr) < 2 {
return arr
}
// 分为两组
var mid = len(arr) / 2
left := arr[:mid]
right := arr[mid:]
l := MergeSort(left)
r := MergeSort(right)
return Merge(l, r... |
package API_Responses
type Response struct {
StatusCode int `json:"statusCode"`
Message string `json:"message"`
Data map[string]interface{} `json:"data"`
}
func DefineResponse(statusCode int, message string, data map[string]interface{}) Response {
return Response{
Sta... |
// upload_plain
package cmd
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path"
"strings"
"github.com/spf13/cobra"
"gopkg.in/rana/ora.v4"
)
var (
script string
)
// uploadCmd represents the upload_plain command
var uploadPlainCmd = &cobra.Command{
Use: "upload_plain",
Short: "Upload file to Oracle DB and ex... |
package controllers
import (
"fmt"
"net/http"
)
// PrivacyController is the Privacy screen
func PrivacyController() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Privacy Controller")
}
}
|
package mr
import (
"encoding/json"
"fmt"
"hash/fnv"
"io/ioutil"
"log"
"net/rpc"
"os"
"sort"
"sync/atomic"
"time"
)
//
// Map functions return a slice of KeyValue.
//
type KeyValue struct {
Key string
Value string
}
//
// use ihash(key) % NReduce to choose the reduce
// task number for each KeyValue em... |
package proxy
import (
"encoding/json"
"fmt"
)
type JSONRpcResp struct {
Id *json.RawMessage `json:"id"`
Method string `json:"method"`
Params *json.RawMessage `json:"params"`
}
type StratumReq struct {
JSONRpcResp
Worker string `json:"worker"`
}
func (s *StratumReq) String() string {
m, err :=... |
package main
/*
+----------+
| |-+
| internal | |-+ Common util packages
| | | |
+----------+ | |
+-----------+ |
+-----------+
+----------+
| |-+
| main | |-+ Application domain packages
| | | |
+----------+ | |
+-----------+ |
+--------... |
// Copyright (c) 2022 Zededa, Inc.
// SPDX-License-Identifier: Apache-2.0
package main
import (
"context"
"fmt"
"io/ioutil"
"os"
"strconv"
"github.com/lf-edge/eve/libs/depgraph"
)
var lastFileID int
func newFileID() int {
lastFileID++
return lastFileID
}
// file represents a named, regular file.
type file... |
// Copyright (c) 2020 Doc.ai 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/LIC... |
package main
import (
"golangStudy/project/note_money_struct/util"
)
func main() {
a := util.NewAccount()
a.MainMenu()
}
|
package fakes
import "github.com/cloudfoundry-incubator/notifications/models"
type FakeUnsubscribesRepo struct {
Unsubscribes map[string]models.Unsubscribe
}
func NewFakeUnsubscribesRepo() *FakeUnsubscribesRepo {
return &FakeUnsubscribesRepo{
Unsubscribes: map[string]models.Unsubscribe{},
}
}
fu... |
package leetcode
func letters(n byte) string {
switch n {
case '2':
return "abc"
case '3':
return "def"
case '4':
return "ghi"
case '5':
return "jkl"
case '6':
return "mno"
case '7':
return "pqrs"
case '8':
return "tuv"
case '9':
return "wxyz"
default:
return ""
}
}
func letterCombination... |
package client
import (
"encoding/xml"
"fmt"
"net/http"
"net/url"
"github.com/BenjaminLam1202/test-go-config-cameras/hkvision/types/streaming"
)
/**
* @author : Donald Trieu
* @created : 9/24/21, Friday
**/
/*
It is used to get a device streaming status.
*/
func (cli *Client) StreamingStatus() (streaming.St... |
package configlib
import (
"fmt"
"os"
"os/user"
"path/filepath"
"strings"
)
var (
CurrentUser *user.User
MetaConfigPath string
DefaultConfigPath string
DefaultConfigType = "local"
)
// error codes
const (
Unknown = -1
ErrCodeCouldNotFindCurrentUser = iota + 1
)
// Storage... |
package controllers
import (
"alta-store/lib/database"
"alta-store/middlewares"
"alta-store/models"
"net/http"
"strconv"
"github.com/labstack/echo"
)
func GetAllUsers(c echo.Context) error {
users, err := database.GetUsers()
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
r... |
// Copyright 2015-2018 trivago N.V.
//
// 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 main
import (
"fmt"
"io"
"log"
"github.com/minio/minio-go/v6"
uuid "github.com/nu7hatch/gouuid"
)
//TODO: create an interface and have several implementations e.g. test mocks
func writeImageToObjectStorage(scaledReader io.Reader, length int, imageType string, targetScale string, config imageScalerConfi... |
// Package utils - utils funcs
package utils
|
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"strings"
)
func ProcessINPUT(rd io.Reader) string {
var found = false
fmt.Print("Enter data: ")
in := bufio.NewReader(rd)
line, err := in.ReadString('\n')
if err != nil {
log.Fatal(err)
}
line = strings.Trim(line, "\n")
line = strings.ToLower(lin... |
package main
import (
"time"
"fmt"
)
func main() {
//year := time.Now().Year()
//year_str := strconv.Itoa(year)
//year, month, _ := time.Now().Date()
//thisMonth := time.Date(year, month, 1, 0, 0, 0, 0, time.Local)
//start := thisMonth.AddDate(0, 1, 0).Format("2006-01-02")
//fmt.Println(year,month,thisMonth,... |
package util
import (
"fmt"
"os"
"time"
"github.com/shanghuiyang/rpi-devices/util/geo"
)
const (
timeFormat = "2006-01-02T15:04:05"
)
// GPSLogger ...
type GPSLogger struct {
f *os.File
chPoints chan *geo.Point
}
// NewGPSLogger ...
func NewGPSLogger() *GPSLogger {
fname := time.Now().Format(timeFor... |
package models
import (
"github.com/jinzhu/gorm"
"time"
)
type Blood struct {
ID int `json:"id" gorm:"primaryKey;autoIncrement" db:"id"`
DeviceId string `json:"device_id" db:"device_id"`
Pulse int `json:"pulse" db:"pulse" gorm:"comment:脈搏"`
Diastolic float32 `json:"diastolic" db:"diastolic" gorm:"comment:舒張壓"`
... |
package core
import (
"time"
"github.com/golang/protobuf/ptypes"
pb "github.com/popstk/olddriver/backend"
)
// Item -
type Item struct {
Title string `json:"title"`
URL string `json:"url"`
Tag string `json:"tag"`
Time time.Time `json:"time"`
Baidu []string `json:"baidu" bson:"baidu,omitem... |
package dirlist
import (
"net/http"
"io"
"log"
"html/template"
"os"
"net/url"
"sort"
)
type DirList struct {
FS http.FileSystem
Tpl *template.Template
IndexFiles []string
}
func (d *DirList) ServeHTTP(w http.ResponseWriter, r *http.Request) {
urlPath := r.URL.Path;
method := r.Method
if method != "GET"... |
package main
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/abiosoft/ishell"
"github.com/abiosoft/readline"
"github.com/gliderlabs/ssh"
"github.com/gtfierro/xboswave/ingester/types"
"github.com/olekukonko/tablewriter"
logrus "github.com/sirupsen/logrus"
)
func parseFilterFromArgs(args []string) (*Re... |
package antminer
import (
"context"
"fmt"
"sync"
"github.com/ka2n/masminer/machine/asic/base"
"golang.org/x/crypto/ssh"
"golang.org/x/sync/errgroup"
)
// GetStats returns MinerStats
func (c *Client) GetStats() (stats MinerStats, err error) {
return c.GetStatsContext(context.Background())
}
// GetStatsContex... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2021/12/2 9:18 上午
# @File : lt_279_完全平方数.go
# @Description :
# @Attention :
*/
package v2
import "math"
/*
给定正整数 n,
找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
给你一个整数 n ,返回和为 n 的完全平方数的 最少数量 。
完全平方数 是一个整数,
其值等于另一个整数的平方;换句话说,其值等于一个整数自乘的积。例如,1、4、9 ... |
package testutil
import (
ds2 "github.com/ipfs/go-ipfs/thirdparty/datastore2"
"gx/ipfs/QmVSase1JP7cq9QkPT46oNwdp9pT6kBkG3oqS14y3QcZjG/go-datastore"
syncds "gx/ipfs/QmVSase1JP7cq9QkPT46oNwdp9pT6kBkG3oqS14y3QcZjG/go-datastore/sync"
)
func ThreadSafeCloserMapDatastore() ds2.ThreadSafeDatastoreCloser {
return ds2.Clo... |
package commands
import (
"drdgvhbh/discordbot/internal/cli/anime/mal"
"drdgvhbh/discordbot/internal/cli/anime/mal/api"
messageMal "drdgvhbh/discordbot/internal/discord/message/anime/mal"
"log"
"github.com/bwmarrin/discordgo"
realCli "github.com/urfave/cli"
)
type CommandCallback = func(output *discordgo.Messa... |
package main
import (
"sync"
"sync/atomic"
)
type ClientSessions struct {
sync.Mutex
list []*ClientSession
counter uint64
}
func (c *ClientSessions) Add(s *ClientSession) {
c.Lock()
defer c.Unlock()
c.list = append(c.list, s)
}
func (c *ClientSessions) Remove(s *ClientSession) {
c.Lock()
defe... |
// DO NOT EDIT. This file was generated by "github.com/frk/gosql".
package testdata
import (
"github.com/frk/gosql"
)
func (q *InsertBasicSliceQuery) Exec(c gosql.Conn) error {
var queryString = `INSERT INTO "test_user" AS u (
"id"
, "email"
, "full_name"
, "created_at"
) VALUES ` // `
params := make([]... |
package gorestreact
//go:generate swag init --parseInternal --parseDependency -g ./cmd/main.go
|
package nlp
import (
"io/ioutil"
"log"
"regexp"
"strings"
)
var stopwordRegex *regexp.Regexp
var stopwordMap map[string]bool
func init() {
stopwords := []string{"the", "is", "at",
"which", "on", "and", "a", "an",
"am", "hello", "hey",
"be", "as", "by",
"for", "from",
"he", "her", "hers",
"him", "his... |
package actions
import (
"errors"
"github.com/barrydev/api-3h-shop/src/common/connect"
"github.com/barrydev/api-3h-shop/src/factories"
"github.com/barrydev/api-3h-shop/src/model"
"strings"
)
func UpdateOrderItem(orderItemId int64, body *model.BodyOrderItem) (*model.OrderItem, error) {
queryString := ""
var arg... |
// 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 main
import (
"encoding/csv"
"flag"
//"fmt"
svg "github.com/ajstarks/svgo"
"io"
"log"
"math/rand"
"os"
"strconv"
)
func rn(n int) int { return rand.Intn(n) }
func main() {
canvas := svg.New(os.Stdout)
var file string
flag.StringVar(&file, "input", "input.csv", "input file")
flag.Parse()
csvfil... |
package main
import (
"os"
"path/filepath"
"testing"
)
func TestValidateDocsDirStructure(t *testing.T) {
testCases := []struct {
name string
dirStructure []string
expectedErr bool
}{
{
name: "Valid directory structure",
dirStructure: []string{"mutation-examples", "validation", "int... |
package accgenerator_test
import(
"testing"
"dbcreator"
//"fmt"
)
func Test_FiDBCreator_Process(t *testing.T){
m := accgenerator.NewAccDBCreator()
//m.Process()
m.Delete()
}
|
package phpCommons
import (
"testing"
"fmt"
)
func Test_array_values(t *testing.T) {
b := []string{"aaaaa", "vvvv", "cc", "aaaa", "aaaaa", "aaaaa", "cc", "vvvv"}
fmt.Printf("%#v\n", array_values(b))
// c := []string{"aaaa", "aaaaa", "cc", "vvvv"}
}
|
package sndtag
import (
"fmt"
"io"
)
// Types of tags that are supported.
// TODO: support id3
const (
RIFF = iota
ID3v1
ID3v2
)
// New creates a new map with metadata read from an io.Reader.
// If the type is not one of the supported types then an error is returned.
func New(r io.Reader) (map[string]string, er... |
package csvConvert
import (
"testing"
)
// TestOpenCSV check to open file and content
func TestOpenCSV(t *testing.T) {
// test.csv used for this test
file := "./test.csv"
data, err := OpenCSV(file)
if err != nil {
t.Fatal(err)
}
// check content data
if len(data) < 1 {
t.Fatal("no data inside test.csv")... |
package common
func IsStringSliceHas(target interface{}, slice []string) (bool, int) {
for index, key := range slice {
if key == target {
return true, index
}
}
return false, -1
}
|
package django
import (
"fmt"
"github.com/spf13/viper"
"io/ioutil"
"os"
"path/filepath"
"projcli/utils"
"time"
)
var workDir string
func init() {
wd, err := os.Getwd()
if err != nil {
utils.HandleErr(err)
}
workDir = wd
}
func setup(configName string) {
extension := filepath.Ext(configName)
_configNa... |
package text
import (
"fmt"
)
func Box(message string) (output string) {
messageLength := len(message)
output += fmt.Sprintf("╭")
for i := 0; i < l+2; i++ {
output += fmt.Sprintf("─")
}
output += fmt.Sprintf("╮\n")
output += fmt.Sprintf("│ %v │\n", message)
output += fmt.Sprintf("╰")
for i := 0; i < l+2; i... |
package environment
import (
"fmt"
"github.com/getynge/environment/filter"
"gopkg.in/alessio/shellescape.v1"
"os"
"strings"
)
type Environment struct {
m map[string]string
}
// New creates an empty Environment
func New() (e Environment) {
e = Environment{
m: make(map[string]string),
}
return e
}
// Shel... |
package service
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/rbonnat/blockchain-in-go/blockchain"
)
const (
testTime = "2020-07-04T14:05:53-04:00"
)
func mockNowFunc(t *testing.T) func() time.Time {
now, err := time.Parse(time.RF... |
// Copyright © 2016 Nathan Sharpe <nathanjsharpe@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 by a... |
package main
import "testing"
func TestHashSet(t *testing.T) {
hs := Constructor()
hs.Add(1)
hs.Add(2)
if hs.Contains(1) != true {
t.Fatal()
}
if hs.Contains(3) != false {
t.Fatal()
}
hs.Add(2)
if hs.Contains(2) != true {
t.Fatal()
}
hs.Remove(2)
if hs.Contains(2) != false {
t.Fatal()
}
}
|
package problem0084
import "testing"
func TestSolve(t *testing.T) {
t.Log(largestRectangleArea([]int{2, 1, 2}))
t.Log(largestRectangleArea([]int{1, 1}))
}
|
package ruffe
import "net/http"
var emptyHandler = HandlerFunc(func(Context) error { return nil })
type HandlerFunc func(Context) error
func (h HandlerFunc) Handle(ctx Context) error {
return h(ctx)
}
type Handler interface {
Handle(h Context) error
}
type HTTPHandlerFunc func(http.ResponseWriter, *http.Request... |
// gRPC server
package main
import (
"bytes"
"flag"
"fmt"
"hash"
"io"
"log"
"net"
"os"
"runtime/pprof"
"sync"
"time"
"google.golang.org/grpc"
"github.com/glycerine/blake2b" // vendor https://github.com/dchest/blake2b"
"google.golang.org/grpc/credentials"
"github.com/glycerine/bchan"
"github.com/gly... |
package main
import (
controller "go-todo/backend/controller"
"net/http"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
func main() {
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"*"},
AllowMethods: []string{... |
// 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 ... |
/*
Package go-sudoku implements a simple library for solving sudoku puzzles.
*/
package main
import (
"flag"
"fmt"
"net/http"
"github.com/jamesandersen/gosudoku/sudokuparser"
"github.com/nytimes/gziphandler"
)
func main() {
var filename string
var mode string
flag.StringVar(&mode, "mode", "serve", "whether t... |
package leetcode
func dominantIndex(nums []int) int {
tm, m, mi := 0, 0, 0
for i, v := range nums {
if m < v {
tm = m * 2
m = v
mi = i
} else if tm < v*2 {
tm = v * 2
}
}
if m >= tm {
return mi
} else {
return -1
}
}
|
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2021/6/13 8:27 上午
# @File : lt_z型打印二叉树.go
# @Description :
# @Attention :
*/
package v2
func zigzagLevelOrder(root *TreeNode) [][]int {
if nil == root {
return nil
}
r := make([][]int, 0)
toogle := true
queue := make([]*TreeNode, 0)
queue = append(queue, r... |
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use ... |
package util
import (
"reflect"
)
// ParseArray for return empty arrays in responses
func ParseArray(a interface{}) (res interface{}) {
if a == nil || reflect.ValueOf(a).IsNil() {
res = []string{}
} else {
res = a
}
return
}
|
package main
import (
"fmt"
"log"
"net"
"sync"
"time"
"golang.org/x/net/context"
"google.golang.org/grpc"
pb "github.com/gautamrege/gochat/api"
)
type chatServer struct {
}
func (s *chatServer) Chat(ctx context.Context, req *pb.ChatRequest) (res *pb.ChatResponse, err error) {
fmt.Printf("\n%s\n> ", fmt.Sp... |
package reqValidator
import (
"errors"
"fmt"
"reflect"
"strings"
)
type structure interface {
Map() map[string]interface{}
}
// Validate the types and return a bool
func Validate(structure structure, itemsMap map[string]interface{}) bool {
fmt.Println("DEPRECATED: Validate(structure structure, itemsMap map[str... |
package vfs
import (
"strconv"
"strings"
"github.com/ncw/rclone/fs"
"github.com/ncw/rclone/fs/rc"
"github.com/pkg/errors"
)
// Add remote control for the VFS
func (vfs *VFS) addRC() {
rc.Add(rc.Call{
Path: "vfs/forget",
Fn: func(in rc.Params) (out rc.Params, err error) {
root, err := vfs.Root()
if er... |
package domain
import (
"fmt"
"regexp"
"strings"
"github.com/thoas/go-funk"
)
type MJLog struct {
ID string
MyPosition string
Body string
}
func (m MJLog) GetRiichCount() int {
r := regexp.MustCompile(`<REACH.*?/>`)
matches := r.FindAllString(m.Body, -1)
return len(funk.Filter(matches, func... |
package mqtt
import (
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"os"
"regexp"
"time"
aws "github.com/aws/aws-sdk-go/aws/credentials"
paho "github.com/eclipse/paho.mqtt.golang"
"github.com/uhppoted/uhppote-core/uhppote"
"github.com/uhppoted/uhppoted-lib/uhppoted"
"github.com/uhppoted/uhppoted-mqtt/acl"... |
package main
import (
"fmt"
)
func apply(afungsi func(int) int, val int) int {
return afungsi(val)
}
func increment(x int) int { return x + 1 }
func decrement(x int) int { return x - 1 }
func main() {
fmt.Println(apply(increment, 2))
fmt.Println(apply(decrement, 2))
}
|
package keeper_test
import (
"encoding/hex"
"fmt"
"math/big"
"testing"
"github.com/stretchr/testify/suite"
abci "github.com/tendermint/tendermint/abci/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/irisnet/irismod/modules/random/keeper"
"github.com/irisnet/irismod/modules/random/types"
)
fun... |
package main
import (
"fmt"
"log"
"os"
"strings"
"time"
"qpid.apache.org/amqp"
"qpid.apache.org/electron"
)
func main() {
s := newSender()
count := 0
// endless for loop which keeps sending data
for {
m := amqp.NewMessage()
msg := fmt.Sprintf("hello from %q on %q! %d", os.Getenv("TYPE_OF_AMQP_USER"),... |
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
mygraph := IngestInput()
if mygraph.Balance() {
fmt.Println("Balanced")
} else {
fmt.Println("Not balanced")
}
}
// IngestInput ingest input
func IngestInput() Graph {
mygraph := Graph{
nodes: []*Node{},
enemy: map[Node]... |
package jsonapi
import (
. "github.com/smartystreets/goconvey/convey"
"testing"
)
func TestRoutes(t *testing.T) {
Convey("Given a new resquest builder", t, func() {
b := NewRequestBuilder()
Convey("Resource collection routes are defined without ids", func() {
r, err := b.SetResourcePath("posts").Build()
... |
package main
import (
"testing"
"time"
)
func TestMatchmakingSimplePairing(t *testing.T) {
t.Skip()
mmc := makeMatchmakingController()
client0 := client{clientNum:0}
connec0 := MakePlayerConnection(client0,nil)
client1 := client{clientNum:1}
connec1 := MakePlayerConnection(client1,nil)
client2 := client{... |
package main
import (
"fmt"
)
func copyArray() {
slice := []int{1, 2, 3, 4, 3, 5}
copia := make([]int, len(slice), cap(slice)*2) //incrementar la capacidad x 2
//copy(destino, fuente)
copy(copia, slice)
fmt.Println(slice)
fmt.Println(copia)
}
|
//line waccparser.y:2
package parser
import __yyfmt__ "fmt"
//line waccparser.y:2
import (
. "ast"
)
//line waccparser.y:10
type parserSymType struct{
yys int
str string
stringconst Str
number int
pos int
integer Integer
ident Ident
character Character
boolean Boolean
fieldacce... |
package lib
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
)
type layerDetails string
func (l layerDetails) ContentDigest() string {
return string(l)
}
type tagDetails struct {
name string
tag string
rawManifest interface{}
contentDigest string
layers []Layer... |
package main
import (
"fmt"
"strings"
)
func main() {
str := "abdc"
greatest := ""
pairs := [][]int{{1, 4}, {3, 4}}
for _, x := range pairs {
s1 := x[0] - 1
s2 := x[1] - 1
tempArr := strings.Split(str, "")
tempStr := tempArr[s1]
tempArr[s1] = tempArr[s2]
tempArr[s2] = tempStr
combinStr := st... |
package calc
import (
"fmt"
)
func init() {
fmt.Println("calc init...")
}
// 加法运算
func Add(a, b int) (result int) {
result = a + b
return
}
// 减法运算
func Minus(a, b int) (result int) {
result = a - b
return
}
// 乘法运算
func multiply(a, b int) (result int) {
result = a * b
return
}
|
package dushengchen
func isPalindrome(x int) bool {
if x < 0 {
return false
}
if reverse(x) == x {
return true
}
return false
}
//
////from q7
//func reverse(x int) int {
// if x == 0 {
// return 0
// } else if x < 0 {
// return -reverse(-x)
// }
// res := 0
// ... |
package main;
import (
"fmt";
"time";
)
type Customer struct {
name string
old string
sdt string
address string
}
type geometry interface {
area() int
}
type reg struct{
w int
h int
}
func (r reg) area() int{
return r.w * r.h
}
func s(g geometry){
fmt.Println(g.area());
}
func goroutin2(){
fmt.Println("he... |
package api
import (
utils "github.com/kevinbarbary/go-lms/utils"
"encoding/json"
"log"
)
type EnrolStatus string // @todo - rune
func (s EnrolStatus) Enabled() bool {
// Status A = Active, G = Group, P = Pending, D = Disabled, etc.
return s == "A" || s == "G"
}
type UserEnrol struct {
EnrollID int ... |
package main
import (
"crypto/rand"
"fmt"
"io/ioutil"
"net"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/rn/iso9660wrap"
log "github.com/sirupsen/logrus"
)
func buildQemuCmdline(config QemuConfig) (QemuConfig, []string) {
// Iterate through the flags and build arguments
var qemuArgs []... |
package main
import (
"fmt"
"os"
"os/exec"
)
func warn(directory string) error {
if directory == "" {
return fmt.Errorf("warn directory should not be nil")
}
find := exec.Command(
"/usr/bin/find",
directory,
"-name",
"*.swift",
"-print0",
)
match := exec.Command(
"xargs",
"-0",
"egrep",
"-... |
package template
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/AlecAivazis/survey"
"gopkg.in/yaml.v2"
)
const (
// The configuration file relative to the template root directory
configName = "config.yaml"
// The directory holding the template file and directories relative to
// the template ... |
package config
import (
"os"
"path"
)
var Server = map[string]string{
"host": "localhost",
"port": "8080",
}
var Client = map[string]string{
"cache_dir": path.Join(os.Getenv("HOME"), ".fx/"),
"remote_images_url": "https://raw.githubusercontent.com/metrue/fx/master/images.zip",
}
|
// Implement [VLQ] encoding/decoding
// https://en.wikipedia.org/wiki/Variable-length_quantity
package variablelengthquantity
const testVersion = 1
func EncodeVarint(input uint32) (byteArr []byte) {
r := input % 128
byteArr = []byte{byte(r)}
input = input / 128
for input > 0 {
r := input % 128
input = input ... |
package runner
import (
"context"
"fmt"
"os"
"strings"
"time"
"github.com/Shopify/sarama"
"github.com/pkg/errors"
)
// Topic is a definition for a kafka topic
type Topic struct {
Name string
Partitions int
Replicas int
Compact bool
Retention time.Duration
Segment time.Duration
Create ... |
package main
func reverse(number int) {
println(number)
}
func main() {
number := []int{1, 2, 3, 4, 5}
for _, i := range number {
defer reverse(i)
}
}
|
// Copyright 2021 Akamai Technologies, 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.