text stringlengths 11 4.05M |
|---|
package nrpc
import (
"context"
"errors"
"github.com/stretchr/testify/require"
"net/http"
"net/http/httptest"
"testing"
)
type TestHealthCheck struct {
err error
}
func (hc *TestHealthCheck) HealthCheck(ctx context.Context) error {
return hc.err
}
func TestHealthChecks(t *testing.T) {
hc1 := &TestHealthChe... |
package auth
import (
"log"
"fmt"
"net/http"
"time"
"encoding/json"
"github.com/go-ldap/ldap/v3"
"github.com/dgrijalva/jwt-go"
"mytca/booking/db/my_ldap"
)
// For HMAC signing method, the secret key can be any []byte. It is recommended to generate
// a key using crypto/rand or something equivalent. You need t... |
package _287_Find_the_Duplicate_Number
func findDuplicate(nums []int) int {
var (
slow = nums[0]
fast = nums[nums[0]]
)
for {
if slow == fast {
break
}
slow = nums[slow]
fast = nums[nums[fast]]
}
fast = 0
for {
if slow == fast {
return fast
}
fast = nums[fast]
slow = nums[slow]
}
retu... |
func pivotIndex(nums []int) int {
res := -1
sum:=0
csum:=0
for _,v:=range nums{
sum+=v
}
for i,v:=range nums{
if (sum-v)/2==csum && (sum-v)%2==0{
res=i
break
}
csum+=v
}
return res
}
|
package secret
import (
"fmt"
"image"
_ "image/png"
"io/ioutil"
"net/url"
"os"
"os/exec"
"strings"
"github.com/makiuchi-d/gozxing"
"github.com/makiuchi-d/gozxing/qrcode"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh/terminal"
)
type SecretValue struct {
value string
isSet bool
}
func (s *SecretValu... |
package main
import (
"bytes"
"encoding/binary"
)
func EncodeUTF32BE(codepoints []uint32) []byte {
buf := new(bytes.Buffer)
// BOM (optional)
binary.Write(buf, binary.BigEndian, uint32(0xFEFF))
for _, codepoint := range codepoints {
// Each codepoint is written as unit32
binary.Write(buf, binary.BigEndian... |
package main
import "fmt"
func calcTriangle(a, b int) int {
return a + b
}
// 入口函数
func main() {
sum := calcTriangle(1,3)
fmt.Println(sum)
}
|
package statistics
var (
TransferMgr *StatTransferManager
PkgMgr *StatPkgManager
)
func init() {
TransferMgr = NewStatTransferManager()
PkgMgr = new(StatPkgManager)
}
|
package main
import "fmt"
func main() {
go f(0) //to execute this function in background and proceed with next statements
var input int
fmt.Scanf("%d",&input)
fmt.Println(input)
}
func f(n int){
for i :=0;i<50;i++{
fmt.Println(n,":",i)
}
}
|
package model
import (
"github.com/sirsean/packhunter/ph"
"gopkg.in/mgo.v2/bson"
)
type Tag struct {
Id bson.ObjectId `bson:"_id,omitempty"`
Owner BasicUser
Name string
Public bool
Users []ph.User
}
type BasicTag struct {
Id string
OwnerId string
Name string
UserCount int
}
type Bas... |
// Copyright © 2020 Attestant Limited.
// 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 ... |
// Copyright 2013 hanguofeng. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gocaptcha
import (
"time"
)
//CaptchaConfig ,the captcha config
type CaptchaConfig struct {
LifeTime time.Duration
CaseSensitive bool
}
//FilterC... |
package p10
func canThreePartsEqualSum(A []int) bool {
sum := 0
for _, v := range A {
sum += v
}
if sum%3 != 0 {
return false
}
s := sum / 3
curS := 0
for i := 0; i < len(A); i++ {
curS += A[i]
if curS == s {
curS = 0
}
}
if curS != 0 {
return false
}
return true
}
|
package ospafLib
import (
github "../github"
"fmt"
"io/ioutil"
"net/http"
"strconv"
)
type Account struct {
//Basic/Oauth
Type string
User string
Password string
Remains int
}
//TODO: add lock to Remains
func (account *Account) Init(accountType string, accountUser string, accountPassword string) ... |
package gonbt
import (
"bytes"
"testing"
"github.com/stretchr/testify/assert"
)
func TestReader_String(t *testing.T) {
t.Run("read return an error because reader is empty", func(t *testing.T) {
data := []byte{}
r := &reader{flux: bytes.NewReader(data)}
expectedError := "EOF"
str, err := r.String()
if ... |
package main
import (
"fmt"
ct "go-ansi"
)
func main() {
ct.ResetColor()
ct.ChangeColor(ct.RED,true, ct.BLACK, false)
fmt.Println("red forecolor and black bgcolor")
ct.ChangeColor(ct.NONE,false, ct.GREEN, false)
fmt.Print("white forecolor and green bgcolor")
ct.ResetColor()
fmt.Println()
fmt.Println("NORMAL... |
/*
Copyright 2021 CodeNotary, Inc. 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 applicable law or agreed to i... |
//go:generate pumapotion $GOFILE
package odder
//pumapotion:generate service depends Evener
type Odder interface {
IsOdd(n int) (even bool, err error)
}
|
package model
import (
"github.com/astaxie/beego/config"
"fmt"
"github.com/astaxie/beego/orm"
)
/**
*
* 初始化mysql数据
*/
func init(){
appConf, err := config.NewConfig("ini", "conf/app.conf")
if err != nil {
panic(err)
}
orm.RegisterDriver("mysql", orm.DRMySQL)
conn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?chars... |
package fileinfo
import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
)
const (
PathSep = string(os.PathSeparator)
)
// os.FileInfo + inode
type FileInfo struct {
fi os.FileInfo
dir string
ino uint64 // inode
}
func Stat(name string) (*FileInfo, error) {
info := &FileInfo{}
fi, err := os.Stat(name)
if... |
package storage
import (
"docktor/server/types"
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
)
// ConfigRepo is the repo for config
type ConfigRepo interface {
// Save the config into database
Save(config types.Config) (types.Config, error)
// Find get the config
Find() (types.Config, error)
... |
package ias3
import (
"bytes"
"fmt"
"net/http"
"os"
"regexp"
"strings"
)
const baseURL = "http://s3.us.archive.org/"
//Req holds the data for the request
type Req struct {
header http.Header
}
//NewReq returs a new Req
func NewReq() *Req {
return &Req{header: make(http.Header)}
}
//AutoCreateBucket creates... |
package main
import (
"fmt"
"net/http"
)
func DisplayHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Headers\n")
for name, values := range r.Header {
for _, value := range values {
fmt.Fprintf(w, "%s: %s\n", name, value)
}
}
}
|
package models
type Users struct {
Id int `json:"id"`
FullName string `json:"full_name" db:"full_name"`
Email string `json:"email"`
Phone string `json:"phone"`
About string `json:"about"`
CourseId int `json:"course_id,omitempty" db:"course_id"`
//Password string `json:"password" db:"password_hash"`
}
type Subs... |
// Created at 10/25/2021 3:43 PM
// Developer: trungnq2710 (trungnq2710@gmail.com)
package go_apns
type aps struct {
Alert interface{} `json:"alert,omitempty"`
Badge int `json:"badge,omitempty"`
Sound interface{} `json:"sound,omitempty"`
ThreadId string `j... |
package swarm
import (
"errors"
"testing"
"time"
"github.com/docker/engine-api/types/swarm"
"github.com/gaia-docker/tugbot-leader/mockclient"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func TestUpdateServices_ErrorServiceList(t *testing.T) {
client := mockclient.NewMockClient()... |
/*
* Copyright 2018 Dgraph Labs, Inc. and Contributors
*
* 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 appli... |
package main
import (
"strconv"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/user/:id", getUserData)
router.Run(":8080")
}
func getUserData(c *gin.Context) {
user_id, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.JSON(200, gin.H{"user_id":"0"})
return
}
c.JSO... |
package diffsquares
// SquareOfSum returns the the square of the sum of the first N natural numbers.
func SquareOfSum(number int) (square int) {
sum := (number * (number + 1)) / 2 // note to self instead of /2, >> 1 is also possible.
return sum * sum
}
// SumOfSquares returns the sum of the squares of the first N ... |
package tusdx
import "fmt"
var Version string
func init() {
Version = fmt.Sprintf(
"|- %s service:\t\t\t%s",
"tusdx",
"0.0.1")
}
|
package simplessh
import (
"errors"
"os"
"github.com/cinus-ue/securekit/common/sshclient"
)
type CommandFunc func(args []string, client *sshclient.Client) error
type ExtendedCommand struct {
name string
cf CommandFunc
usage string
}
var argsError = errors.New("required arguments not provided")
var (
ft... |
//test toml format,and can decode in a map[string]interface{}
package main
import (
"log"
"net/http"
"vendor/toml"
)
const (
routeConfig = "config/laserRouter.cfg"
)
func main() {
log.Println(http.Dir(routeConfig))
var result = make(map[string]interface{})
_, err := toml.DecodeFile(routeConfig, result)
if er... |
package main
import (
"strconv"
"strings"
)
// result represents a benchmark test result.
type result struct {
rowno int
rank int
userName string
score float64
trimDecimal bool
}
// String returns a string value of the result.
func (r result) String() string {
// Create a string value o... |
package cmd
import (
"github.com/Files-com/files-cli/lib"
"github.com/spf13/cobra"
"fmt"
"os"
files_sdk "github.com/Files-com/files-sdk-go"
"github.com/Files-com/files-sdk-go/automation"
)
var (
Automations = &cobra.Command{
Use: "automations [command]",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra... |
package log
import (
"github.com/go-jar/golog"
"blog/conf"
)
var accessLogWriter golog.IWriter
var AccessLogger golog.ILogger
var traceLogWriter golog.IWriter
var TraceLogger golog.ILogger
var NoopLogger golog.ILogger = new(golog.NoopLogger)
var TestLogger, _ = golog.NewConsoleLogger(golog.LevelDebug)
func Ini... |
package model
import (
"time"
"github.com/google/uuid"
"gorm.io/gorm"
)
type Item struct {
ID string `json:"-" gorm:"primaryKey"`
Title string `json:"title,omitempty"`
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
DeletedAt gorm.DeletedAt `json:"-" sql:"in... |
package fuse
import (
"bytes"
"fmt"
"log"
"path/filepath"
"strings"
"sync"
)
type mountData struct {
// If non-nil the file system mounted here.
fs PathFilesystem
// Protects the variables below.
mutex sync.RWMutex
// If yes, we are looking to unmount the mounted fs.
unmountPending bool
// Count files... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-08-18 15:42
# @File : of_剑指_Offer_28_对称的二叉树.go
# @Description : 判断树是否是对称的
# @Attention :
*/
package offer
func isSymmetric(root *TreeNode) bool {
if nil == root {
return true
}
return recurr(root.Left, root.Right)
}
func recurr(left, right *TreeNode) b... |
package key
import (
"fmt"
"strings"
"github.com/giantswarm/apiextensions-application/api/v1alpha1"
"github.com/giantswarm/k8smetadata/pkg/annotation"
"github.com/giantswarm/microerror"
)
func ChartConfigMapName(customResource v1alpha1.App) string {
return fmt.Sprintf("%s-chart-values", customResource.GetName(... |
package lox
func (p *Parser) expression() Expr {
return p.assignment()
}
func (p *Parser) assignment() Expr {
expr := p.equality()
if p.match(TokenTypeEqual) {
equals := p.previous()
value := p.assignment()
exprVar, ok := value.(*ExprVar)
if ok {
return &ExprAssign{exprVar.Name, value}
}
pan... |
package report
import (
"github.com/jinzhu/gorm"
)
type RepositoryInterface interface {
getProductValuesReport() ([]productStock, error)
getSalesReport() ([]order, error)
}
type reportRepository struct {
DB *gorm.DB
}
func initRepository(db *gorm.DB) RepositoryInterface {
return &reportRepository{
DB: db,
}... |
package main
import (
"fmt"
"log"
"google.golang.org/protobuf/encoding/protojson"
"int64json/proto/intjson"
)
func main() {
messages := []*intjson.Numbers{
&intjson.Numbers{
Label: "small numbers",
Signed64: -10,
Unsigned64: 12,
Signed32: -210,
Unsigned32: 212,
},
&intjson.Numbers{
L... |
package manifest
import (
"strings"
"github.com/docker/buildx/util/platformutil"
v1 "github.com/opencontainers/image-spec/specs-go/v1"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
type DeploymentOpt struct {
Nam... |
/*
Copyright 2021 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, so... |
package main
import (
"errors"
"fmt"
"time"
"github.com/pebbe/zmq4"
)
// for the momment desn't work because
// Assertion failed: !_current_out (src/router.cpp:191)
func NewPZmqServer() (Server, error) {
ctx, err := zmq4.NewContext()
if err != nil {
return nil, err
}
sock, err := ctx.NewSocket(zmq4.ROUTER... |
package reset
/*
import (
"io/ioutil"
"os"
"path/filepath"
"testing"
"github.com/devspace-cloud/devspace/pkg/devspace/config/constants"
"github.com/devspace-cloud/devspace/pkg/devspace/config/generated"
"github.com/devspace-cloud/devspace/pkg/util/fsutil"
"github.com/devspace-cloud/devspace/pkg/util/log"
"g... |
package main
import (
"context"
"crypto/md5"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"os"
"strings"
"time"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/render"
"github.com/goware/cors"
)
//The Config struct holds general configuration options for the application
type Co... |
package main
import(
"fmt"
"net"
"os"
"encoding/json"
"bytes"
"io"
)
type User struct{
Name UserInfo
Email []Email
}
type UserInfo struct {
userName string
}
type Email struct {
emailAddress string
}
func (u User) String() string {
userString := u.UserInfo.userName
for _, emailData := ran... |
package zip
import (
"archive/zip"
"bytes"
"io"
"net/http"
"os"
"path/filepath"
)
func ExtractFromRequestForm(req *http.Request, field, dest string) error {
f, _, err := req.FormFile(field)
if err != nil {
return err
}
defer f.Close()
buf := new(bytes.Buffer)
fs, err := buf.ReadFrom(f)
if err != nil {
... |
package main
import "fmt"
func main() {
var arr = []int32{11218, 100, 10,8,11, 7, 2, 1, 4, 3, 3, 0, 55, 6}
merge_sort(arr)
}
func merge_sort(arr []int32) {
merge_sortHelper(arr, 0, len(arr)-1)
}
func merge_sortHelper(arr []int32, start int, end int) []int32 {
var mid int
if start >= end {
var retarr []int32... |
package main
import (
. "github.com/dkrieger/batcher/lib"
"github.com/go-redis/redis"
"gopkg.in/urfave/cli.v1"
"gopkg.in/urfave/cli.v1/altsrc"
"os"
"strconv"
"strings"
"time"
)
func main() {
app := cli.NewApp()
app.Name = "batcher"
app.Usage = "Batch contents of various redis streams into one output" +
"... |
package admin
import (
"testing"
"github.com/IcanFun/utils/utils"
"github.com/gin-gonic/gin"
)
type ChangeModel struct {
ID int64 `json:"id"`
CreateAt int64 `json:"create_at"`
UpdateAt int64 `json:"update_at"`
DeleteAt *int64 `json:"delete_at,omitempty"`
}
type User struct {
ChangeModel
Username s... |
// Copyright 2016 Martin Hebnes Pedersen (LA5NTA). All rights reserved.
// Use of this source code is governed by the MIT-license that can be
// found in the LICENSE file.
package main
var (
UsageConnect = `'alias' or 'transport://[host][/digi]/targetcall[?params...]'
transport:
telnet: TCP/IP
ardop: ... |
package main
import (
"bytes"
"context"
"image"
"image/draw"
"image/jpeg"
"image/png"
"log"
"os"
"path"
"strings"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
... |
package backend
import (
"testing"
"github.com/goropikari/psqlittle/core"
"github.com/stretchr/testify/assert"
)
func TestTableCopy(t *testing.T) {
var tests = []struct {
name string
given DBTable
}{
{
name: "test insert",
given: DBTable{
Cols: core.Cols{
{
ColName: core.ColumnName{... |
package gosnowth
import (
"bytes"
"context"
"encoding/json"
"fmt"
"path"
"strconv"
"time"
)
// TextValueResponse values represent text data responses.
type TextValueResponse []TextValue
// UnmarshalJSON decodes a JSON format byte slice into a TextValueResponse.
func (tvr *TextValueResponse) UnmarshalJSON(b []... |
package fixtures
import (
"time"
models "github.com/gomeetups/gomeetups/models"
)
// Rsvps Contains fictures for in memory service
var Rsvps = []models.Rsvp{
{
RsvpID: "62036543-292e-4751-ace0-13624d09c79e",
GroupID: "6db72c07-1fdd-480e-b9af-7dd96efa4986",
EventID: "43e3aef7-af84-468c-a65a-0... |
// Package pkg provides a DC6 animation decoder, used by diablo 2.
package pkg
|
/*
Created by: Maulik Shah (mshah@redhat.com)
Date Created: 10/01/2018
To write all the small helper functions
*/
package main
import (
// "fmt"
"log"
"bufio"
"os"
"strings"
)
// Read the .csv file with the namespace,pod,container name from the fileptr
// and split it into a 2d string array
func readCSV(f... |
// Copyright 2022 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 morgoth
import "github.com/yash-ontic/morgoth/counter"
type Fingerprint interface {
IsMatch(other counter.Countable) bool
}
type Fingerprinter interface {
Fingerprint(window *Window) Fingerprint
}
|
package Model
import (
"testing"
)
var employee Employee
func InitEmployee() {
employee = Employee{
Account: Account{
FirstName: "kazuya",
LastName: "sugimoto",
},
Credit: 100,
}
}
func Test_Employee_ChangeName(t *testing.T) {
InitEmployee()
employee.ChangeName("update", "name")
expect := "updat... |
// Copyright (c) 2020, The Garble Authors.
// See LICENSE for licensing information.
package main
import (
"bytes"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"golang.org/x/mod/module"
)
//go:generate ./scripts/gen-go-std-tables.sh
// sharedCache ... |
package program
import (
"sync"
"sync/atomic"
"time"
"unsafe"
)
//
// 1、Hacked Lock/TryLock 模式
//
//其实,对于标准库的sync.Mutex要增加这个功能很简单,下面的方式就是通过hack的方式为Mutex实现了TryLock的功能。
const mutexLocked = 1 << iota
type Mutex struct {
mu sync.Mutex
}
func (m *Mutex) Lock() {
m.mu.Lock()
}
func (m *Mutex) Unlock() {
m.mu.Unlock... |
package consts
const (
ISTIO_INJECT_ANNOTATION = "sidecar.istio.io/inject"
)
|
package models
type Redditor struct {
Kind string `json:"kind"`
Data RedditorData `json:"data"`
}
type RedditorData struct {
IsEmployee bool `json:"is_employee"`
IconImg string `json:"icon_img"`
PrefShowSnoovatar bool `json:"pref_show_snoovatar"`
Name strin... |
package service
import (
"context"
"github.com/choria-io/aaasvc/signers"
"github.com/choria-io/go-choria/inter"
"github.com/choria-io/go-choria/providers/agent/mcorpc"
"github.com/choria-io/go-choria/server/agents"
"github.com/sirupsen/logrus"
)
type SignRPCRequest struct {
Request string `json:"request"`
... |
/*
* @lc app=leetcode.cn id=1337 lang=golang
*
* [1337] 矩阵中战斗力最弱的 K 行
*/
package main
import (
"sort"
)
// @lc code=start
func kWeakestRows(mat [][]int, k int) []int {
arr := make([]int, len(mat))
for i := 0; i < len(mat); i++ {
arr[i] = i
}
sort.Slice(arr, func(i, j int) bool {
counti := 0
countj := 0... |
package bitsize
import "math"
var sizes [65]uint64
func init() {
for i := 0; i < 65; i++ {
sizes[i] = 1<<uint8(i) - 1
}
}
func Float(v interface{}) uint8 {
switch f := v.(type) {
case float32:
return 32
case float64:
if f >= math.SmallestNonzeroFloat32 && f <= math.MaxFloat32 {
return 32
}
retur... |
package vm
import (
"fmt"
"defs"
"fdops"
"mem"
"util"
)
//import "fd"
const PTE_P mem.Pa_t = 1 << 0
const PTE_W mem.Pa_t = 1 << 1
const PTE_U mem.Pa_t = 1 << 2
const PTE_A mem.Pa_t = 1 << 5
const PTE_D mem.Pa_t = 1 << 6
const PTE_G mem.Pa_t = 1 << 8
const PTE_PCD mem.Pa_t = 1 << 4
const PTE_PS mem.Pa_t = 1 << ... |
package split_string
import (
"strings"
)
//Split self strings.Split
func Split(source string, sep string) []string {
res := make([]string, 0, strings.Count(source, sep)+1)
run := true
var index int
for run {
for i := 0; i < len(source); i++ {
if string(source[i]) == sep {
index = i
run = true
b... |
// UDP server : 10.100.23.147
// Our pc : 10.100.23.230
package main
import (. "fmt"
"runtime"
"time"
."net"
)
func checkError(err error) {
if err != nil {
Println("Noe gikk galt %v", err)
return
}
}
func read(udp_addr *UDPAddr) {
buffer := make([]byte, 1024)
conn, err := ListenUDP("udp", udp_addr)
c... |
package course
import (
"fmt"
"github.com/manifoldco/promptui"
"github.com/manifoldco/promptui/list"
"github.com/pathbird/pbauthor/internal/graphql"
"github.com/pkg/errors"
"strings"
)
var (
promptCourseTemplate = newSelectTemplate("Course", "🎓", ".Course.Name")
promptCodexCategoryTemplate = newSelect... |
package tusdx_handler
import (
"encoding/base64"
"github.com/tus/tusd"
"net/http"
"strconv"
"strings"
)
var handler *unroutedHandler = nil
// mimeInlineBrowserWhitelist is a map containing MIME types which should be
// allowed to be rendered by browser inline, instead of being forced to be
// dow... |
package employee
import "fmt"
type employee struct {
firstName string
lastName string
totalLeavers int
leaversTaken int
}
func (e *employee) LeavesRemaining() {
fmt.Printf("%s %s has %d leaves remaining", e.firstName, e.lastName, e.totalLeavers - e.leaversTaken)
}
func New(firstName, lastName string, totalLeav... |
package LICY_BLC
import (
"bytes"
"encoding/gob"
"log"
"time"
"crypto/sha256"
"encoding/hex"
"crypto/elliptic"
"math/big"
"crypto/ecdsa"
"crypto/rand"
)
type Licy_Transaction struct {
//1. 交易hash
Licy_TxHash []byte
//2. 输入
Licy_Vins []*Licy_TxInput
//3. 输出
Licy_Vouts []*Licy_TxOutput
}
const miner... |
package fronius
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_Symo_GetPowerFlowData_GivenUrl_WhenRequestData_ThenParseStruct(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(rw http.Respons... |
package security
import ("github.com/robbert229/jwt"
"time")
func CreateJWT(secret string) string {
algorithm := jwt.HmacSha256(secret)
claims := jwt.NewClaim()
claims.Set("Role", "Admin")
claims.SetTime("exp", time.Now().Add(time.Minute))
token, err := algorithm.Encode(claims)
if err != nil {
panic(err)... |
package main
import (
"container/list"
"fmt"
"strconv"
)
type People struct {
Name string
Age int
}
func main() {
// Create a new list and put some numbers in it.
l := list.New()
l.PushBack(People{"zjw", 1})
// Iterate through list and print its contents.
e := l.Front()
p, ok := (e.Value).(People)
if ... |
package main
import (
"fmt"
"github.com/golang/protobuf/proto"
)
type server struct{}
var port = 8080
func main() {
listen, err := net.Listen("tpc", port)
if err != nill {
fmt.Println(err)
return
}
}
|
package basic
import (
"fmt"
"time"
)
func time1() {
datetime := "2015-01-01 00:00:00" //待转化为时间戳的字符串
//日期转化为时间戳
timeLayout := "2006-01-02 15:04:05" //转化所需模板
loc, _ := time.LoadLocation("Local") //获取时区
tmp, _ := time.ParseInLocation(timeLayout, datetime, loc)
timestamp := tmp.Unix() //转化为时间戳 类型是int64
fmt.Pr... |
package walk
import (
"testing"
"gopkg.in/yaml.v2"
"gotest.tools/assert"
)
func TestWalk(t *testing.T) {
// Input yaml
input := `
test:
image: appendtag
test: []
test2:
image: dontreplaceme
test3:
- test4:
test5:
image: replaceme
`
inputObj := make(map[interface{}]interface{})
err := ya... |
package main
import "fmt"
import "math"
var Sum int64 = 0
func main() {
counter := 1
for counter < 2000000 {
if isPrime(counter) {
Sum += int64(counter)
}
counter += 2
}
fmt.Println(Sum + 2)
}
func Sqrt(x float64) float64 {
x = math.Sqrt(x)
return x
}
func isPrime(n int) (isP bool) {
if n == 1 {... |
package bosh
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"net"
"net/http"
yaml "gopkg.in/yaml.v2"
"github.com/cloudfoundry/bosh-bootloader/storage"
"golang.org/x/net/proxy"
)
var proxySOCKS5 func(string, string, *proxy.Auth, proxy.Dialer) (proxy.Dialer, error) = proxy.SOCKS5
type ClientProvider str... |
package util
import (
"bytes"
"encoding/json"
"net/http"
)
var (
TopUpWeChatUrl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?"
)
func InitNotifyWeChatUrl(url string) {
TopUpWeChatUrl = url
}
func NotifyWeChatMarkDown(markdown string) {
p := struct {
Type string `json:"msgtype"`
Markd... |
package main
import (
"fmt"
)
type errortest struct {
lat,long string
err error
}
func (rec *errortest) Error() string{ // Any type with this signature implicitly implements the error interface
return fmt.Sprintf("error occured %v %v %v",rec.lat,rec.long,rec.err)
}
func main() {
_,err:=sqrt(-12)
if er... |
package datastructure
import (
"fmt"
"net/http"
"strings"
"time"
)
// Response is delegated to save the necessary information related to an HTTP call
type Response struct {
Headers map[string]string
Body []byte
StatusCode int
Time time.Duration
Error error
Cookie []*http.Cookie
Resp... |
package main
import (
"fmt"
)
// Interfaces
type CARFACTORY interface {
makeCar() CAR
getMake() string
}
type CAR interface {
getModel() string
}
// 'Class' factories
type CarFactoryCreator func() CARFACTORY
type CarFactoryFactory struct {
m map[string]CarFactoryCreator
}
func NewCarFactoryFactory() *CarFa... |
package main
import (
"fmt"
"github.com/benka-me/laruche/go-pkg/discover"
"github.com/benka-me/users/go-pkg/http/rpc"
"github.com/urfave/cli"
"log"
"os"
)
func main() {
app := cli.NewApp()
app.Commands = cli.Commands{
{
Name: "dev",
Action: func(context *cli.Context) error {
if len(os.Args) < 3 {
... |
// Package main implements a command-line tool, lorica, for operating a
// certification authority.
package main
import (
"fmt"
"io/ioutil"
"os"
"time"
"github.com/cloudflare/cfssl/log"
"github.com/ericyan/lorica/internal/cliutil"
"github.com/ericyan/lorica/pkg/ca"
"github.com/ericyan/lorica/pkg/cryptoki"
"g... |
package pathfileops
import (
"io"
"strings"
"testing"
)
func TestFileMgr_ReadFileString_01(t *testing.T) {
expectedStr := "Now is the time for all good men"
fh := FileHelper{}
setupFileName := "testRead918256.txt"
setupFile := fh.AdjustPathSlash(
"../../filesfortest/checkfiles/" + setupFileName)... |
package 链表
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func isPalindrome(head *ListNode) bool {
if head == nil {
return true
}
leftMiddleNode := getLeftMiddleNode(head)
rightPartList := getReverseList(leftMiddleNode.Next)
return isPrefix(head... |
/*
Copyright Mojing Inc. 2016 All Rights Reserved.
Written by mint.zhao.chiu@gmail.com. github.com: https://www.github.com/mintzhao
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.apa... |
// Longest Common Subsequence
// Dynamic Programming
//
// Time complexity: O(len(str1) * len(str2))
// Space complexity: O(len(str1) * len(str2))
//
// References:
// https://www.geeksforgeeks.org/longest-common-subsequence/
// https://github.com/mission-peace/interview/blob/master/src/com/interview/dynamic/LongestCom... |
package fslm
// Common routines for testing a language model.
import (
"errors"
"strings"
"testing"
)
type ngram struct {
Context, Word string
Weight, BackOff Weight
}
func (n ngram) Params() ([]string, string, Weight, Weight) {
var context []string
if n.Context != "" {
context = strings.Fields(n.Context... |
package Problem0661
func imageSmoother(M [][]int) [][]int {
res := make([][]int, len(M))
for i := range res {
res[i] = make([]int, len(M[0]))
for j := range res[i] {
res[i][j] = getValue(M, i, j)
}
}
return res
}
func getValue(M [][]int, r, c int) int {
value, count := 0, 0
for i := r - 1; i < r+2; i+... |
package network
import (
"testing"
"time"
)
func TestPing(t *testing.T) {
addrs := []string{
"www.google.com",
"cn.bing.com",
"202.182.98.210",
"192.168.101.134",
"127.0.0.1",
}
pongAddrs := Ping(addrs, time.Second*10)
t.Logf("pong addresses: %v\n", pongAddrs)
} |
package libkv
import (
"bytes"
"encoding/json"
validator "gopkg.in/go-playground/validator.v9"
"go.uber.org/zap"
"github.com/serverless/event-gateway/event"
"github.com/serverless/event-gateway/metadata"
"github.com/serverless/libkv/store"
)
// EventTypeKey is a key under which event type data is stored KV ... |
package main
import (
"flag"
"github.com/VertebrateResequencing/wr/kubernetes/client"
"github.com/VertebrateResequencing/wr/kubernetes/deployment"
"github.com/sevlyar/go-daemon"
"log"
"os"
"path/filepath"
"strings"
"syscall"
)
var (
signal = flag.String("s", "", `send signal to the port forwarding daemon
... |
/*
* @lc app=leetcode.cn id=1812 lang=golang
*
* [1812] 判断国际象棋棋盘中一个格子的颜色
*/
// @lc code=start
// package main
//
// import "fmt"
func squareIsWhite(coordinates string) bool {
return (coordinates[0]-'a')%2 != (coordinates[1]-'1')%2
}
// func main() {
// fmt.Println(squareIsWhite("a1"))
// fmt.Println(squareIsWhi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.