text stringlengths 11 4.05M |
|---|
package cls
import (
"bytes"
"crypto/md5"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"github.com/pierrec/lz4"
"google.golang.org/protobuf/proto"
)
func lz4Compress(src []byte) ([]byte, error) {
dst := make([]byte, len(src))
ht := make([]int, 64<<10)
n, err := lz4.Co... |
// Copyright 2016 The Go 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 glock
import (
"bufio"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"github.com/golang/dep"
"github.com/golang/dep/gps"
"github.com/golang/dep/... |
package typesutil
import (
"errors"
"go/types"
"strings"
)
var ErrBadType = errors.New("bad type")
type NamedStruct struct {
Named *types.Named
Struct *types.Struct
}
// GetStruct is a helper function that returns a *NamedStruct value that represents
// the struct type of the the given *types.Var. If the stru... |
package main
import (
"fmt"
"os"
"strconv"
"strings"
"time"
"periph.io/x/conn/v3/driver/driverreg"
"periph.io/x/conn/v3/i2c"
"periph.io/x/conn/v3/i2c/i2creg"
_ "periph.io/x/host/v3/bcm283x"
_ "periph.io/x/host/v3/rpi"
)
var temperatureBands = []map[string]int{
{"temp": 50, "speed": 10},
{"temp": 60, "spe... |
package parser
import (
"regexp"
"strconv"
"strings"
)
func MemorableCharacters(body []byte, memorableCharacters string) [3]string {
memSplit := strings.Split(memorableCharacters, "")
bodyStr := string(body)
characters := []string{
regexp.MustCompile(`memInfo1\">Character (\d+)`).FindStringSubmatch(bodyStr)... |
package metrocard
import (
// "fmt"
)
func Lifecycle(value, cost float64) ([]float64) {
balances := make([]float64, (int(value/cost) + 1))
for i := 0; value >= 0; i++ {
balances[i] = value
value -= cost
}
return balances
}
|
/**
*@Author: haoxiongxiao
*@Date: 2019/3/20
*@Description: CREATE GO FILE admin
*/
package admin
import (
"bysj/services"
"bysj/web/middleware"
"github.com/kataras/iris"
"github.com/spf13/cast"
)
type AuthController struct {
Ctx iris.Context
Service *services.AuthServices
Common
}
func NewAuthController... |
package main
import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/mvc"
"log"
)
func newApp() *iris.Application {
app := iris.Default()
mvc.New(app.Party("/")).Handle(&lotteryController{})
return app
}
func main() {
app := newApp()
err := app.Run(iris.Addr(":8081"), iris.WithoutServerError(iri... |
package leetcode
import "testing"
func TestUniqueOccurrences(t *testing.T) {
if uniqueOccurrences([]int{1, 2, 2, 1, 1, 3}) != true {
t.Fatal()
}
if uniqueOccurrences([]int{1, 2}) != false {
t.Fatal()
}
if uniqueOccurrences([]int{-3, 0, 1, -3, 1, 1, 1, -3, 10, 0}) != true {
t.Fatal()
}
}
|
package gothreat
import (
"encoding/json"
)
type AntiVirusData struct {
ResponseCode string `json:"response_code"`
Md5 string `json:"md5"`
Sha1 string `json:"sha1"`
Scans []string `json:"scans"`
Ips []string `json:"ips"`
Domains []string `json:"domains"`
References ... |
package main
import "fmt"
func uniqueMorseRepresentations(words []string) int {
morselist := []string{".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}
morseset := make(map[string]int)
for _, word := rang... |
package jpush
type AdminRequest struct {
AppName string `json:"app_name,string"`
AndroidPackage string `json:"android_package,string"`
GroupName string `json:"group_name,string"`
}
|
package main
import (
"bufio"
"fmt"
"github.com/tidwall/gjson"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
)
func main() {
usernameList, err := readLines("usernames.txt")
if err != nil {
log.Fatalf("readLines: %s", err)
}
file, err := os.Create("available.txt")
if err != nil {
fmt.Println(... |
package logger
import (
"log"
"go.uber.org/zap"
)
// Logger zap logger instance
var Logger *zap.Logger
func init() {
l, err := zap.NewProduction()
if err != nil {
log.Fatalln(err)
}
Logger = l
}
|
package service
import (
"context"
"sync"
raEvents "github.com/go-ocf/cloud/resource-aggregate/cqrs/events"
pbRA "github.com/go-ocf/cloud/resource-aggregate/pb"
"github.com/go-ocf/cqrs/event"
"github.com/go-ocf/cqrs/eventstore"
httpUtils "github.com/go-ocf/kit/net/http"
)
type resourceCtx struct {
lock s... |
package services
import (
"os"
"sync"
"sort"
"log"
"example.com/finder/models"
)
var dirPath string
func GetFiles(dirPath string) ([]os.FileInfo, error) {
f, err := os.Open(dirPath)
if err != nil {
return []os.FileInfo{}, err
}
files, err := f.Readdir(-1)
f.Close()
if err != nil {
return []os.FileInfo{... |
/*
* @lc app=leetcode.cn id=63 lang=golang
*
* [63] 不同路径 II
*/
// @lc code=start
package main
import "fmt"
func main() {
a := [][]int {
{0,0,1},
{0,0,0},
{0,0,0},
}
fmt.Println(uniquePathsWithObstacles(a))
}
func uniquePathsWithObstacles(obstacleGrid [][]int) int {
n := len(obstacleGrid)
m := len(obs... |
package com
import (
"fmt"
"gopkg.in/go-playground/validator.v9"
"log"
"testing"
)
func Test_Validation(t *testing.T) {
type Address struct {
Street string `validate:"required"`
City string `validate:"required"`
Planet string `validate:"required"`
Phone string `validate:"required"`
}
type User stru... |
package main
import "fmt"
func do(i interface{}){
switch i.(type) {
case int:
fmt.Println("int type")
case string:
fmt.Println("string type")
default:
fmt.Printf("unknown type %T\n", i)
}
}
func main() {
do(12)
do("Ayo")
do(4 + 5i)
do(false)
} |
package alibabacloud
import (
"sort"
survey "github.com/AlecAivazis/survey/v2"
"github.com/AlecAivazis/survey/v2/core"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// GetBaseDomain returns a base domain chosen from among the account's domains.
func GetBaseDomain() (string, error) {
client, err := New... |
package testutils
import (
"io/ioutil"
"os"
"github.com/mitchellh/go-homedir"
)
// NewTempDir constructs a new temporary directory
// and returns the directory name along with a cleanup function
// or any error that occurred during the process
func NewTempDir(name string) (string, func(), error) {
dir, err := io... |
package gosupervisor
// SupervisorRPC ...
type SupervisorRPC struct {
URL string
}
// New ...
func New(url string) *SupervisorRPC {
return &SupervisorRPC{URL: url}
}
|
/*
This file handles configuration info for a DVID datastore and its serialization
to files as well as the keys to be used to store values in the key/value store.
*/
package datastore
import (
"encoding/json"
"fmt"
_ "log"
"github.com/janelia-flyem/dvid/dvid"
"github.com/janelia-flyem/dvid/storage"
)
const (... |
package commands
import (
"fmt"
"github.com/cuichenli/doing/model"
"github.com/spf13/cobra"
)
var showCommand = &cobra.Command{
Use: "show",
Short: "Show all records",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
records, err := getExistingRecords()
if err != nil {
retur... |
// Copyright 2021 Clivern. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package service
import (
"fmt"
"strings"
"github.com/manifoldco/promptui"
)
// Prompt struct
type Prompt struct {
}
// NotEmpty returns error if input is empty
func... |
package smg
import (
"encoding/json"
"errors"
"os"
"os/signal"
"path"
"path/filepath"
"syscall"
"github.com/sirupsen/logrus"
"github.com/geniuscirno/smg/configurator"
"github.com/geniuscirno/smg/registrator"
)
type EnvironmentType int
const (
EEnvironmentTypeInvaild EnvironmentType... |
package heuristics
func tScore(puzzle []int, nb int, x int, y int, size int) float32 {
nb1 := puzzle[get1d(x, y, size)]
if nb == nb1 {
return 0
}
return 1
}
// Tiles out-of place
func toop(grid []int, size int, depth int) float32 {
var score float32
for x := 0; x < size; x++ {
for y := 0; y < size; y++ {
... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//110. Balanced Binary Tree
//Given a binary tree, determine if it is height-balanced.
//For this problem, a height-balanced binary tree is defined as:... |
package httpserver
import (
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"go.uber.org/zap"
)
type options struct {
//TODO add storage interface
logger *zap.Logger
}
// Option server options
type Option interface {
apply(*options)
}
typ... |
package main
//import fmt "fmt" // Пакет, реализующий форматированный ввод-вывод
func main() {
//fmt.Printf("Hello, world; Привет, мир; или Καλημέρα κόσμε; или こんにちは 世界\n")
// fmt.Printf("Hello, world\n");
}
|
package exchange
import (
"io/ioutil"
"testing"
"github.com/ghodss/yaml"
"github.com/test-go/testify/require"
)
func TestHandlePairSyncEvent(t *testing.T) {
t.Skipf("ski pair sync event")
testCase := &TestCase{}
pairSyncEventYaml, err := ioutil.ReadFile("./testdata/TestHandlePairSyncEvent.yaml")
require.NoEr... |
package migration
import (
"database/sql"
"github.com/jinzhu/gorm"
"github.com/pressly/goose"
"tezos_index/puller/models"
)
func init() {
goose.AddMigration(Up20200910103420, Down20200910103420)
}
func Up20200910103420(tx *sql.Tx) error {
// This code is executed when the migration is applied.
db, err := gorm... |
package charts
import "github.com/go-echarts/go-echarts/v2/opts"
type SingleSeries struct {
Name string `json:"name,omitempty"`
Type string `json:"type,omitempty"`
// Rectangular charts
Stack string `json:"stack,omitempty"`
XAxisIndex int `json:"xAxisIndex,omitempty"`
YAxisIndex int `json:"yAxisInde... |
package infrastructure
import (
"github.com/caarlos0/env"
"github.com/pkg/errors"
"regexp"
)
type Config struct {
Port string `env:"CONVERTER_PORT" envDefault:":8000"`
}
func LoadConfig() (Config, error) {
cnf := Config{}
err := env.Parse(&cnf)
if err != nil {
return cnf, err
}
err = validateConfig(cnf)... |
package tsrv
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document00300101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:tsrv.003.001.01 Document"`
Message *UndertakingIssuanceNotificationV01 `xml:"UdrtkgIssncNtfctn"`
}
func (... |
package main
import (
"bufio"
"fmt"
"io"
"log"
"net"
)
type file struct {
name string
content []byte
}
type server struct {
files []file
}
var ftp *server
func init() {
f1 := file{"hello.txt", []byte("helllo world")}
f2 := file{"goodbye.txt", []byte("goodbye")}
ftp = &server{[]file{f1, f2}}
}
func ... |
package simple_factory
import "fmt"
type Person interface {
Say()
}
type Man struct {
Person
}
func (m *Man) Say() {
fmt.Println("man")
}
type Women struct {
Person
}
func (w *Women) Say() {
fmt.Println("women")
}
func NewPerson(t int) Person {
switch t {
case 0:
return &Women{}
case 1:
return &Man{}... |
package models
import (
"fmt"
"github.com/astaxie/beego/orm"
"github.com/devplayg/ipas-mcs/objs"
log "github.com/sirupsen/logrus"
)
// 순위통계 검색 by 기관, 그룹, 장비(stats_evt?_by_(group|equip)
func GetStatsBy(member *objs.Member, filter *objs.StatsFilter) ([]objs.Stats, int64, error) {
var where string
var args []inter... |
package validate
import (
"fmt"
"net/url"
)
// URI ...
func URI(uri string) error {
_, err := url.ParseRequestURI(uri)
return err
}
// Currency ...
func Currency(currency string, currencyArray []string) error {
for _, c := range currencyArray {
if c == currency {
return nil
}
}
return fmt.Errorf("curr... |
package config
import (
"testing"
)
func TestRead(t *testing.T) {
//configDB := &ConfigDB{
// Dbhost: "172.26.163.76",
// Dbport: "3306",
// Dbuser: "rookie2",
// Dbpassword: "12345678",
// Dbname: "dbconfig",
// Tblname: "params",
//}
////err := configDB.GetParameters(PARAMS)
//if err ... |
package notifications
import (
"context"
"fmt"
"strings"
"testing"
"time"
"github.com/go-kit/kit/log"
"github.com/stretchr/testify/assert"
"gopkg.in/DATA-DOG/go-sqlmock.v1"
)
func TestCreateNotificationShouldReturnNoError(t *testing.T) {
db, mock, err := setUpTestDatabase()
assert.NoError(t, err)
n := &N... |
package dto
type SignupUserDto struct {
Username string `json:"username"`
Password string `json:"password"`
Email string `json:"email"`
IsSubscribed bool `json:"isSubscribed"`
}
|
package main
import (
"fmt"
"image"
"math"
"os"
)
type Rnd interface {
Float64() float64
}
func randomInUnitSphere(rnd Rnd) Vector {
x := rnd.Float64()
y := rnd.Float64()
z := rnd.Float64()
s := math.Sqrt(1.0 / (x*x + y*y + z*z))
return Vector{s * x, s * y, s * z}
}
func randomInUnitDisk(rnd Rnd) Vector {... |
package db
import (
"context"
"time"
"gcp-trace/ltrace"
"go.opencensus.io/trace"
)
// Query emulates some DB request
func Query(ctx context.Context, traceable bool) {
if traceable {
_, span := trace.StartSpan(ctx, ltrace.Prefix+"/db")
defer span.End()
}
time.Sleep(50 * time.Millisecond)
}
|
package moex
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/inputs"
)
type Moex struct{
start, limit int
ac telegraf.Accumulator
Log telegraf.Logger `toml:"-"`
Tickers []string `toml:"tickers"`
}
type History stru... |
package hoist
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
"time"
"github.com/square/p2/pkg/util/size"
. "github.com/anthonybishopric/gotcha"
)
type testInstall struct {
name string
modTime time.Time
byteCount size.ByteCount
}
func (i testInstall) create(parent string) error {
path ... |
package cgroup
// Cgroup defines the common interface to control cgroups
// including v1 and v2 implementations.
// TODO: implement systemd integration
type Cgroup interface {
// AddProc add a process into the cgroup
AddProc(pid int) error
// Destroy deletes the cgroup
Destroy() error
// CPUUsage reads total cp... |
package goauth
import (
"bytes"
"net/http"
"net/http/httptest"
"testing"
)
func TestCheckInScopeTrue(t *testing.T) {
scope := []string{"1", "2", "3"}
check := "1"
b := checkInScope(check, scope)
if !b {
t.Error("Test failed, expected true but got false")
}
}
func TestCheckInScopeFalse(t *testing.T) {
sco... |
package storage_test
import (
"fmt"
"testing"
"github.com/lorthos/gosu/storage"
"strings"
)
//https://groups.google.com/forum/#!topic/google-appengine-go/Kh1eLUROq90
//https://blog.golang.org/gobs-of-data
func assertEqual(t *testing.T, a interface{}, b interface{}, message string) {
if a == b {
return
}
if... |
package main
import (
"context"
"fmt"
"os/exec"
"time"
)
//命令运行结果
type result struct {
output []byte
err error
}
func main() {
//执行一个cmd,让它在一个协程里去执行,让它执行2秒,sleep 2;echo hello;
//1秒的时候,我们杀死cmd
var (
ctx context.Context
cancelFunc context.CancelFunc
resultChan chan *result
)
resultChan = m... |
// Copyright 2020 The Reed Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
package vm
import (
"bytes"
"github.com/reed/crypto"
"github.com/reed/errors"
"github.com/reed/vm/vmcommon"
)
var (
vmErr = errors.New(... |
package pokemon
import (
"fmt"
"net/http"
"github.com/skos-ninja/truelayer-tech/svc/pokemon/app"
"github.com/skos-ninja/truelayer-tech/svc/pokemon/rpc"
"github.com/gin-gonic/gin"
"github.com/spf13/cobra"
)
var CMD = &cobra.Command{
Use: "pokemon",
RunE: runE,
}
func runE(cmd *cobra.Command, args []string)... |
package contracts
import (
"context"
"math/big"
"time"
"github.com/smartcontractkit/integrations-framework/client"
"github.com/smartcontractkit/integrations-framework/config"
"github.com/smartcontractkit/integrations-framework/tools"
. "github.com/onsi/ginkgo"
. "github.com/onsi/ginkgo/extensions/table"
. "... |
package etcdummy
import (
"log"
"net"
"sort"
"sync"
"time"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/coreos/etcd/etcdserver/etcdserverpb"
"github.com/coreos/etcd/mvcc/mvccpb"
)
var (
ErrNotImplemented = status.Errorf(c... |
package e2e
import (
"context"
"fmt"
"github.com/blang/semver/v4"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
. "github.com/operator-framework/operator-lifecycle-manager/test/e2e/dsl"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis... |
package issue_test
import (
"context"
"testing"
"go.mongodb.org/mongo-driver/bson/primitive"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"go.mongodb.org/mongo-driver/bson"
"williamfeng323/mooncake-duty/src/domains/issue"
"williamfeng323/mooncake-duty/src/domains/project"
repoimpl "williamfeng323/... |
// +build generic
package agrasta
func (s *State) rand() uint64 {
s.rpos--
if s.rpos < 0 {
binary.Read(s.ShakeHash, binary.LittleEndian, &s.rbuf)
s.rpos = 16
}
return s.rbuf[s.rpos]
}
|
// Copyright (c) 2012-2014 Jeremy Latt
// Copyright (c) 2014-2015 Edmund Huber
// Copyright (c) 2017 Daniel Oaks <daniel@danieloaks.net>
// released under the MIT license
package irc
import (
"fmt"
"net"
"github.com/oragono/oragono/irc/modes"
"github.com/oragono/oragono/irc/utils"
)
type webircConfig struct {
... |
/*
Package crypto "Every package should have a package comment, a block comment preceding the package clause.
For multi-file packages, the package comment only needs to be present in one file, and any
one will do. The package comment should introduce the package and provide information
relevant to the package as a whol... |
package main
import (
"context"
"fmt"
"os"
"sort"
"github.com/google/go-github/v31/github"
"github.com/rotisserie/eris"
"github.com/solo-io/go-utils/versionutils"
"github.com/spf13/cobra"
"golang.org/x/oauth2"
)
func main() {
ctx := context.Background()
app := rootApp(ctx)
if err := app.Execute(); err !=... |
package main
import (
"exer9"
"fmt"
"math"
)
func main() {
fmt.Println(exer9.Message)
pt := exer9.NewPoint(3, 4.5)
fmt.Println(pt) // should print (3, 4.5)
fmt.Println(pt.String() == "(3, 4.5)") // should print true
p1 := exer9.NewPoint(3, 4)
fmt.Println(p1.Norm() == 5.0)
p1.Scale(5... |
/*
Copyright 2011 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
di... |
package db_analyze
import (
"database/sql"
"encoding/csv"
"encoding/json"
"fmt"
_ "github.com/go-sql-driver/mysql"
"log"
"os"
"strconv"
"time"
)
type DbWorker struct {
//mysql data source name
Dsn string
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}
type raiingTCMSUser struct {
id ... |
//
// Copyright (C) 2019-2021 vdaas.org vald team <vald@vdaas.org>
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless requir... |
package group
import "titan-auth/types"
// 创建组织请求
type CreateGroupReq struct {
Name string `json:"name"`
Parent string `json:"parent_id"`
Description string `json:"description"`
}
// 创建组织响应
type CreateGroupResp struct {
types.Group
}
// 查询所有组织请求
type QueryGroupsReq struct {
}
// 查询所有组织响应
type Query... |
package main
import (
"flag"
"fmt"
"net"
"strings"
"syscall"
"github.com/syossan27/tebata"
)
var (
address string
protocol string
ports string
)
func listen(address, port, protocol string, t *tebata.Tebata) error {
listenAddress := address + ":" + port
fmt.Println(listenAddress, protocol)
lis, err :... |
//go:build browsertest
package checkbox_test
import (
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/shurcooL/frontend/checkbox"
"github.com/shurcooL/go/gopherjs_http"
"github.com/shurcooL/go/open"
"github.com/shurcooL/httpfs/httputil"
)
func Test(t *testing.T) {
http.Handle("/script.js", httput... |
package 一维子序列问题
// dp[i] 表示: 以nums[i]结尾的最长递增子序列长度
// count[i]表示: 以nums[i]结尾的最长递增子序列个数
func findNumberOfLIS(nums []int) int {
dp := [2005]int{}
count := make(map[int]int, len(nums)+5)
for i := 0; i < len(nums); i++ {
dp[i] = 1 // 注意初始化
count[i] = 1 // 注意初始化
for t := 0; t < i; t++ {
if nums[i] > nums[t]... |
// Copyright 2019-2023 The sakuracloud_exporter 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 appl... |
package connector
import (
"sync"
"github.com/mayflower/docker-ls/lib/auth"
)
type tokenCache struct {
entries map[string]auth.Token
mutex sync.RWMutex
}
func (t *tokenCache) Get(hint string) (token auth.Token) {
t.mutex.RLock()
if value, cached := t.entries[hint]; cached {
token = value
}
t.mutex.RUnlo... |
/*
Copyright 2018 Mark DeNeve.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
di... |
package alg
import (
"algutil"
"math/rand"
"testing"
)
func TestHuffmanCode1(t *testing.T) {
input1 := make([]*HuffmanCodeInput, 0)
a := new(HuffmanCodeInput)
a.count = 45
a.Value = 'a'
input1 = append(input1, a)
input1[0] = a
b := new(HuffmanCodeInput)
b.count = 13
b.Value = 'b'
input1 = append(input1, ... |
package skipList
import (
"math/rand"
"strconv"
"testing"
"time"
)
func BenchmarkSkipList_Insert_Ordered(b *testing.B) {
skipList := NewSkipList(10)
b.ReportAllocs()
for i := 0; i < b.N; i++ {
t := rand.New(rand.NewSource(time.Now().UnixNano())).Intn(100000)
_ = Hash([]byte(strconv.Itoa(t)))
skipList.Ins... |
package cmd
import (
"fmt"
"os"
"strings"
"github.com/mattn/go-pipeline"
"github.com/urfave/cli"
)
func Commit(c *cli.Context) error {
cmd, opts := getCmdOpts()
texts, err := filterMsgs(cmd, opts)
if err != nil {
fmt.Println(err)
return err
}
if len(texts) == 0 {
return nil
}
if len(texts) != 1 {
... |
// Copyright 2020 Bjerk AS
//
// 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 wr... |
package main
type Client interface {
Conn()
}
type DBClient struct {
timeout int
retryTimes int
}
func (c DBClient) Conn() {
// Do SOMETHING
}
type ClientConnOption func(*ClientConnOptions)
type ClientConnOptions struct {
retryTimes int
timeout int
}
func WithRetryTimes(retryTimes int) ClientConnOptio... |
/*
* This file is part of impacca. Copyright (C) 2013 and above Shogun <shogun@cowtech.it>.
* Licensed under the MIT license, which can be found at https://choosealicense.com/licenses/mit.
*/
package utils
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/Masterminds/se... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//146. LRU Cache
//Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
... |
package requests
import (
"encoding/json"
"testing"
"github.com/mitchellh/mapstructure"
"github.com/stretchr/testify/assert"
)
func TestDecodePasswordChangeRequest(t *testing.T) {
encoded := `{"action":"password_change","password":"1234","wallet":"1234"}`
var decoded PasswordChangeRequest
json.Unmarshal([]byt... |
package medias
import (
"encoding/json"
"errors"
"net/http"
"os"
"path/filepath"
"strconv"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
"github.com/Zenika/marcel/api/auth"
"github.com/Zenika/marcel/api/clients"
"github.com/Zenika/marcel/api/commons"
"github.com/Zenika/marcel/api/db/medias"
... |
/////////////////////////////////////////////////////////////////////
// arataca89@gmail.com
// 20210417
//
// func Split(s, sep string) []string
//
// Retorna um slice dos tokens de s separados por sep.
// Se s não contém sep e sep não é vazio, retorna um slice de tamanho
// 1 cujo único elemento é s.
// Se s... |
package plik
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"github.com/root-gg/utils"
"github.com/root-gg/plik/server/common"
)
// Create creates a new empty upload on the Plik Server and return the upload metadata
func (c *Clien... |
package server
import (
"net/http"
"strconv"
"github.com/empirefox/esecend/cerr"
"github.com/empirefox/esecend/front"
"github.com/gin-gonic/gin"
)
func (s *Server) PostWishlistAdd(c *gin.Context) {
var payload front.WishlistSavePayload
if err := c.BindJSON(&payload); Abort(c, err) {
return
}
data, err :... |
// len.
package main
import (
"fmt"
)
func main() {
ss := []string{"hello world"}
printss := func() {
fmt.Printf("%q\n\tlen:%d\n\n", ss, len(ss))
}
printss()
ss = append(ss, "foo", "bar")
printss()
fmt.Printf("ss[1:1]:%q len:%d, cap:%d\n\n", ss[1:1], len(ss[1:1]), cap(ss[1:1]))
s := "hello world"
fmt.P... |
package friend
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
pbFriend "Open_IM/pkg/proto/friend"
"Open_IM/pkg/utils"
"context"
)
func (s *friendServer) GetBlacklist(ctx context.Context, req *pbFriend.GetBlacklistReq) (*pbFriend.GetBlacklistResp,... |
package helper
import (
"bytes"
"fmt"
"io"
"strings"
)
//THIS files funtions has been borrowed from
func escapeString(txt string) string {
var (
esc string
buf bytes.Buffer
)
last := 0
for ii, bb := range txt {
switch bb {
case 0:
esc = `\0`
case '\n':
esc = `\n`
case '\r':
esc = `\r`
c... |
// Copyright 2019 The go-interpreter 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 compile
import (
ops "github.com/go-interpreter/wagon/wasm/operators"
)
type scanner struct {
supportedOpcodes map[byte]bool
}
// Inst... |
package models
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/stretchr/testify/assert"
"strconv"
"strings"
"testing"
)
func TestHarvesterStatus_TableName(t *testing.T) {
dsn := "root:WcGsHDMBmcv7mc#QWkuR@tcp(127.0.0.1:3306)/tezos_index?charset=utf8mb4&parseTime=True&loc... |
package views
import (
"fmt"
"os"
"path/filepath"
"text/template"
)
var (
LayoutDir string = "views/layouts/"
TemplateDir string = "views/"
TemplateExt string = ".tmpl"
)
type View struct {
Template *template.Template
Layout string
}
func NewView(layout string, files ...string) *View {
for i, f := ran... |
package mock
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/pomerium/pomerium/internal/sessions"
)
func TestStore(t *testing.T) {
tests := []struct {
name string
store *Store
wantLoad string
saveSession *sessions.State
wantLoadErr bool
wantSaveErr bool
}{
{
... |
package requests
import "time"
var _ = time.Time{}
type CreateProject struct {
Status string
}
type UpdateProject struct {
Status string
}
func (c *CreateProject) Valid() error {
return validate.Struct(c)
}
func (c *UpdateProject) Valid() error {
return validate.Struct(c)
}
|
package drivers
// ToOneRelationship describes a relationship between two tables where the local
// table has no id, and the foreign table has an id that matches a column in the
// local table, that column can also be unique which changes the dynamic into a
// one-to-one style, not a to-many.
type ToOneRelationship st... |
/*
Today your goal is to find integers a and b given non-negative integer n such that:
(3 + sqrt(5))^n = a + b * sqrt(5)
You should write a program or a function that takes parameter n and outputs a and b in a format of your choice.
Standard loopholes apply. Additionally, it's intended that you implement the above ... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//33. Search in Rotated Sorted Array
//Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
//(i.e., [0,1,2,4... |
package main
import (
"encoding/json"
"flag"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"os"
"regexp"
"strings"
)
var (
proxyFlag = flag.String("p", "", "valid proxy ip address with port (ex: 176.107.17.129:8080")
receiverTargetURLFlag = flag.String("t", "", "Target URL that has the receiver... |
package jsonrpc
import (
"bufio"
"net"
)
// DECL> OMIT
// Channel represents some absctract channel over net.Conn.
type Channel struct {
conn net.Conn
out chan Packet
}
func NewChannel(conn net.Conn) *Channel {
c := &Channel{conn, make(chan Packet, N)}
go c.reader()
go c.writer()
}
// DECL< OMIT
// IMPL> OM... |
package api_test
import (
"net/http"
"github.com/odpf/stencil/config"
"github.com/odpf/stencil/server"
"github.com/odpf/stencil/server/api"
"github.com/odpf/stencil/server/api/mocks"
)
func setup() (http.Handler, *mocks.StoreService, *mocks.MetadataService, *api.API) {
mockService := &mocks.StoreService{}
mo... |
package main
import "fmt"
type Human struct {
name string
age int
phone string
}
type Student struct {
Human
school string
}
type Employee struct {
Human
company string
}
func (h *Human) SayHi() {
fmt.Printf("Hi, I am %s u can call me on %s\n", h.name, h.phone)
}
func main() {
... |
package main
import (
"fmt"
"log"
"os"
_ "restaurantManageAPI/init/runtime"
"restaurantManageAPI/pkg/router"
)
func main() {
err := router.Router.Run(fmt.Sprintf(":%s", os.Getenv("GIN_SERVER_PORT")))
if err != nil {
log.Fatal(err)
}
}
|
package cache
import (
"fmt"
"github.com/pilillo/igovium/utils"
)
// todo: convert to a map
func NewDMCacheFromConfig(config *utils.DMCacheConfig) (DMCache, error) {
switch dmType := config.Type; dmType {
case "olric":
return NewOlricDMCache(), nil
case "redis":
return NewRedisDMCache(), nil
default:
ret... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.