text stringlengths 11 4.05M |
|---|
package shutil
import (
"io/ioutil"
"os"
"path"
"testing"
)
func TestMoveCrossDomain(t *testing.T) {
var (
err error
)
homeDir := os.Getenv("OTHER_DRIVE")
if homeDir == "" {
t.Skipf("OTHER_DRIVE env not set")
}
tmpDir, err := ioutil.TempDir("", "shutil-test")
if err != nil {
t.Fatalf("could not creat... |
/*
Farmer Feb has three fields with potatoes planted in them. He harvested x potatoes from the first field, y potatoes from the second field and is yet to harvest potatoes from the third field.
Feb is very superstitious and believes that if the sum of potatoes he harvests from the three fields is a prime number (http:... |
package kata
import (
"fmt"
"testing"
)
// digPow(89, 1) should return 1 since 8¹ + 9² = 89 = 89 * 1
// digPow(92, 1) should return -1 since there is no k such as 9¹ + 2² equals 92 * k
// digPow(695, 2) should return 2 since 6² + 9³ + 5⁴= 1390 = 695 * 2
// digPow(46288, 3) should return 51 since 4³ + 6⁴+ 2⁵ + 8⁶ + ... |
package subscription_test
import (
"context"
"errors"
"testing"
"time"
"github.com/imrenagi/go-payment/invoice"
"github.com/imrenagi/go-payment"
. "github.com/imrenagi/go-payment/subscription"
sm "github.com/imrenagi/go-payment/subscription/mocks"
"github.com/stretchr/testify/assert"
"github.com/stretchr/... |
// Copyright (C) 2015 Nippon Telegraph and Telephone Corporation.
//
// 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... |
/*
Copyright AppsCode 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 applicable law or agreed to in writing... |
package carbon2
import (
"bytes"
"fmt"
"strconv"
"strings"
"github.com/influxdata/telegraf"
)
type format string
const (
Carbon2FormatFieldSeparate string = "field_separate"
Carbon2FormatMetricIncludesField string = "metric_includes_field"
formatFieldSeparate = format(Carbon2FormatFieldSeparate... |
package bot
import (
"os"
"github.com/sad0vnikov/wundergram/bot/dialog"
"github.com/sad0vnikov/wundergram/logger"
"gopkg.in/telegram-bot-api.v4"
)
var dialogTreeProcessor dialog.Processor
//Bot is a struct representing Bot state
type Bot struct {
API *tgbotapi.BotAPI
}
//Create returns a new Bot
func Create(t... |
package main
import (
"log"
"net"
"github.com/pietern/pductl/watchdog"
)
// Monitor wraps a watchdog and kicks it when it receives a packet on
// a UDP socket that it listens on.
type Monitor struct {
*watchdog.Watchdog
}
func NewMonitor(outlet Outlet) (*Monitor, error) {
addr, err := net.ResolveUDPAddr("udp",... |
package http
import (
"net/http"
"github.com/b2wdigital/goignite/pkg/config"
)
// NewServer returns a pointer with new Server
func NewServer(handler http.Handler) *http.Server {
return &http.Server{
Addr: config.String(ServerAddress),
Handler: handler,
MaxHeaderBytes: config.Int(Ma... |
package pulsar
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/apache/pulsar-client-go/pulsar"
"github.com/pkg/errors"
uuid "github.com/satori/go.uuid"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"github.com/batchcorp/plumber-schemas/build/go/protos/records"
"github.com/batchcor... |
// CLI to convert CM to Feet & Inches. sample usage: go run 09_distange.go 48
package main
import (
"os"
"fmt"
"strconv"
)
type Inch float64
type Centimetre float64
func(i Inch) String() string {
inches := uint(i) % 12
feet := (uint(i) - inches) / 12
if feet > 0 {
return fmt.Sprintf("%d'%d\"", feet, ... |
package analyser
import (
"bytes"
"errors"
"htmlparser/models"
"io"
"strconv"
"strings"
"golang.org/x/net/html"
"fmt"
)
func ParseSparkDashboard(content string) (*models.Report, error) {
doc, _ := html.Parse(strings.NewReader(content))
table, err := FindTagWithId(doc, "table", "completed-batches-table")
i... |
package kafka
import (
"github.com/anchorfree/data-go/pkg/promutils"
"github.com/prometheus/client_golang/prometheus"
"github.com/valyala/fastjson"
)
var (
rdHistoMetrics = []string{"min", "max", "avg", "p50", "p95", "p99"}
rdGlobalMetrics = []string{"replyq", "msg_cnt", "msg_size", "tx", "tx_bytes", ... |
func intersect(nums1 []int, nums2 []int) []int {
sort.Ints(nums1)
sort.Ints(nums2)
p1 := 0
p2 := 0
res := []int{}
for p1 < len(nums1) && p2 < len(nums2) {
n1 := nums1[p1]
n2 := nums2[p2]
if n1 == n2 {
res = append(res, n1)
p1 += 1
p2 +=... |
package wx
type WxpayReq struct {
Appid string `xml:"appid"`
BankType string `xml:"bank_type"`
CashFee string `xml:"cash_fee"`
FeeType string `xml:"fee_type"`
IsSubscribe string `xml:"is_subscribe"`
MchId string `xml:"mch_id"`
NonceStr string `xml:"nonce_str"`
Openid ... |
/*
Tencent is pleased to support the open source community by making Basic Service Configuration Platform available.
Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except
in compliance with the License. You may obtain... |
package middleware
import (
log "github.com/best-expendables/logger"
"bytes"
"context"
"io/ioutil"
"net/http"
)
// loggable structure helper
type logger struct {
logger log.Entry
}
// get context-dependent logger.
// If logger not presented into context then returns "base" logger from property.
func (l *logger... |
// Copyright 2018 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... |
// Copyright 2020 MongoDB 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... |
package main
import (
"compress/gzip"
"fmt"
"io"
"math"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
func TestCLIDownloadServer(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "CLI Download server")
}
var _ = Describe("Tes... |
package main
import (
"net/http"
"github.com/gorilla/mux"
"html/template"
)
var templates *template.Template
func main() {
templates = template.Must(template.ParseGlob("templates/*.html"))
r := mux.NewRouter()
r.HandleFunc("/", handler).Methods("GET")
http.Handle("/", r)
http.ListenAndServe(":8000", nil)
}
... |
// Copyright 2015 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package main
import (
"testing"
"github.com/GoogleCloudPlatform/golang-samples/internal/testutil"
)
func TestListBuckets(t *testing.T) {
tc := testutil.Sys... |
package expsocket
import (
"fmt"
"golang.org/x/net/websocket"
"html/template"
"log"
"net/http"
"strings"
)
const host = ":8080"
type message struct {
Text string `json:"text"`
Author string `json:"author"`
}
var (
connections = make(map[*websocket.Conn]bool)
broadcast = make(chan *message)
)
func Serv... |
package types
type User struct {
Username string `json:"username"`
Password string `json:"passwd"`
Active bool `json:"active"`
}
|
// Copyright (c) 2018-2020 The qitmeer developers
// Copyright (c) 2013-2017 The btcsuite developers
// Copyright (c) 2015-2016 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package wallet
import (
"encoding/json"
"errors"
"fmt"
"github.com... |
package cmd
import (
"log"
"github.com/grrtrr/exit"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
func init() {
var (
nic = &cobra.Command{ // Top-level NIC command
Use: "nic",
Short: "Manage server NICs",
Long: "Add or remove server secondary network interface",
PersistentPreRunE: func(cm... |
package main
import (
"database/sql"
_ "github.com/lib/pq"
"os"
)
var db *sql.DB
func init(){
var err error
db, err = sql.Open("postgres", os.Getenv("DATABASE_URL"))
if err != nil{
panic(err)
}
}
func retrieveAll()(users []User, err error){
rows, err := db.Query("SELECT id, name, is_paid FROM users")
if e... |
package resolver
import (
"github.com/dalloriam/synthia/core"
"github.com/dalloriam/websynth/app/audio"
)
type KnobResolver struct {
sys *audio.System
knob *core.Knob
}
func (r *KnobResolver) Value() float64 {
return r.knob.GetValue()
}
func (r *KnobResolver) Set(args struct{ Value float64 }) float64 {
r.kno... |
package main
import "fmt"
func main() {
age := 56
fmt.Printf("%T", age)
}
|
package main
import (
"github.com/fsouza/go-dockerclient"
"github.com/codegangsta/cli"
"github.com/mcuadros/go-version"
"log"
)
func doNetworks(c *cli.Context) {
client, err := docker.NewClient(c.GlobalString("endpoint"))
if err != nil {
log.Fatal(err)
}
ver, err := client.Version()
if version.Compare(ver... |
package bucket
import "testing"
const (
BucketSize = 5
BucketListSize = 5
MaxIdxProduct = 5
)
var myBucket = New(BucketSize, BucketListSize, MaxIdxProduct)
func BenchmarkBucket_ReceiveOrderSlow(b *testing.B) {
b.ResetTimer()
b.StartTimer()
for i := 0; i < b.N; i++ {
myBucket.ReceiveOrderSlow(1, 2, 3, 4... |
// Copyright 2020 MongoDB 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... |
package main
import (
"github.com/redisTesting/deployment/analysis"
cfg "github.com/redisTesting/internal/config"
"github.com/redisTesting/roles/client"
"os"
)
func main() {
// Remove logs
err := os.RemoveAll(cfg.Conf.LogDir)
if err != nil {
panic(err)
}
// Run n clients
client.StartNClients(cfg.Conf.NC... |
package main
import "fmt"
var rows,cols,blocks []map[uint8]bool
type Node struct{
x,y int
}
func solveSudoku(board [][]byte) {
rows = make([]map[uint8]bool,9)
cols = make([]map[uint8]bool,9)
blocks = make([]map[uint8]bool,9)
for i:=0;i<9;i++{
rows[i] = make(map[uint8]bool)
cols[i] = make(map[uint8]bool)
... |
package rogue
import (
"fmt"
"log"
// "time"
"github.com/I82Much/rogue/combat"
"github.com/I82Much/rogue/dungeon"
"github.com/I82Much/rogue/gameover"
"github.com/I82Much/rogue/monster"
"github.com/I82Much/rogue/player"
"github.com/I82Much/rogue/stats"
"github.com/I82Much/rogue/title"
)
type Game struct {
... |
package main
import ("encoding/json"; "fmt"; "os" )
type Person struct {
Name Name
Email []Email
}
type Name struct {
First string
Last string
}
type Email struct {
Kind
string
Address string
}
func main() {
person := Person{
Name: Name{First: "Ууганбаяр", Last: "Сүхбаатар"},
Emai... |
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"strings"
)
func main() {
var b bytes.Buffer // A Buffer needs no initialization.
b.Write([]byte("Hello "))
fmt.Fprintf(&b, "world!\n")
_, _ = b.WriteTo(os.Stdout)
fmt.Printf("'%s'\n", b.String())
fmt.Printf("'%s'\n", b.String())
// Secon... |
// Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
package wasmlib
import (
"encoding/binary"
"strconv"
)
type ScImmutableAddress struct {
objId int32
keyId Key32
}
func (o ScImmutableAddress) Exists() bool {
return Exists(o.objId, o.keyId, TYPE_ADDRESS)
}
func (o ScImmutableAddress) Strin... |
package main
import (
"bufio"
"encoding/json"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"time"
)
var CONFIG *Config
func main() {
// 设置CPU核心数量
runtime.GOMAXPROCS(runtime.NumCPU())
// 设置日志的结构
log.SetFlags(log.Lshortfile | log.Ldate | log.Ltime ... |
/**********************************
/ Sedgewick's algorithm edition 4
/ Chapter 1 Quick Find
*********************************/
package quick_find
type Sites struct {
id []int
number int
}
func Init(n int) *Sites {
sites := &Sites{make([]int, n), n}
for i := range sites.id {
sites.id[i] = i
}
return sites... |
package main
import (
"fmt"
"sort"
)
func main() {
s := []string{"Ali", "Sancho", "Messi", "Bale", "Ronaldo"}
sort.Strings(s)
fmt.Println(s)
}
// [Ali Bale Messi Ronaldo Sancho]
|
package main
import (
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/spf13/viper"
"github.com/tidwall/gjson"
)
var (
ticker *time.Ticker
network string
prometheusURL string
totalVotin... |
package data
import (
"fmt"
"gopkg.in/go-playground/validator.v9"
)
type Validation struct {
validation *validator.Validate // refs validator.Validate struct
}
// NewValidation initialize and return the Validation struct
func NewValidation() *Validation {
validation := validator.New()
return &Validation{
va... |
// Copyright 2020 The Operator-SDK 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 ... |
/*Package income depicts current situation
Imaginary organisation has income from two kinds of projects viz. fixed billing and time and material.
The net income of the organisation is calculated by the sum of the incomes from these projects.
Assume that the currency is dollars and we will not deal with cents. It wil... |
package rules
import (
"strings"
)
//Execute1 :Todos los ComplexType\Sequence\Element del documento deben tener nombres con el primer caracter en minuscula
func (r *Rule) Execute1(xsd Schema) {
r.result = "OK"
if r.isXSD(xsd.XMLFile) {
for _, complexType := range xsd.ComplexType {
for _, element :=... |
package backtracking
import (
"fmt"
"testing"
)
func Test_permuteUnique(t *testing.T) {
res := permuteUnique([]int{1, 1, 2})
if len(res) != 3 {
t.Error(res)
}
fmt.Println(res)
}
|
package utils
import (
"bytes"
"context"
"os/exec"
"time"
)
/*
指令工具
*/
/* 超时执行指令 */
func RunWithTimeout(cmd *exec.Cmd, timeout time.Duration) (string, error) {
var out bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &out
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
if err... |
package mt
type SoundID int32
type SoundSrcType uint8
const (
NoSrc SoundSrcType = iota // nowhere
PosSrc // pos
AOSrc // ao
)
//go:generate stringer -linecomment -type SoundSrcType
type SoundDef struct {
Name string
Gain, Pitch, Fade float32
}
|
// Package database is a plugin that manages the badger database (e.g. garbage collection).
package database
import (
"errors"
"github.com/iotaledger/hive.go/kvstore"
"github.com/iotaledger/wasp/packages/coretypes"
"github.com/iotaledger/wasp/packages/dbprovider"
"github.com/iotaledger/wasp/packages/parameters"
... |
package main
import (
"fmt"
)
func main() {
imprimirMessage("hola", "mundo", "!")
}
func imprimirMessage(messages ...string) {
for _, message := range messages {
fmt.Println(message)
}
}
|
// Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
package solo
import "time"
// LogicalTime return current logical clock time on the 'solo' instance
func (env *Solo) LogicalTime() time.Time {
env.glbMutex.Lock()
defer env.glbMutex.Unlock()
return env.logicalTime
}
// AdvanceClockTo advances ... |
package main
type Priority int
const (
EMERGENCY Priority = 0
ALERT Priority = 1
CRITICAL Priority = 2
ERROR Priority = 3
WARNING Priority = 4
NOTICE Priority = 5
INFO Priority = 6
DEBUG Priority = 7
)
var PriorityName = map[Priority]string{
EMERGENCY: "EMERG",
ALERT: "ALERT",
C... |
package recursion
// Fac return n's factorial by recursion
func Fac(n int) int {
if n < 2 {
return n
}
return n * Fac(n-1)
}
// Fac2 return n's factorial by foreach
func Fac2(n int) (ret int) {
ret = 1
for i := 2; i <= n; i++ {
ret = ret * i
}
return
}
|
package main
import (
"bufio"
"fmt"
"io"
"os"
"strings"
)
func ReadConfig(filepath string) map[string]string {
res := map[string]string{}
file, err := os.Open(filepath)
if err != nil {
return res
}
defer file.Close()
buf := bufio.NewReader(file)
for {
l, err := buf.ReadString('\n')
line := strings.T... |
package leetcode
import "testing"
func TestSubtractProductAndSum(t *testing.T) {
if subtractProductAndSum(234) != 15 {
t.Fatal()
}
if subtractProductAndSum(4421) != 21 {
t.Fatal()
}
if subtractProductAndSum(114) != -2 {
t.Fatal()
}
}
|
package api
import (
"fmt"
"github.com/kalifun/gin-template/global"
"github.com/kalifun/gin-template/middleware/config"
"github.com/kalifun/gin-template/middleware/logs"
"github.com/kalifun/gin-template/router"
"github.com/spf13/cobra"
"net/http"
)
var Api = &cobra.Command{
Use: "server",
Short: "Start... |
package main
import (
"errors"
"flag"
"net"
"os"
"os/signal"
"syscall"
"protocol"
"tun"
"github.com/golang/glog"
)
func main() {
var network, secret, listenAddr, ipnet, upScript, downScript string
flag.StringVar(&network, "network", "udp", "network of transport layer")
flag.StringVar(&secret, "secret",... |
// Matt Behrens <askedrelic@gmail.com>
// 2013/04/08 16:57:42
package main
import "strconv"
// import "fmt"
func IterativeFizz(max int) {
for i:= 1; i <= max; i++ {
if (i % 3 == 0 && i % 5 == 0) {
println("fizzbuzz")
} else if (i % 3 == 0) {
println("fizz")
} else... |
package main
import "fmt"
type Node struct {
Left *Node
Value rune
Right *Node
}
type Queue struct {
nodes []*Node
head int
tail int
count int
}
func walk(n *Node) {
if n == nil { return }
q := &Queue{nodes: make([]*Node, 11)}
q.push(n)
for q.count != 0 {
current := q.pop()
fmt.Printf("%c", current... |
package gocmd
import (
"os/exec"
"strings"
)
func ExecCmd(cmdStr string) (res string, err error) {
args := strings.Split(cmdStr, " ")
resb,err := exec.Command(args[0], args[1:]...).Output()
if err != nil {
return "", err
}
return string(resb), nil
}
|
package main
import (
"bytes"
"crypto/rand"
"database/sql"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"os"
"time"
"github.com/gorilla/mux"
_ "github.com/lib/pq"
"github.com/satori/go.uuid"
"github.com/tobyjsullivan/log-sdk/reader"
"github.com/tobyjsull... |
package api
import (
"bytes"
"encoding/json"
"fmt"
"strings"
MQTT "github.com/eclipse/paho.mqtt.golang"
"github.com/johannesrohwer/redfish/core"
)
const APIBASE = "redfish/api/v1.0"
type ReplyChannelMessage struct {
RequestID string
Payload interface{}
}
type MQTTFacade struct {
broker string
cl... |
package main
import (
"errors"
"fmt"
"math/rand"
"net"
"os"
"os/exec"
"os/signal"
"strconv"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/Logiase/gomirai/bot"
"github.com/Logiase/gomirai/message"
)
type KEY struct {
word string
reply string
}
type KEYS struct {
data []KEY
}
type COUNTE... |
package jsonv
import (
"bytes"
"io"
"reflect"
"testing"
)
func Test_scannerTokens(t *testing.T) {
cases := []struct {
json string
tok TokenType
val []byte
}{
{"{", TokenObjectBegin, []byte("{")},
{" {", TokenObjectBegin, []byte("{")},
{"\t{", TokenObjectBegin, []byte("{")},
{"\n{", TokenObjectBe... |
package services_test
import (
"errors"
"reflect"
"strconv"
"testing"
"github.com/mrdulin/go-rpc-cnode/mocks"
"github.com/mrdulin/go-rpc-cnode/models"
"github.com/mrdulin/go-rpc-cnode/services"
"github.com/stretchr/testify/mock"
)
const (
baseurl string = "http://localhost:3000"
accesstoken string = "1... |
package global
const (
// Version go-admin version info
Version = "2.1.0"
)
var (
Source string
Driver string
DBName string
)
|
package persistence
import (
"database/sql"
"errors"
"gopetstore/src/domain"
"gopetstore/src/util"
"log"
"time"
)
const (
getOrderByOrderIdSQL = `select BILLADDR1 AS billAddress1,BILLADDR2 AS billAddress2,BILLCITY,BILLCOUNTRY,BILLSTATE,BILLTOFIRSTNAME,BILLTOLASTNAME,BILLZIP,
SHIPADDR1 AS shipAddress1,SHIPADDR2... |
package configuration
import (
"io/ioutil"
"launchpad.net/goyaml"
"log"
"os"
"path/filepath"
)
type Configuration interface {
GetDatabase() Database
GetKeys() Keys
GetMail() Mails
GetUrl() string
loadConfiguration()
GetFilePath(filename string) string
}
type FileConfiguration struct {
Db Database
Key ... |
package util
import (
"bytes"
"io"
"testing"
)
func makeStreams() (*ReadSeekCloseWrapper, io.WriteCloser) {
r, w := io.Pipe()
s := WrapReadSeekClose(r)
return s, w
}
func TestRead(t *testing.T) {
r, w := makeStreams()
buf := make([]byte, 10)
go func() {
if _, err := w.Write([]byte("hello")); err != nil {... |
package lib
import (
"fmt"
"github.com/sacloud/libsacloud/api"
"github.com/sacloud/libsacloud/sacloud"
"github.com/yamamoto-febc/jobq"
"github.com/yamamoto-febc/sacloud-delete-all/version"
"strings"
"sync"
"time"
)
type ParallelJobPayload struct {
RouteName string
Targets []string
}
func doActionPerZone(... |
package scraper
import (
"net/http"
"net/http/httptest"
"reflect"
"testing"
"github.com/yevhenshymotiuk/ekatalog-scraper/items"
)
func newTestServer() *httptest.Server {
mux := http.NewServeMux()
mux.HandleFunc("/html", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/htm... |
/**
* day 02 2020
* https://adventofcode.com/2020/day/2
*
* compile: go build main.go
* run: ./main < input
* compile & run: go run main.go < input
**/
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func sled(min int, max int, c byte, pass string) int {
count := 0
for i, _ := range pass {
if... |
package main
import (
"github.com/antonybudianto/go-starter/app"
)
func main() {
a := app.App{}
a.Initialize("root", "hello", "rest_api_example")
a.Run(":8000")
}
|
package common
import (
"github.com/asim/go-micro/config"
"github.com/asim/go-micro/plugins/config/source/consul"
"strconv"
)
func GetConsulConfig(host string, port int64, prefix string) (config.Config, error) {
consulSource := consul.NewSource(
consul.WithAddress(host+":"+strconv.FormatInt(port,10)),
consul.... |
package types
import (
"github.com/graphql-go/graphql"
)
//Owner type definition
type Owner struct {
ID int `db:"id" json:"id"`
FirstName string `db:"first_name" json:"first_name"`
LastName string `db:"last_name" json:"last_name"`
}
//OwnerType is graphql schema for type owner
var OwnerType = graphql.... |
package templates
//go:generate go run github.com/pseudo-su/templates -t text -s . -o templates.gen.go
|
package pget
import (
"bytes"
"fmt"
"github.com/Code-Hex/updater"
"github.com/jessevdk/go-flags"
"github.com/pkg/errors"
)
// Options struct for parse command line arguments
type Options struct {
Help bool `short:"h" long:"help"`
NumConnection int `short:"p" long:"procs" default:"1"`
Output ... |
package sweet
import (
"fmt"
"strings"
)
type nameChain struct {
fmt.Stringer
names []string
}
func newNameChain(names ...string) *nameChain {
return &nameChain{
names: names,
}
}
func (n *nameChain) String() string {
return strings.Join(n.names, " => ")
}
func (n *nameChain) append(name string) *nameChai... |
package main
import (
"fmt"
tl "github.com/JoelOtter/termloop"
)
// GameOverLevel is displayed when the game has ended.
type GameOverLevel struct {
*tl.BaseLevel
}
func gameOver() {
game.Log("Game ended :(")
screen := tl.NewScreen()
lvl := &GameOverLevel{
BaseLevel: tl.NewBaseLevel(tl.Cell{
Bg: tl.ColorD... |
package auth
import (
"github.com/dghubble/go-twitter/twitter"
"github.com/dghubble/oauth1"
"log"
"os"
)
var twitterClient *twitter.Client = nil
func grantNewClientAccess(){
consumerKey := os.Getenv("TWITTER_CONSUMER_KEY")
consumerSecret := os.Getenv("TWITTER_CONSUMER_SECRET")
accessToken := os.Getenv("TWI... |
package main
// modified from HelloWorld example at https://github.com/GoogleCloudPlatform/golang-samples/blob/master/appengine/go11x/helloworld/helloworld.go
import (
"fmt"
"log"
"net/http"
"os"
"time"
"cloud.google.com/go/datastore"
)
func main() {
http.HandleFunc("/", indexHandler)
port := os.Getenv("POR... |
// +build !windows
package process
func (p *Process) postStart() error {
return nil
}
|
package main
/*
#cgo pkg-config
#include "Python.h"
#include <stdio.h>
#include <stdlib.h>
extern void c_msg(char*);
*/
import "C"
import "unsafe"
import (
"fmt"
"strings"
)
const Version = `v0.0.0`
//export blahblah
func blahblah(cStr *C.char, cCnt C.int) *C.char {
// Convert our cStr into a Go string
s := C.G... |
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
)
const (
filename = "test.txt"
)
func main() {
write()
read()
}
func write() {
file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer file.Close()
file.WriteString("metaprogramming... |
package main
import "fmt"
func main() {
sc := Constructor([]string{
"ab", "ba", "aaab", "abab", "baa",
})
res := []bool{false, false, false, false, false, true, true,
true, true, true, false, false, true, true, true, true, false, false, false, true, true, true, true, true, true, false, true, true, true, fals... |
package cluster
import (
"fmt"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/openshift/rosa/pkg/helper/versions"
)
var _ = Describe("Validates OCP version", func() {
const (
nightly = "nightly"
stable = "stable"
fast = "fast"
)
var _ = Context("when creating a hosted cluster... |
package account
import (
"database/sql"
"errors"
_ "github.com/go-sql-driver/mysql"
)
type Account struct {
Login string
Password string
LastActive string
AccessLevel uint8
Banned bool
CharacterSlot uint8
// CharacterList []Character
}
// Update the database with all these fun values
func (a *Ac... |
package memory
import (
"context"
"errors"
"go.uber.org/zap"
"github.com/silverspase/todo/internal/modules/auth"
"github.com/silverspase/todo/internal/modules/auth/model"
)
type memoryStorage struct {
users map[string]model.User // TODO change to sync.Map
// usersArray []model.User // TODO use this for pagin... |
package model
type StreamFilterList struct {
// List of stream filters
Filters []StreamFilter `json:"filters,omitempty"`
}
|
package pathfileops
type DirectoryStatsDto struct {
numOfFiles uint64
numOfSubDirs uint64
numOfBytes uint64
isInitialized bool
}
func (dirStats *DirectoryStatsDto) IsInitialized() bool {
return dirStats.isInitialized
}
func (dirStats *DirectoryStatsDto) NumOfFiles() uint64 {
return dirStats.numOfF... |
// 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 (
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
)
// The BIND Port
const PORT = 8000
// Local SystemInfo Cache
var SystemInfo *SysInfo
func main() {
//Initialize System Info
SystemInfo = NewSystemInfo()
//Initialize a new router object
router := mux.NewRouter()
//Set header content... |
// Package iban implements validation of IBAN as defined in ISO 13616
package iban
import (
"errors"
"math/big"
"regexp"
"strings"
)
// Validate performs a sanity check on the IBAN number provided
func Validate(iban string) error {
iban = normalizeIBAN(iban)
if !validIBANChars(iban) {
return errors.New("inval... |
package start
import (
. "github.com/zond/godip/variants/classical/common"
"github.com/zond/godip/common"
)
func SupplyCenters() map[common.Province]common.Nation {
return map[common.Province]common.Nation{
"edi": England,
"lvp": England,
"lon": England,
"bre": France,
"par": France,
"mar": France,
"... |
package application
import (
"net/http"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
type Application struct {
ListenAddr string
MongoAddr string
}
func NewApplication() *Application {
viper.SetConfigName("config")
viper.AddConfigPath(".")
if err := viper.ReadInConfig(); err != nil {
log.... |
package main
import (
"fmt"
)
func genParens(strSoFar string, remainingLParens, unpairedLParens int, results []string) []string {
if remainingLParens == 0 {
if len(strSoFar) == 0 {
return results
}
if unpairedLParens > 0 {
return genParens(strSoFar+string(")"), remainingLParens, unpairedLParens-1, resu... |
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reorderList(head *ListNode) {
if head==nil || head.Next==nil{
return
}
var fast, slow *ListNode
fast=head
slow=head
for ;fast.Next != nil && fast.Next.Next !=nil;{
... |
package github
import (
"archive/tar"
"compress/gzip"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"github.com/gomods/athens/pkg/repo"
)
const (
fetchRepoURI string = "https://api.github.com/repos/%s/%s/tarball/%s"
tmpFileName = "%s-%s-%s" // owner-repo-ref
)
type gitCrawler struct {
owne... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.