text stringlengths 11 4.05M |
|---|
/* Mysterium network payment library.
*
* Copyright (C) 2020 BlockDev AG
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) an... |
package redisLayer
import (
"fmt"
"os"
"github.com/gomodule/redigo/redis"
)
var pool *redis.Pool
var connection redis.Conn
var redisURL = os.Getenv("REDIS_URL")
func Initialize() {
pool = newPool()
}
func SetKeyBytes(key string, value []byte) error {
if pool == nil {
Initialize()
}
conn := pool.Get()
def... |
package main
import "sync"
func main() {
wg := sync.WaitGroup{}
si := []int{1,2,3,4,5,6,7}
for i := range si {
wg.Add(1)
go func(l int) {
println(l)
wg.Done()
}(i)
}
// var i *int = 0x00c420094010
// println(*i)
wg.Wait()
} |
package horspool
func createShiftTable(pattern string) map[byte]int {
shiftTable := make(map[byte]int)
for i := 0; i < len(pattern)-1; i++ {
index := pattern[i]
shiftTable[index] = len(pattern) - i - 1
}
return shiftTable
}
func createReverseShiftTable(pattern string) map[byte]int {
shiftTable := make(map[b... |
package heuristics
func mScore(nb int, x int, y int, size int, nbPos map[int][2]int) float32 {
tmp := nbPos[nb]
x1 := tmp[0]
y1 := tmp[1]
return float32(abs((x1 - x)) + abs((y1 - y)))
}
func manhattan(grid []int, size int, depth int) float32 {
var score float32
for x := 0; x < size; x++ {
for y := 0; y < size... |
// Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
package consensus
import (
"fmt"
"github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/balance"
valuetransaction "github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/transaction"
"github.com/iotaledger/wasp/packages/chain"
... |
// 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 host
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"net"
"sync"
"time"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/google/gopacket/pcap"
)
// Scanner provide container for control local network scanning
// process and checking results
type Scanner struct {
mu ... |
package main
import "fmt"
type person struct {
first string
last string
age int
}
// func [reciver] functionName([params]) [return type] {}
// Here we attach this function (fullName) to the type person
func (p person) fullName() string {
return p.first + " " + p.last
}
func main() {
p1 := person{"James", "B... |
package memrepo
import (
"github.com/scjalliance/drivestream/commit"
"github.com/scjalliance/drivestream/resource"
)
var _ commit.TreeGroup = (*CommitTreeGroup)(nil)
// CommitTreeGroup is an unordered group of tree changes sharing a common
// parent.
type CommitTreeGroup struct {
repo *Repository
drive resour... |
package main
import "fmt"
type Item struct {
productID int
qtd int
price float64
}
type Order struct {
userID int
items []Item
}
func (o Order) Value() float64 {
total := 0.0
for _, Item := range o.items {
total += Item.price * float64(Item.qtd)
}
return total
}
func main() {
order := Order{... |
package sieve
import (
"bytes"
"encoding/json"
"fmt"
"regexp"
"text/template"
)
type EventHandler interface {
HandleEvent(results []string, event *Event) error
}
// SimpleEventHandler assigns event description formatted based on regex groups
type SimpleEventHandler struct {
*template.Template
Severity string... |
package main
import (
"crypto/ed25519"
"fmt"
"time"
"github.com/pascaldekloe/jwt"
)
var JWTPrivateKey ed25519.PrivateKey
var JWTPublicKey ed25519.PublicKey
func initJWT() {
seed := Config.Seed
if seed == "" {
return
}
for len(seed) < ed25519.SeedSize {
seed = seed + seed
}
if len(seed) > ed25519.SeedS... |
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main() {
var i uint64 = 4
var d float64 = 4.0
var s string = "HackerRank "
scanner := bufio.NewScanner(os.Stdin)
var j uint64
var e float64
var t string
var texts []string
for scanner.Scan() {
text := scanner.Text()
texts = append(texts, te... |
package problems
import (
"testing"
)
func TestReverseBetween(t *testing.T) {
tasks := []struct {
list []int
m, n int
expect []int
}{
{
list: []int{1, 2, 3, 4, 5},
m: 2,
n: 4,
expect: []int{1, 4, 3, 2, 5},
},
{
list: []int{2, 3, 5, 6, 4, 1, 8, 9, 0, 7},
m: 2,
... |
package stockdb
import(
_ "github.com/go-sql-driver/mysql"
"entity"
"util"
)
type StockHistDataDB struct {
DBBase
}
func (s *StockHistDataDB) Insert(code string, d entity.StockHistData) int {
db := s.Open()
stmt, err := db.Prepare("insert stockhistdata set code=?, date=?, open=?, close=?, hig... |
package main
import "fmt"
func main() {
numbers := [5]int{1, 2, 3, 4, 5}
var s1 []int = numbers[1:3]
var s2 []int = numbers[2:4]
fmt.Println(numbers)
fmt.Println(s1)
fmt.Println(s2)
// Change data
s2[0] = 333
fmt.Println("numbers :", numbers)
fmt.Println("s1 :", s1)
fmt.Println("s2 :", s2)
}
|
/*
Given an initial array arr, every day you produce a new array using the array of the previous day.
On the i-th day, you do the following operations on the array of day i-1 to produce the array of day i:
If an element is smaller than both its left neighbor and its right neighbor, then this element is incremented.
... |
package main
import (
"flag"
"fmt"
"github.com/nokamoto/grpc-proxy/proxy"
"github.com/prometheus/client_golang/prometheus/promhttp"
"net/http"
)
func main() {
var (
port = flag.Int("p", 9000, "gRPC server port")
pb = flag.String("pb", "", "file descriptor protocol buffers filepath")
yml = flag.String("... |
package sploit
import (
"bytes"
"testing"
)
func TestROPDumpX8664(t *testing.T) {
e, _ := NewELF(elfFile)
r, err := e.ROP()
if err != nil {
t.Fatal(err)
}
r.Dump()
}
func TestROPInstrSearchX8664(t *testing.T) {
e, _ := NewELF(elfFile)
r, _ := e.ROP()
gadgets, err := r.InstrSearch(".*")
if err != nil {
... |
package main
import (
"alignfootbot/afdb"
"fmt"
"github.com/Syfaro/telegram-bot-api"
"github.com/vrischmann/envconfig"
"log"
"reflect"
"strconv"
"strings"
)
type Config struct {
DbHost string `envconfig:"DB_HOST"`
DbPort string `envconfig:"DB_PORT"`
DbUser string `envconfig:"DB_USER"`
DbName s... |
// 1. 以 maxPutQPS 的速度写入
// 2. 写入一定数量之后,开始以 getQPS, putQPS 分别进行读写
// 3. 读取的内容为之前写入的数据,按照 sampleRatio (抽样率)进行抽样后随机处理,然后再进行去取。如果读取的速率大于写入的速率,则倒带至最开始
// 4. 顺便告诉需要等多久
package pool
import (
"context"
"errors"
"fmt"
"io/ioutil"
"log"
"math/rand"
"os"
"path"
"sync/atomic"
"time"
"golang.org/x/time/rate"
)
type P... |
package openinstrument
import (
"fmt"
"time"
)
type DurationTimer struct {
name string
start_time time.Time
end_time time.Time
total_time time.Duration
running bool
}
func NewNamedDurationTimer(name string) *DurationTimer {
return &DurationTimer{
name: name,
}
}
func NewDurationTime... |
package helpers
import (
"strconv"
"strings"
)
func SumConverter(amount string) (float64, bool, error) {
val, err := strconv.ParseFloat(amount, 64)
if err != nil {
s := strings.Trim(amount, "$")
if val, err = strconv.ParseFloat(s, 64); err != nil {
return 0, false, err
}
return val, false, nil
}
r... |
package model
// HealthComponent has variables that can be
// implemented into other structs
type HealthComponent struct {
}
|
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
"context"
"log"
"net"
"google.golang.org/grpc"
pb "google.golang.org/grpc/examples/helloworld/helloworld"
)
const (
port = ":50051"
)
// server is used to implement helloworld.GreeterServer.
type server struct{}
// SayHello implements hel... |
package main
import (
"consumer-importer/io"
"consumer-importer/model"
"consumer-importer/service"
"fmt"
"time"
)
var consumerService = service.ConsumerService{Props: &dbProperties}
var fileService = service.FileService{Props: &dbProperties}
var dbInitializerService = service.DatabaseInitializerService{Props: &d... |
package util
var (
EnvNodeName = "NODE_NAME"
)
|
package main
import "strconv"
type overLoad struct {
Name string
Age int
Wives []string
}
func NewOverLoad(arg interface{}) interface{} {
o := &overLoad{}
if val, ok := arg.(int); ok {
o.Age = val
} else if val, ok := arg.(string); ok {
o.Name = val
} else if val, ok := arg.([]string); ok {
o.Wives =... |
package response
//HealthResponse ...
type HealthResponse struct {
Status string `bson:"status" json:"status"`
}
|
package json
import (
"encoding/json"
"log"
)
func ToString(i interface{}) string {
if i == nil {
return ""
}
b, err := json.Marshal(i)
if err != nil {
log.Println("json.ToString:", err)
}
return string(b)
}
func ToBytes(i interface{}) (bs []byte) {
if i == nil {
return
}
b, err := json.Marshal(i)
i... |
// Copyright 2015 The Chromium 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 swarming
import (
"testing"
"github.com/maruel/ut"
)
func TestNew(t *testing.T) {
t.Parallel()
// TODO(maruel): Make a fake.
_, err := New... |
package helper
import (
"bytes"
"fmt"
"regexp"
"strings"
"syscall"
"text/template"
"github.com/gookit/goutil/strutil"
"golang.org/x/term"
)
const (
// RegGoodName match a good option, argument name
RegGoodName = `^[a-zA-Z][\w-]*$`
// RegGoodCmdName match a good command name
RegGoodCmdName = `^[a-zA-Z][\w... |
package main
import "fmt"
func main(){
x := []int{4, 7, 5 , 43}
fmt.Println(x)
x = append(x, 23, 33, 55, 44)
fmt.Println(x)
y := []int{23, 24, 54, 53}
x = append(x, y...)
fmt.Println(x)
} |
package main
import "fmt"
type Recipe struct {
Name string
CookTime float32
CookTemp float32
}
func (r Recipe) String() string {
return fmt.Sprintf("{Name: %s; CookTime: %g; CookTemp: %g}", r.Name, r.CookTime, r.CookTemp)
}
// Lab 08. Embarassingly Parallel
// Requirements:
// 01 - As a lonely person livin... |
package gcp
// see gcp_test.go for a test that subsumes tests for the deleter
|
package line_login
import (
"github.com/5hields/line-login/linethrift"
"github.com/apache/thrift/lib/go/thrift"
"log"
)
func newThriftClient(apiUrl string) (*thrift.TStandardClient, error) {
trans, err := thrift.NewTHttpClient(apiUrl)
if err != nil {
return nil, err
}
httpTrans := trans.(*thrift.THttpClient)... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//640. Solve the Equation
//Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' oper... |
package immortal
import (
"io/ioutil"
"log"
"testing"
)
func TestNewLoggerFileNone(t *testing.T) {
log.SetOutput(ioutil.Discard)
cfg := &Config{
Log: Log{
File: "/dev/null/nonexist",
},
}
quit := make(chan struct{})
l := NewLogger(cfg, quit)
expect(t, true, l == nil)
}
func TestNewLoggerBadLogger(t *... |
// Copyright 2019 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"
import "math" //可以使用多个import语句
func main() {
fmt.Printf("%f\n", math.Pi)
fmt.Printf("%.2f\n", math.Pi)
}
|
/*
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic. The number is represented as a string.
For example, the numbers "69", "88", and "818" are all strobogrammatic.
*/
package main
func main() {
... |
package main
import (
"fmt"
)
func main() {
fmt.Print("first ")
fmt.Print("second")
}
|
package kata
func FindOdd(seq []int) int {
target:=0
for i:=0;i<len(seq);i++{
target = seq[i]
times:=0
for j:=0;j<len(seq);j++ {
if target == seq[j]{
times++
}
}
if times%2==1{
return target
}
}
return -1
}
|
package problems
/*
Follow up:
1. only use constant extra space.
2. recursive solution is fine.
*/
// normal binary tree
func connect(root *Node) *Node {
if root == nil {
return nil
}
p := root.Next
// next subtree's most left child
for p != nil {
if p.Left != nil {
p = p.Left
break
}
if p.Right... |
package main
import (
"fmt"
"time"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
type Post struct {
Id int
Content string
Author string `sql:"not null"`
Comments []Comment
CreatedAt time.Time
}
type Comment struct {
Id int
Content string
Author string `sql:"not null"`
PostId... |
package main
import (
"fmt"
"io"
"os"
)
func main() {
// 读取文件 方法1
file, err := os.Open("./main/test.txt")
// 关闭文件流
defer file.Close();
if err != nil {
fmt.Println("打开文件出错")
}
// 读取文件里面的内容
var tempSlice = make([]byte, 1024)
var strSlice []byte
for {
n, err := file.Read(tempSlice)
if err == io.EOF {
... |
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func kthSmallest(root *TreeNode, k int) int {
elements := [] int{}
dfs(root, &elements)
sort.Slice(elements, func(a, b int) bool {
return elements[a] < elemen... |
package gate
import (
"encoding/binary"
"flag"
"fmt"
"github.com/golang/protobuf/proto"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
"hub000.xindong.com/rookie/rookie-framework/protobuf"
"log"
"net/http"
"net/url"
"sausage-shoot-proto/protocol"
"testing"
)
type TestHandler struct {}
func (m *Te... |
// Checkdisk looks at mounted filesystems, and reports the freespace.
// If the freespace is less than 10%, exit code is non-0.
package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
"syscall"
)
func main() {
// capicityThreshold is the percentage when alerts are generated.
capacityThreshold := 90
var aler... |
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"sort"
"strings"
"unicode"
"unicode/utf8"
)
func main() {
reader := bufio.NewReader(os.Stdin)
lineno := 0
var chars []rune
pinyinsOf := map[rune][]string{}
for {
lineno++
line, err := reader.ReadString('\n')
if err == io.EOF {
break
} else i... |
package generator
import (
"fmt"
)
type PersistStringer struct{}
// TYPECHANGE
func (per *PersistStringer) MessageInputDeclaration(method *Method) string {
printer := &Printer{}
printer.P("type %s struct{\n", NewPLInputName(method))
getPersistLibTypeName := GetSqlPersistLibTypeName
if method.IsSpanner() {
ge... |
package errors
import (
"errors"
"fmt"
"strconv"
spb "google.golang.org/genproto/googleapis/rpc/status"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type StatusError spb.Status
func ErrorCode(err error) int32 {
var stErr *StatusError
if errors.As(err, &stErr) {
return stErr.Code
}
if... |
package database
import (
"github.com/jinzhu/gorm"
"database/sql"
"flag"
"os"
"strconv"
"sync"
seeds "ImaginatoGolangTestTask/seeder"
)
// IConnection ITransaction is
type IConnection interface {
GetDB() *gorm.DB
}
// GormDB is
type connection struct {
db *gorm.DB
readonly bool
isTranscation bool
... |
package entity
type UserEntity struct {
Id int64 `mysql:"id" redis:"id" json:"UserId"`
Username string `mysql:"username" redis:"username" json:"Username"`
Password string `mysql:"password" redis:"password" json:"Password"`
Role string `mysql:"role" redis:"role" json:"Role"`
CreatedTime stri... |
package main
import (
"net/smtp"
"log"
//"fmt"
//"bytes"
"bytes"
)
func main() {
//auth := smtp.PlainAuth("", "", "", "mail.sonicwall.com:25")
//err := smtp.SendMail("mail.sonicwall.com:25", auth, "test@sonicwall.com", []string{"wcheng@sonicwall.com"}, []byte("test"))
//if err != nil {
// log.Fatal(err)
//}... |
package main
import (
"encoding/csv"
"os"
"reflect"
"strconv"
"github.com/olekukonko/tablewriter"
)
type Reporter interface {
Append(ps *PageStats)
Render() error
}
func structToMap(ps *PageStats) map[string]string {
values := make(map[string]string)
s := reflect.ValueOf(ps).Elem()
typeOfT := s.Type()
f... |
package models
import (
"database/sql"
"strconv"
"time"
"github.com/GoAdminGroup/go-admin/modules/db"
"github.com/GoAdminGroup/go-admin/modules/db/dialect"
)
// RoleModel is role model structure.
type RoleModel struct {
Base
Id int64
Name string
Slug string
CreatedAt string
UpdatedAt str... |
package main
import (
"fmt"
)
func main(){
var a int;
b:=2;
var c,d,e = 1, 2.0,"hello";
f:=010; /*octal no always starts with 0*/
g:=0xa; /*hexadecimal*/
fmt.Println("Hello-Go");
fmt.Printf("a=%d type(a)=%T\n",a,a);
fmt.Printf("b=%d type(b)=%T\n",b,b);
fmt.Printf("c=%d type(c)=%T\n",c,c);
fmt.Printf("d=%f... |
// 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... |
package index
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"regexp"
"time"
"github.com/dgrijalva/jwt-go"
"go.mongodb.org/mongo-driver/bson"
"golang.org/x/crypto/bcrypt"
)
func LoginUser(response http.ResponseWriter, request *http.Request) {
response.Header().Add("content-type", "appl... |
/*
Copyright © 2022 SUSE LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distri... |
package payloads
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
)
// Cipher provides methods to encrypt and decrypt values
type Cipher struct {
cipher.Block
}
// NewCipher returns a new aes Cipher for encrypting values
func NewCipher(secret []byte) (*Cipher, error) {
c, err ... |
package main
import (
"strconv"
"strings"
)
func parsePrice(priceText string) float64 {
newPrice := strings.Join(strings.Split(priceText, ","), "")
price, err := strconv.ParseFloat(newPrice, 64)
if err != nil {
return 0.0
}
return price
}
func parseCurrency(price string) float64 {
numberStart := 0
price =... |
/*
Copyright 2022 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,... |
package htmlLinks
import (
"net/http"
"net/url"
"sync"
"github.com/PuerkitoBio/goquery"
)
type Links struct {
Internal int
External int
Inaccesable int
}
/* FindLinks: In a html document, finds
Internal, External and Inaccesable links.
Param: doc (goquery.Document) html-document
Returns: Links... |
package main
import (
"context"
"crypto/tls"
"fmt"
"os"
"time"
"github.com/go-jwdk/activemq-connector"
"github.com/go-jwdk/jobworker"
"github.com/go-stomp/stomp"
uuid "github.com/satori/go.uuid"
)
func main() {
addr := os.Getenv("ACTIVEMQ_ADDR")
username := os.Getenv("ACTIVEMQ_USERNAME")
password := os.... |
package database
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
func Connection() *gorm.DB {
connection := "host=0.0.0.0 port=5432 user=postgres dbname=teste2 password=postgres sslmode=disable"
db, err := gorm.Open("postgres", connection)
if err != nil {
fmt.Println(... |
package main
import "fmt"
// fmt is format like printf
func main() {
fmt.Println("Hello World")
}
|
package main
import (
"flag"
"fmt"
"os"
"runtime"
"sync"
"github.com/BurntSushi/toml"
"github.com/agtorre/gocolorize"
"github.com/mijia/gobuildweb/assets"
"github.com/mijia/gobuildweb/loggers"
"strings"
)
type ProjectConfig struct {
sync.RWMutex
Package *PackageConfig
Assets *assets.Config
D... |
// Copyright 2021 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applica... |
package core
func NewVector(args ...Type) *Type {
slice := make([]Type, 0)
for _, arg := range args {
slice = append(slice, arg)
}
return &Type{Vector: &slice}
}
func (node *Type) IsVector() bool {
return node.Vector != nil
}
|
package core
import (
"fmt"
"sync"
"time"
)
type Space interface {
Get(key string) (Source, bool)
}
type Center struct {
nodes map[string]Source
sessions map[string]*Session
}
func (c *Center) NewSession(name string) (*Session, error) {
if _, ok := c.sessions[name]; ok {
return nil, fmt.Errorf("Session ... |
package scheduler
import (
"github.com/EmpregoLigado/cron-srv/mock"
"github.com/EmpregoLigado/cron-srv/models"
"testing"
)
func TestScheduleAll(t *testing.T) {
repoMock := mock.NewRepo()
s := New()
if err := s.ScheduleAll(repoMock); err != nil {
t.Errorf("Expected to schedule all events %s", err)
}
}
func T... |
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gorilla/mux"
)
func GetTestHandler() *Handler {
db := newDB(":memory:")
h := Handler{}
h.initialise(db)
return &h
}
func newRequest(t *testing.T, method, url string, body io.Reader) *http.Request {
... |
package main
/*
* @lc app=leetcode id=718 lang=golang
*
* [718] Maximum Length of Repeated Subarray
*/
// 提示:
// 1 1 2 3 4
// 1 2 3 4 5
//
// 1. 最长公共子串的写法
func findLength(A []int, B []int) int {
max := 0
dp := make([][]int, len(A)+1)
for i := range dp {
dp[i] = make([]int, len(B)+1)
}
for i := 0; i < len(A... |
package sdl2
import (
"fmt"
"github.com/veandco/go-sdl2/sdl"
"github.com/veandco/go-sdl2/ttf"
"github.com/evelritual/goose/graphics"
)
// Font wraps an SDL TTF Font and allows drawing to screen.
type Font struct {
renderer *sdl.Renderer // reference to renderer to use
font *ttf.Font
}
// NewFont opens a TTF... |
package algorand
import (
"bytes"
appComm "github.com/HNB-ECO/HNB-Blockchain/HNB/appMgr/common"
"github.com/HNB-ECO/HNB-Blockchain/HNB/config"
"github.com/HNB-ECO/HNB-Blockchain/HNB/consensus/algorand/bftGroup/vrf"
"github.com/HNB-ECO/HNB-Blockchain/HNB/consensus/algorand/msgHandler"
"github.com/HNB-ECO/HNB-Bloc... |
/*
Copyright 2020 The Kubernetes 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, ... |
package storage
import (
"bytes"
"encoding/gob"
"github.com/ActiveState/log"
"io/ioutil"
"os"
"sync"
)
// exposing these for testing
type Storage interface {
Encode(data interface{}) ([]byte, error)
Load(data interface{}) error
Write(buf []byte) error
}
type FileStorage struct {
file_path string
writeLock... |
package main
/**
* created: 2019/7/15 15:43
* By Will Fan
*/
func main() {
ch := make(chan int)
ch <- 1
println(<-ch)
}
|
package searching
import (
"fmt"
)
//BinarySearch implementation
func BinarySearch(array []int, tosearch int) int {
fmt.Println("Binary Search")
a := searching(array, 0, (len(array) - 1), tosearch)
return a
}
func searching(array []int, left, right, tosearch int) int {
if right >= left {
mid := left + (r... |
package domain
import (
"time"
"github.com/gofrs/uuid"
)
type CropBatchCreated struct {
UID uuid.UUID
BatchID string
Status CropStatus
Type CropType
Container CropContainer
InventoryUID uuid.UUID
FarmUID uuid.UUID
CreatedDate time.Time
InitialAreaUID uu... |
package mergeTwoLists
type ListNode struct {
Val int
Next *ListNode
}
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
var head *ListNode
var tail *ListNode
for l1 != nil && l2 != nil {
var node *ListNode
if l1.Val < l2.Val {
node = ... |
package main
import (
"fmt"
"log"
"net/http"
socketio "github.com/googollee/go-socket.io"
)
func main() {
fmt.Println("test")
server, err := socketio.NewServer(nil)
if err != nil {
log.Fatal(err)
}
server.OnConnect("/", func(s socketio.Conn) error {
log.Println("connected:", s.ID())
s.Emit(s.ID())
... |
package main
import (
"io/ioutil"
"os"
"github.com/yamil-rivera/flowit/internal/command"
"github.com/yamil-rivera/flowit/internal/config"
"github.com/yamil-rivera/flowit/internal/fsm"
"github.com/yamil-rivera/flowit/internal/io"
"github.com/yamil-rivera/flowit/internal/repository"
"github.com/yamil-rivera/flo... |
/*
* Copyright (C) 2016-Present Pivotal Software, Inc. All rights reserved.
*
* This program and the accompanying materials are made available under
* the terms of the 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 ... |
package cachingloader
import (
"context"
"github.com/ns1/jsonschema2go/pkg/gen"
"log"
"net/url"
"sync"
)
// New returns a new thread safe loader which caches requests and can handle either file system or http URIs. If the
// debug bool flag is set true, messages will be logged concerning every served request.
fu... |
package main
import (
"fmt"
)
func main() {
nrs := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
for i, nr := range nrs {
if nr%2 == 0 {
fmt.Println(i, " even")
} else {
fmt.Println(i, " odd")
}
}
}
|
package main
import (
"archive/tar"
"archive/zip"
"compress/gzip"
"fmt"
"github.com/gookit/color"
"github.com/vbauerster/mpb"
"github.com/vbauerster/mpb/decor"
"io"
"net/http"
"os"
"path/filepath"
"runtime"
"strconv"
"sync"
"time"
)
func main() {
sukkit := " ____ _ _ _ _ \n / ___| _ ... |
package oidc
import (
"fmt"
"github.com/ory/fosite"
"github.com/ory/herodot"
"github.com/authelia/authelia/v4/internal/configuration/schema"
"github.com/authelia/authelia/v4/internal/storage"
"github.com/authelia/authelia/v4/internal/templates"
)
// NewOpenIDConnectProvider new-ups a OpenIDConnectProvider.
fu... |
package core
import(
"log"
"fmt"
"github.com/boltdb/bolt"
"encoding/hex"
"os"
)
const dbFile="blockchain.db" //数据库文件名目录
const blockBucket="blocks" //名称
const genesisCoinbaseData="sssssdkdk"
/*
结构体定义区块 Blockchain
*/
type Blockchain struct{
// Blocks []*Block //一个存储Block指针地址的数组,
Tip []byte //二进制数组
DB *bolt.... |
package log
import (
"time"
"github.com/sirupsen/logrus"
"github.com/feng/future/go-kit/microsvr/app-server/service"
"github.com/feng/future/go-kit/microsvr/app-server/model"
)
//LoggingMiddleware 日志中间件
func LoggingMiddleware() service.SvcMiddleware {
return func(next service.AppService) service.AppService {
r... |
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/gorilla/mux"
"github.com/saurabmish/Coffee-Shop/data"
"github.com/saurabmish/Coffee-Shop/handlers"
)
func main() {
l := log.New(os.Stdout, "Coffee shop API service ", log.LstdFlags)
v := data.NewValidation()
coffeeHandl... |
package main
import (
"encoding/json"
"fmt"
)
//Person struct to build Go slice of struct from JSON string
type Person struct{
First string
Last string
Age int
Sayings []string
}
func main() {
s := `[
{
"First":"James",
"Last":"Bond",
"Age":32,
"Sayings":["Shaken, not stirred","Youth is no guara... |
package guest
import "context"
func (s *Service) GetAvailableSpace(ctx context.Context) (int, error) {
allGuests, err := s.ListGuests(ctx, false)
if err != nil {
return 0, err
}
allArrivedGuests, err := s.ListGuests(ctx, true)
if err != nil {
return 0, err
}
var totalSpace int
for _, guest := range allG... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//551. Student Attendance Record I
//You are given a string representing an attendance record for a student. The record only contains the following thr... |
func isIdealPermutation(A []int) bool {
for i,v:=range A{
if v-i>1 || v-i<(-1){
return false
}
}
return true
}
|
package conv
import (
"github.com/badgerodon/goreify/generics"
)
//go:generate goreify github.com/ElPeque/reflect-db/conv.To uint,uint8,uint16,uint32,uint64,int,int8,int16,int32,int64,float32,float64
func To(elem interface{}) generics.T1 {
switch elem.(type) {
// unsigned
case *uint:
return generics.T1(*elem.... |
package test
import (
"fmt"
"gengine/builder"
"gengine/context"
"gengine/engine"
"testing"
"time"
)
func Test_at_salience(t *testing.T) {
dataContext := context.NewDataContext()
dataContext.Add("println", fmt.Println)
//init rule engine
ruleBuilder := builder.NewRuleBuilder(dataContext)
err := ruleBuilde... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.