text stringlengths 11 4.05M |
|---|
package head
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document00100101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:head.001.001.01 Document"`
Message *BusinessApplicationHeaderV01 `xml:"AppHdr"`
}
func (d *Document00100101) Ad... |
package endpoints
import (
"context"
"testing"
"github.com/giantswarm/apiextensions/pkg/apis/provider/v1alpha1"
"github.com/giantswarm/micrologger/microloggertest"
apiv1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes/fake"
"github.com/giantswarm/aws-operator/client/aws"
"github.com/giantswarm/aws-operator... |
package git
/*
#include <git2.h>
*/
import "C"
type Feature int
const (
// libgit2 was built with threading support
FeatureThreads Feature = C.GIT_FEATURE_THREADS
// libgit2 was built with HTTPS support built-in
FeatureHTTPS Feature = C.GIT_FEATURE_HTTPS
// libgit2 was build with SSH support built-in
Feature... |
package helm
import (
"fmt"
"github.com/spf13/cobra"
"github.com/werf/werf/cmd/werf/common"
"github.com/werf/werf/pkg/git_repo"
"github.com/werf/werf/pkg/git_repo/gitdata"
"github.com/werf/werf/pkg/true_git"
"github.com/werf/werf/pkg/werf"
)
var getReleaseCmdData common.CmdData
func NewGetReleaseCmd() *cobr... |
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type Elm struct {
Node *TreeNode
Depth int
}
// time: O(n), space: O(n)
func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
res := 0
lif... |
package inMemoryDatabase
import (
"goChat/Server/models"
"testing"
)
func TestNewUserRepository(t *testing.T) {
t.Parallel()
repo := getTestUserRepository()
if repo.users == nil {
t.Errorf("user repository map not initialized properly")
}
}
func TestUserRepository_Create(t *testing.T) {
t.Parallel()
repo :... |
package main
func mainqueue() {
}
|
package cos_test
import (
"fmt"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
sut "github.com/rancher-sandbox/ele-testhelpers/vm"
)
var _ = Describe("cOS Deploy tests", func() {
var s *sut.SUT
BeforeEach(func() {
s = sut.NewSUT()
s.EventuallyConnects(360)
})
AfterEach(func() {
// Try to ga... |
package controllers
import "github.com/labstack/echo"
type Response struct {
Success bool `json:"success"`
Payload interface{} `json:"payload"`
}
func HealthCheck(c *echo.Context) error {
c.String(200, "")
return nil
}
type GetData struct {
Data string `json:"data"`
}
func GetA(c *echo.Context) error {... |
package robot
import (
"fmt"
"time"
"github.com/golang/glog"
)
const tout time.Duration = time.Second * 20
func Tick_download_from_sina(id string, t time.Time) []byte {
body, err := Http_get(Tick_sina_url(id, t), nil, tout)
if err != nil {
glog.Warningln(err)
return nil
}
return body
}
func Tick_downlo... |
package main
import "fmt"
var angka = 7
func main() {
if angka%2 == 0 {
fmt.Println("Angka", angka, "adalah angka genap")
} else {
fmt.Println("Angka", angka, "adalah angka ganjil")
}
}
|
package dandandowlonad
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"runtime"
"strings"
"sync"
)
//DanDownload is struct
type DanDownload struct {
urlsfilePath string
}
//NewDanDownload is constracutor
func NewDanDownload(urlfilePath string) *DanDownload {
return &DanDownload{
urlsf... |
package main
import "fmt"
func rob1(nums []int) int {
if len(nums)==0{
return 0
}
//一开始basecase设为-10000 荒谬啦 偷东西还能赔钱哈哈
dp_i__1 := 0
dp_i_0 := 0
for i:=0;i<len(nums);i++{
temp := dp_i_0
dp_i_0 = max213(dp_i_0,dp_i__1+nums[i])
dp_i__1 = temp
}
return dp_i_0
}
func max213(a,b int) int {
if a>b {
ret... |
package main
import (
"fmt"
"github.com/im2kl/ProxyShed/Client/admin"
"github.com/im2kl/ProxyShed/Client/config"
"github.com/im2kl/ProxyShed/Client/scraper"
)
//var RAWProxyList []string
func main() {
config.Init()
x := admin.GetURLList()
s := scraper.Scrape(x)
//y := proxydial.Test()
//f := config.Max... |
package ginhandler
import (
"github.com/gin-gonic/gin"
"github.com/line/line-bot-sdk-go/linebot"
"github.com/line/line-bot-sdk-go/linebot/httphandler"
)
// WebhookHandler is gin wrapper for line-bot-sdk-go/linebot/httphandler.WebhookHandler.
type WebhookHandler struct {
httphandlerWebhookHandler *httphandler.Webh... |
// 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 services
var (
UserSignedInSession = "_user_signed_key_"
UserNameKeyInSession = "_user_name_key"
)
|
package rest
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/pilillo/igovium/cache"
"github.com/pilillo/igovium/utils"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
const (
keyParam = "key"
)
func Get(c *gin.Context) {
key := c.Param(keyParam)
value, response := cacheService.... |
package ua
import (
"reflect"
"strconv"
"testing"
"h12.io/gspec"
"github.com/ogdl/flow"
)
var testcases = []struct {
str string
ua []*Product
}{
{`*Product`, []*Product{
{Name: "*Product"},
}},
{`*Product/1.0`, []*Product{
{Name: "*Product",
Version: Version{
Text: "1.0",
}},
}},
{`()`, []... |
package main
import (
"fmt"
)
func main() {
pFather, pMother := GetProtoParents()
PrintPerson(pFather)
PrintPerson(pMother)
for i := 0; i < 10; i++ {
if child, chldErr := Procreate(fmt.Sprintf("Child %v", i+1), pFather, pMother); chldErr == nil {
PrintPerson(child)
} else {
fmt.Printf("----------\n")... |
// Tideland Go Application Support - Identifier
//
// Copyright (C) 2009-2014 Frank Mueller / Tideland / Oldenburg / Germany
//
// All rights reserved. Use of this source code is governed
// by the new BSD license.
package identifier
//--------------------
// IMPORTS
//--------------------
import (
"bytes"
"crypto... |
// Copyright 2019 The Dice Authors. 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by app... |
package db
import (
"github.com/gin-gonic/gin"
"urlshortener.api/models"
)
// DataAccessLayer provides thread-safe access to a database of urlshortens.
type DataAccessLayer interface {
// Fetch retrieves a urlshorten metadata by its ShortURL.
Fetch(ctx *gin.Context, shortURL string) (*models.URLShorten, error)
... |
package util
import (
"io/ioutil"
"strings"
)
func LoadTokens(path string) ([]string, error) {
tokens, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
return strings.Split(string(tokens), "\n"), nil
}
|
package main
//unbuffered channel must be woken up by putting it another Goroutine. REMEMBER that main itself is already a Goroutine.
//buffered channel can work directly from the main function without creating any other Goroutine. But its size is limited.
// func main() {
// mess := make(chan string)
// doneChan :=... |
// license that can be found in the LICENSE file.
//go:build !race
// +build !race
package integration
import (
"fmt"
"os"
"os/exec"
"testing"
"time"
"github.com/u-root/u-root/pkg/qemu"
"github.com/u-root/u-root/pkg/vmtest"
)
var expectString = map[string]string{
"Arch": "TODO_PLEASE_SET_EXPECT_STRIN... |
package fileupload
import (
"fmt"
"os"
"path"
"github.com/majid-cj/go-docker-mongo/util"
"github.com/twinj/uuid"
)
// FormatFile ...
func FormatFile(filepath string) string {
ext := path.Ext(filepath)
return fmt.Sprintf("%s-%s%s", util.GetTimeNow().Format(os.Getenv("TIME_FORMATE")), uuid.NewV4().String(), e... |
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
"strings"
"unicode/utf8"
)
// buildBalloon takes a slice of strings of max width maxwidth
// prepends/appends margins on first and last line, and at start/end of each line
// and returns a string with the contents of the balloon
func buildBalloon(lines []str... |
package basics
import (
"io/fs"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"testing"
"github.com/rogpeppe/go-internal/testscript"
"golang.org/x/tools/txtar"
"cuelang.org/go/cmd/cue/cmd"
"cuelang.org/go/cue/parser"
"cuelang.org/go/internal/cuetest"
)
// TestLatest checks that the examples match the l... |
package compute
import (
"encoding/json"
"encoding/xml"
"fmt"
"net/http"
"net/url"
)
// Server represents a virtual machine.
type Server struct {
ID string `json:"id"`
Name string `json:"name"`
Description string ... |
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
cli "github.com/codegangsta/cli"
)
var infolog, errlog *log.Logger
var port, db string
var proxyList = make(map[string]*LogProxy)
type Command struct {
Type string `json:"type"` //add, remove, list
Node string `json... |
///usr/bin/env go run -ldflags "-X main.Version=shell.run" $0 "$@"; exit
package main
import (
"trident.li/pitchfork/cmd/server"
tf "trident.li/trident/src/lib"
tu "trident.li/trident/src/ui"
)
var Version = "unconfigured"
func main() {
pf_cmd_server.Serve("trident", "Trident", Version, tf.Copyright, tf.Website... |
// Package client manages all requests made to reddit.
package client
import (
"io"
"net/http"
"time"
)
// Client implementations make requests.
type Client interface {
// Do executes a request to reddit and returns the response body.
Do(r *http.Request) (io.ReadCloser, error)
}
// New returns a new Client from... |
package repository
import (
"github.com/taniwhy/mochi-match-rest/domain/models"
)
// RoomBlacklistRepository : ユーザーのリポジトリ
type RoomBlacklistRepository interface {
FindAllBlacklist() ([]*models.RoomBlacklist, error)
FindBlacklistByID(id int64) (*models.RoomBlacklist, error)
InsertBlacklist(room *models.RoomBlackli... |
package oauth2_test
import (
"context"
"github.com/tsingsun/go-oauth2"
"io/ioutil"
"time"
)
var (
defaultService *oauth2.Service
)
const (
ENCRYPTION_KEY = "cxPrjjamV6wI82ka"
PRIVATE_KEY = "./_example/rsa_auth_pkcs8.pem"
)
type Client struct {
oauth2.ClientEntity
}
type ClientRepository struct {
oauth2... |
package stack
type Data interface{}
type Stack struct {
data []Data
}
func (s *Stack) Push(value Data) {
s.data = append(s.data, value)
}
func (s *Stack) IsEmpty() bool {
return len(s.data) == 0
}
func (s *Stack) Top() Data {
if s.IsEmpty() {
return -1
}
return s.data[len(s.data)-1]
}
func (s *Stack) Pop(... |
package middlewares
import (
"github.com/gin-gonic/gin"
"golang-rest/utils"
"net/http"
"strings"
)
func Authorization() gin.HandlerFunc {
return func(c *gin.Context) {
// extract authorization header
headerString := c.GetHeader("Authorization")
// if there is not authorization header, throw error.
if l... |
package main
import "fmt"
type salary interface{
calculateSalary() float64
calculateTax() float64
}
type employee struct{
perDayIncome float64
}
type manager struct{
perDayIncome float64
incentive int
}
// func (e employee) calculateSalary() float64{ error
func (e employee) calculateSalary() float64{
retur... |
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/guregu/dynamo"
)
const workers = 3
func main() {
db := dynamo.New(session.New(), &aws.Config{
Region: a... |
package main
import (
"fmt"
"sort"
)
type HeroKind int
const (
None HeroKind = iota
Tank
Assassin
Mage
)
type Hero struct {
Name string
Kind HeroKind
}
type Heros []*Hero
// 实现sort.Interface 接口比较元素方法
//func (s Heros) Len() int {
// return len(s)
//}
//
//func (s Heros) Less(i, j int) bool {
// if s[i].Ki... |
package cfrida
func Frida_crash_get_pid(obj uintptr) uint {
r, _, _ := frida_crash_get_pid.Call(obj)
return uint(r)
}
func Frida_crash_get_process_name(obj uintptr) string {
r, _, _ := frida_crash_get_process_name.Call(obj)
return CStrToGoStr(r)
}
func Frida_crash_get_summary(obj uintptr) string {
r, _, _ := fr... |
package globals
import (
"fmt"
"github.com/jmoiron/sqlx"
)
type globals struct {
Db *sqlx.DB
}
var G *globals
func Setup() *globals {
defer func() {
if r := recover(); r != nil {
fmt.Printf("Puts.\n")
}
}()
G = new(globals)
G.Db = setupDb()
return G
}
func Close(g *globals) {
closeDb(g.Db)
}
|
package core
import (
"io"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/textileio/go-textile/pb"
)
// getThreadsObserve godoc
// @Summary Observe to thread updates
// @Description Observes updates in a thread or all threads. An update is generated
// @Description when a new block is added to a th... |
package handlers
import (
p "git.benfleming.nz/benfleming/gotasks/app/policies"
"git.benfleming.nz/benfleming/gotasks/app/models"
"github.com/jinzhu/gorm"
"github.com/labstack/echo/v4"
)
// var (
// errUnauthorized = errors.New("unauthorized, you cannot access this user")
// errNotImplemented = errors.New("no... |
package server
import (
"net/http"
"path/filepath"
"strings"
"github.com/dimfeld/httptreemux"
"github.com/rkuris/journey/filenames"
"github.com/rkuris/journey/helpers"
)
func pagesHandler(w http.ResponseWriter, r *http.Request, params map[string]string) {
path := filepath.Join(filenames.PagesFilepath, params[... |
package migration
import (
"errors"
"sort"
"github.com/btcsuite/btcwallet/walletdb"
)
var (
// ErrReversion is an error returned when an attempt to revert to a
// previous version is detected. This is done to provide safety to users
// as some upgrades may not be backwards-compatible.
ErrReversion = errors.Ne... |
package graph
import (
"algorithms/queue"
"algorithms/utils"
"errors"
"sort"
)
// 无权图最短路径
type shortestpath struct {
graph I // 图
source int // 根节点
visited []bool // 节点i是否被访问过
from []int // 记录从哪个节点过来 from[i]=v : i节点是从v节点访问过来
ord []int // 从source到每个节点的最短距离
}
func NewShortestPath(graph I,... |
package smsgate
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strconv"
"time"
)
// APIv4Preferences sets up HTTP and retry scheme
type APIv4Preferences struct {
HTTPClient *http.Client
RetryPeriod time.Duration
MaxRetries int
SubmitURL string
}
// DefaultAPIv4Preferences are de... |
package common
import (
"fmt"
"github.com/thoj/go-ircevent"
)
type Bot struct {
serverAddress string
botNickname string
channels []string
irc *irc.Connection
modules []BotEventer
Owner string
}
func BOT(server, nick, owner string, channels []string) *Bot {
if len(server) == 0 {
ret... |
// Defines interfaces and structures controlling the proxy configuration and changes
package backend
import (
"fmt"
"github.com/mailgun/vulcan/limit"
"strings"
"time"
)
type Backend interface {
GetHosts() ([]*Host, error)
AddHost(name string) error
DeleteHost(name string) error
AddLocation(hostname, id, pat... |
package main
import (
"fmt"
"os"
"github.com/therecipe/qt/core"
"github.com/therecipe/qt/qml"
"github.com/therecipe/qt/quick"
"github.com/therecipe/qt/widgets"
)
//this example demonstrates one possible way to deal with qml errors/warnings
//therefore the qml file does contain errors and will NOT ... |
// Copyright 2015 The Sporting Exchange Limited. All rights reserved.
// Use of this source code is governed by a free license that can be
// found in the LICENSE file.
// tsp-aggregator combines many host feeds into a single site feed.
package main
import (
"log"
"os"
_ "opentsp.org/internal/pprof"
"opentsp.or... |
package main
import "fmt"
// 167. 两数之和 II - 输入有序数组
// 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
// 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
// 说明:
// 返回的下标值(index1 和 index2)不是从零开始的。
// 你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
// https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/
func main() {... |
package main
import (
"errors"
"html/template"
"io/ioutil"
"net/http"
"os"
"regexp"
"time"
)
/*
Page is a struct that defining the data structures for our wiki.Page struct
has two fields title and body. The body element is a byte slice
rather then a string becuase that is the type expected by the
io libraries.... |
package main
type Worker struct {
task string
time int
done bool
}
func InitWorker() Worker {
return Worker{"", 0, false}
}
func (w *Worker) SetTask(task string) {
w.task = task
w.time = int(task[0] - 4)
w.done = false
}
func (w *Worker) IsBusy() bool {
return w.time > 0
}
func (w *Worker) NextTimeStep(ste... |
// https://www.hackerrank.com/challenges/stockmax
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main() {
var t int
_, err := fmt.Scan(&t)
if err == nil {
scanner := bufio.NewScanner(os.Stdin)
scanner.Split(bufio.ScanWords)
testCases := make([][]int, t)
for i := 0; i < t; i++ {
if scanner... |
// +build darwin linux
package portablemmap
import (
"os"
"reflect"
"syscall"
"unsafe"
)
func Prefault(mmappedData []byte) {
// Prefaults mmaped file so it is preloaded in the filesystem cache.
// Note that you should *NOT* call this if the CDB file is bigger than
// the available physical memory.
sliceHeade... |
/*
Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string (i.e. n will be in the range 0..len(str)-1 inclusive).
*/
package main
import (
"fmt"
"strings"
)
func missing_char(str string, n int) strin... |
package tokens
import (
"github.com/pkg/errors"
"github.com/kumahq/kuma/pkg/api-server/authn"
config_access "github.com/kumahq/kuma/pkg/config/access"
"github.com/kumahq/kuma/pkg/core/plugins"
"github.com/kumahq/kuma/pkg/plugins/authn/api-server/tokens/access"
"github.com/kumahq/kuma/pkg/plugins/authn/api-serve... |
package main
import (
cfg "laravel-go/config"
"laravel-go/pkg/config"
"laravel-go/pkg/http"
"laravel-go/pkg/orm"
)
// API 引导入口
func main() {
initConfig()
initDB()
initHTTP()
}
// 加载配置文件
func initConfig() {
config.LoadConfig(".env", "env")
}
// 配置数据库
func initDB() {
dbConf := cfg.NewDBConfig()
// 设置默认数据库连... |
// 思路:从第二个元素开始,向两边扩散,寻找以他为中心的回文串。
func LongestPalindrome(s string) string {
ln := len(s)
if ln == 0 {
return ""
}
start, end := 0, 0
for i := 0; i < ln; i++ {
s1, e1 := findPalindrome(s, i, i) // s长度为奇数
s2, e2 := findPalindrome(s, i, i+1) // s长度为偶数
if e1-s1 > end-start {
start, end = s1, e1
}
if... |
// Package engine - пакет поискового движка
package engine
import (
"encoding/json"
"errors"
"go.core/lesson6/pkg/cache"
"go.core/lesson6/pkg/crawler"
"go.core/lesson6/pkg/index"
"go.core/lesson6/pkg/storage"
)
type Engine struct {
Index index.Service
Storage storage.Storager
Cache cache.SaveLoader
}
// ... |
package migemo_test
import (
"testing"
"unicode/utf16"
"github.com/oguna/gomigemo-experiments-2020/migemo"
)
func TestPatriciaTrie_Lookup(t *testing.T) {
words := []string{"baby", "bad", "bank", "box", "dad", "dance"}
keys := make([][]uint16, len(words))
for i := 0; i < len(words); i++ {
keys[i] = utf16.Enco... |
package ping
import (
"sync"
"testing"
"github.com/zairza-cetb/bench-routes/src/lib/utils"
"github.com/zairza-cetb/bench-routes/src/lib/utils/parser"
"github.com/zairza-cetb/bench-routes/tsdb"
"github.com/zairza-cetb/bench-routes/src/lib/filters"
)
var (
urls = []string{
"google.co.in",
"facebook.com",
... |
package merchant
import (
"context"
"strings"
"tpay_backend/adminapi/internal/common"
"tpay_backend/model"
"tpay_backend/adminapi/internal/svc"
"tpay_backend/adminapi/internal/types"
"github.com/tal-tech/go-zero/core/logx"
)
type GetMerchantChannelListLogic struct {
logx.Logger
ctx context.Context
svcC... |
/*
* @lc app=leetcode.cn id=110 lang=golang
*
* [110] 平衡二叉树
*/
// @lc code=start
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
package main
import "fmt"
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNo... |
/*
Inspired by a recent Daily WTF article...
Write a program or function that takes a GUID (string in the format XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, where each X represents a hexadecimal digit), and outputs the GUID incremented by one.
Examples
>>> increment_guid('7f128bd4-b0ba-4597-8f35-3a2f2756dfbb')
'7f128bd4-... |
package actuator
import "math"
import "time"
import "logging"
import "sensor"
import "actuator/writer"
/* Actuator:
* - Determines the appropriate amount of actuation depending on
* sampled values
* - Smoothes change / applies change over time
*/
type Actuator struct {
id string
actuationCurve C... |
package geom
import "math"
// Mat4 is 4x4 matrix
type Mat4 [16]float32
var ident4 = Mat4{
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1,
}
// Mat4Ident return identity
func Mat4Ident() Mat4 {
return ident4
}
// Mult calculate a * b
func (a Mat4) Mult(b Mat4) (c Mat4) {
c[0] = a[0]*b[0] + a[4]*b[1] + a[8]*b... |
/*
It is a sweltering summer day, and a boy wants to buy some ice cream bars.
At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as pos... |
package main
import (
"fmt"
"image"
"log"
"strconv"
"fyne.io/fyne/dialog"
"fyne.io/fyne/theme"
"fyne.io/fyne/widget"
_calc "github.com/GrigoryKrasnochub/go-simple-chart-project/calc"
"github.com/GrigoryKrasnochub/go-simple-chart-project/calc/poledata"
"github.com/GrigoryKrasnochub/go-simple-chart-project/ch... |
package api
/* Server version range with which this version of the tool is compatible. */
var Version string = "^6.0.0"
|
package piscine
func AppendRange(min, max int) []int {
var ints []int
if min >= max {
return ints
}
for j := min; j < max; j++ {
ints = append(ints, j)
}
return ints
}
|
package compactor
import (
"github.com/stretchr/testify/require"
"testing"
)
func TestSnappy(t *testing.T) {
snappy := NewSnappy()
tstr := "some boy like me"
eb, err := snappy.Encode([]byte(tstr))
require.Nil(t, err)
db, err := snappy.Decode(eb)
require.Nil(t, err)
require.Equal(t, tstr, string(db))
}
|
package instanceid
import (
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/argoproj/argo/util/labels"
"github.com/argoproj/argo/workflow/common"
)
type Service interface {
Label(obj metav1.Object)
With(options *metav1.ListOptions)
Validate(obj metav1.Object) error
InstanceID() string
}
fun... |
package fastsort
import (
"testing"
. "leetcode_notes/utils/array"
)
func TestArrayFastSort1(t *testing.T) {
if ret := ArrayFastSort1([]int{2, 3, 4, 1, 0, 7}); !IsIntArrayEqual(ret, []int{0, 1, 2, 3, 4, 7}) {
t.Errorf("Test1 error with return: %v", ret)
}
}
func TestArrayFastSort2(t *testing.T) {
if ret := A... |
package main
import (
"fmt"
)
func main() {
var array [3]string
array[0] = "hola"
array[1] = "mundo"
array[2] = "!"
fmt.Println(array)
array2 := []string{"hola", "mundo", "!"}
fmt.Println(array2)
array2 = append(array2, "!")
fmt.Println(array2)
fmt.Println(array2[0:1])
}
|
package common
import (
"github.com/mojocn/base64Captcha"
)
type GenerateCodeCaptchaBody struct {
Id string
B64s string
}
type VerifyCaptchaBody struct {
Id string
VerifyValue string
}
var store = base64Captcha.DefaultMemStore
// 生成验证码
func GenerateCaptchaCode() (captchaCode *GenerateCodeCaptchaBody,err error... |
package app
import (
"fmt"
"net/http"
"sync/atomic"
"go.uber.org/zap"
"gorm.io/gorm"
"github.com/silverspase/todo/internal/app/repository/sql"
"github.com/silverspase/todo/internal/config"
appLogger "github.com/silverspase/todo/internal/logger"
"github.com/silverspase/todo/internal/modules/auth"
authMemory... |
package queue
import (
"goqueue/pkg/task"
)
// QueueTasks is a queue of tasks
type QueueTasks struct {
// The specification clearly says: "Channels act as first-in-first-out queues"
jobs chan task.ITask
}
// New returns QueueTasks object, takes writers count to create a buffered channel (more efficient)
func New(... |
package main
import (
"bytes"
"io"
"os"
"testing"
)
func TestEmit(t *testing.T) {
var buf = []byte("hello\nthis is a test\n")
var buf2 = []byte("hello\nthiz is a text")
c1 := make(chan byte, 8192)
c2 := make(chan byte, 8192)
c3 := make(chan byte, 8192)
r := bytes.NewReader(buf)
err := emit(r, c1, 0)
if... |
package build
import (
"context"
"fmt"
"path/filepath"
"runtime"
"testing"
"github.com/gobuffalo/plugins"
"github.com/stretchr/testify/require"
)
func Test_Cmd_Main(t *testing.T) {
r := require.New(t)
bc := &Cmd{}
bn := filepath.Join("bin", "build")
if runtime.GOOS == "windows" {
bn += ".exe"
}
exp ... |
package main
import (
"fmt"
"math"
)
func main() {
// test
var (
a1 int = -591681
b1 int = 591681
)
fmt.Printf("%d + %d = %d\t", a1, b1, Add(a1, b1))
fmt.Printf("check answer: %d\n", a1+b1)
var (
a2 int = 59666
b2 int = 59060
)
fmt.Printf("%d - %d = %d\t", a2, b2, Minus(a2, b2))
fmt.Printf("check ... |
package main
import (
"fmt"
"math"
)
func f(x float64) float64 {
return math.Sin(x)
}
//Метод секущих
func sek() {
var a, b, eps float64
a, b, eps = 2, 4, 0.0001
//fmt.Println("Введите границы отрезка:")
//fmt.Scan(&a, &b)
a, b = math.Min(a, b), math.Max(a, b)
//fmt.Println("Введите погрешность:")
//fmt.S... |
package harmonograph
import (
"image/color"
"math"
"math/rand"
"github.com/devinmcgloin/sail/pkg/canvas"
"github.com/devinmcgloin/sail/pkg/slog"
"github.com/fogleman/gg"
)
type Single struct{}
func (v Single) Dimensions() (int, int) {
return 1400, 2000
}
func (v Single) Draw(context *gg.Context, rand *rand.... |
package conf
import (
"os"
"strings"
)
type envEvaluator struct {
}
var _ EvaluatorFunction = (*envEvaluator)(nil)
func (e *envEvaluator) GetFunctionName() string {
return "env"
}
func (e *envEvaluator) Eval(params []string, def interface{}) interface{} {
if len(params) > 0 {
envVal := os.Getenv(params[0])
... |
package controllers
import (
"encoding/json"
"github.com/astaxie/beego/orm"
"time"
"tokensky_bg_admin/common"
"tokensky_bg_admin/conf"
"tokensky_bg_admin/enums"
"tokensky_bg_admin/models"
"tokensky_bg_admin/utils"
)
//OtcAppealController OTC-申诉表
type OtcAppealController struct {
BaseController
}
//Prepare 参... |
package model
type Grupo struct {
BaseModel
Nome string `json:"nome"`
} |
// 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 fcgi
import (
"io"
"os"
"path"
"strconv"
"syscall"
)
// dialExec will ForkExec a new process, and returns a wsConn that connects to its
// stdin
func dialExec(binpath string) (io.ReadWriteCloser, os.Error) {
listenBacklog := 1024
dir, file := path.Split(binpath)
socketPath := "/tmp/" + file + ".sock"
... |
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
"time"
)
//https://mp.weixin.qq.com/s/m7uMwiWK_b7oudXueUcSjA
//1 数据传递:
//有 4 个 goroutine,编号为 1、2、3、4。每秒钟会有一个 goroutine 打印出它自己的编号,要求你编写程序,
//让输出的编号总是按照 1、2、3、4、1、2、3、4……这个顺序打印出来。
func startTask() {
n := 4
chans := []chan struct{}{}
for i := 0; i < n; i++ ... |
package main
import "fmt"
// 841. 钥匙和房间
// 有 N 个房间,开始时你位于 0 号房间。每个房间有不同的号码:0,1,2,...,N-1,并且房间里可能有一些钥匙能使你进入下一个房间。
// 在形式上,对于每个房间 i 都有一个钥匙列表 rooms[i],每个钥匙 rooms[i][j] 由 [0,1,...,N-1] 中的一个整数表示,其中 N = rooms.length。 钥匙 rooms[i][j] = v 可以打开编号为 v 的房间。
// 最初,除 0 号房间外的其余所有房间都被锁住。
// 你可以自由地在房间之间来回走动。
// 如果能进入每个房间返回 true,否则返回 f... |
package spec
import (
"encoding/json"
"fmt"
"os"
"gopkg.in/yaml.v3"
)
// Config has the specifications for mock server configurations.
type Config struct {
HTTPPort uint16 `json:"httpPort" yaml:"http_port"`
HTTPSPort uint16 `json:"httpsPort" yaml:"https_port"`
}
// Spec has all the specifications.
type Spec ... |
package usecase
import (
"fmt"
"github.com/Khigashiguchi/khigashiguchi.com/api/domain/entity"
"github.com/Khigashiguchi/khigashiguchi.com/api/infrastructure/logger"
"github.com/Khigashiguchi/khigashiguchi.com/api/infrastructure/repository"
)
// GetEntriesUseCaseImpl represents the interface of use case "get entr... |
package main
import "fmt"
func deferDemo1(){
// 1) Some usefull stuff
// 2) Then defers in the reversed order
defer fmt.Println("second - counting function running time")
defer fmt.Println("first - closing a file")
fmt.Println("Some usefull stuff being done here...")
}
func deferDemo2(){
// """1) Second defer... |
package timed_task
import (
"Open_IM/pkg/common/db"
"time"
)
func (t *TimeTask) timedDeleteUserChat() {
now := time.Now()
next := now.Add(time.Hour * 24)
next = time.Date(next.Year(), next.Month(), next.Day(), 0, 0, 0, 0, next.Location())
tm := time.NewTimer(next.Sub(now))
<-tm.C
count, _ := db.DB.MgoUserCo... |
package auth
import (
"errors"
"fmt"
"strconv"
"github.com/uhppoted/uhppoted-lib/kvs"
"github.com/uhppoted/uhppoted-mqtt/log"
)
type Nonce struct {
ignore bool
mqttd struct {
*kvs.KeyValueStore
filepath string
}
counters struct {
*kvs.KeyValueStore
filepath string
}
}
func NewNonce(verify bool, s... |
package robotmsg
import (
"database/sql"
"fmt"
"github.com/grearter/rpa-agent/api"
_ "github.com/mattn/go-sqlite3"
"github.com/sirupsen/logrus"
"reflect"
"strings"
)
var (
sqliteDB *sql.DB
tableName = "robot_message"
)
// InitDB 初始化Table
func InitDB(dbFile string) (err error) {
db, err := sql.Open("sqlite... |
package spec
import (
"fmt"
"reflect"
"regexp"
"github.com/michaelawyu/cloudevents-generator/src/logger"
)
func checkReqAttrs(event *Event, name string) {
for k, v := range defaultAttrs {
_, ok := event.Attributes[k]
if !ok {
logger.Logger.Warn(fmt.Sprintf("required attribute %s from event %s is missing.... |
package main
import (
"fmt"
)
func main() {
// declaration
a := 10
b := 10.
c := "Olá, bom dia"
x, y, z := 1, 2 != 2, 3 == 3
fmt.Printf("a: %v, %T\n", a, a)
fmt.Printf("b: %v, %T\n", b, b)
fmt.Printf("c: %v, %T\n", c, c)
fmt.Printf("x: %v, %T\n", x, x)
fmt.Printf("y: %v, %T\n", y, y)
fmt.Printf("z: %v, %... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.