blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 4
108
| path
stringlengths 2
210
| src_encoding
stringclasses 12
values | length_bytes
int64 13
5.82M
| score
float64 2.52
5.22
| int_score
int64 3
5
| detected_licenses
listlengths 0
161
| license_type
stringclasses 2
values | detected_licenses_right
listlengths 0
161
| license_type_right
stringclasses 2
values | text
stringlengths 13
6.48M
| download_success
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9b7cc164b7cf3d91f0137027607942e44be509c9
|
Go
|
ajit555db/apigate
|
/cmd/auth-server/main.go
|
UTF-8
| 839 | 2.953125 | 3 |
[] |
no_license
|
[] |
no_license
|
// auth-server is an HTTP server API that authenticates all API requests of the travel project.
// It performs HTTP Basic Auth for all URLs except /healthz.
package main
import (
"flag"
"log"
"net/http"
)
func main() {
apiAddr := flag.String("http", ":8000", "HTTP API address")
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
username, password, ok := req.BasicAuth()
if !ok || username != password {
w.Header().Set("WWW-Authenticate", "Basic realm=\"travel\"")
w.WriteHeader(http.StatusUnauthorized)
log.Printf("%s 401", req.RequestURI)
return
}
w.Header().Set("X-Travel-User", username)
log.Printf("%s 200", req.RequestURI)
})
http.HandleFunc("/healthz", func(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("ok"))
})
log.Fatal(http.ListenAndServe(*apiAddr, nil))
}
| true |
29e5374accee48525bfd7d41193673197dab0026
|
Go
|
uaidessa/lets-go-wwg
|
/dia1/aula/ex6.go
|
UTF-8
| 259 | 3.34375 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
func main() {
var numeros [6]string
numeros[0] = "zero"
numeros[1] = "um"
numeros[2] = "dois"
numeros[3] = "tres"
numeros[4] = "quatro"
numeros[5] = "cinco"
fmt.Printf("o tipo é: %T\n", numeros)
fmt.Println(numeros)
}
| true |
33a46a193c5f9a6724ec3fed29df3fb61b1c8198
|
Go
|
lokimanosfr/reghelper
|
/main.go
|
UTF-8
| 11,426 | 2.890625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"errors"
"flag"
"fmt"
"log"
"os"
"reflect"
"regexp"
"strconv"
"strings"
"golang.org/x/sys/windows/registry"
)
type CommandArgs struct {
path string
value string
set string
replace string
get bool
contain string
help bool
valType string
deleteKey string
deleteValue string
createKey string
}
var (
args = CommandArgs{}
regTypes = map[string]uint32{
// "TEST": registry.
"DWORD": registry.DWORD,
"QWORD": registry.QWORD,
"SZ": registry.SZ,
"MULTI_SZ": registry.MULTI_SZ,
"EXPAND_SZ": registry.EXPAND_SZ,
}
//Access is a map for access
Access = map[string]uint32{
"read": registry.QUERY_VALUE,
"write": registry.QUERY_VALUE | registry.SET_VALUE,
"create": registry.QUERY_VALUE | registry.CREATE_SUB_KEY,
"delete": registry.QUERY_VALUE | registry.SET_VALUE,
}
)
func init() {
flag.StringVar(&args.path, "path", "", "Set the path to registry key")
flag.StringVar(&args.value, "value", "", "Set which value use")
flag.StringVar(&args.deleteKey, "delkey", "", "Will delete subkey(value) from path")
flag.StringVar(&args.deleteValue, "delval", "", "Will delete value of subkey ")
flag.StringVar(&args.set, "set", "", "Set params to value")
flag.StringVar(&args.replace, "replace", "", "Replace param or substring to another")
flag.BoolVar(&args.get, "get", false, "Get parametrs of value")
flag.StringVar(&args.contain, "contain", "", "Chek that the value contain param")
flag.StringVar(&args.valType, "type", "", "Used when need create value")
flag.StringVar(&args.createKey, "createkey", "", "create subkey")
flag.BoolVar(&args.help, "help", false, "Show usage")
flag.Parse()
if args.help {
fmt.Println("Usage:")
fmt.Println("-path <Path to key> -value <Value Name> -set <param>\t| Set params to value")
fmt.Println("-path <Path to key> -value <Value Name> -type <value type> -set <param>\t| Set params to value even it doesn't exist ( will create value)")
fmt.Println("-path <Path to key> -value <Value Name> -set \"<[param;param]>\"\t|Usage for REG_MULTI_SZ. Set params to value")
fmt.Println("-path <Path to key> -value <Value Name> type <value type> -set <[param;param]>\t| Usage for REG_MULTI_SZ. Set params to value even it doesn't exist ( will create value)")
fmt.Println("-path <Path to key> -value <Value Name> -replace <param>=><param>\t| Usage for replace param or substring to another. ")
fmt.Println("-path <Path to key> -value <Value Name> -get\t| Get parametrs of value")
fmt.Println("-path <Path to key> -value <Value Name> -contain <param>\t| fing param and return true if it's finded or false if not")
fmt.Println("-path <Path to key> -delkey <key>\t| Will delete key from path")
fmt.Println("-path <Path to key> -delval <value>\t| Will delete value from path ")
fmt.Println("-path <Path to key> -createkey <key>\t| Will create key ")
fmt.Println("-value <DWORD,QWORD,SZ,MULTI_SZ,EXPAND_SZ>\t| Types for params ")
os.Exit(0)
}
}
//main get fdfdfd
func main() {
if args.path == "" {
fmt.Println("invalid path and value, use -help")
return
}
switch arg := args.chekArgs(); arg {
case "set":
i, typ, err := setParams(args.path, args.value, args.valType, []string{args.set})
if err != nil {
fmt.Println(err.Error())
return
}
switch typ {
case 11:
strUint := strconv.FormatUint(getUint64FromInterface(i), 10)
fmt.Println("Set " + strUint + " to " + args.path + "\\" + args.value + " successful")
case 4:
strUint := strconv.FormatUint(uint64(getUint32FromInterface(i)), 10)
fmt.Println("Set " + strUint + " to " + args.path + "\\" + args.value + " successful")
case 1, 2:
fmt.Println("Set " + getStringFromInterface(i) + " to " + args.path + "\\" + args.value + " successful")
case 7:
arr := strings.Join(getStringsFromInterface(i), ";")
fmt.Println("Set " + arr + " to " + args.path + "\\" + args.value + " successful")
default:
}
case "replace":
was, now, typ, err := replaceParams(args.path, args.value, []string{args.replace})
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println("Replaced successful!")
switch typ {
case regTypes["SZ"], regTypes["EXPAND_SZ"]:
fmt.Println("Was: " + getStringFromInterface(was))
fmt.Println("Now: " + getStringFromInterface(now))
case regTypes["MULTI_SZ"]:
fmt.Println("Was: " + strings.Join(getStringsFromInterface(was), ";"))
fmt.Println("Now: " + strings.Join(getStringsFromInterface(now), ";"))
}
case "get":
i, typ := getParams(args.path, args.value)
switch typ {
case 11:
fmt.Println(getUint64FromInterface(i))
case 4:
fmt.Println(getUint32FromInterface(i))
case 1, 2:
fmt.Println(getStringFromInterface(i))
case 7:
fmt.Println(getStringsFromInterface(i))
default:
fmt.Println(args.path + "\\" + args.value + " is not exist")
}
case "contain":
case "create":
fmt.Println(createKey(args.path, args.createKey))
case "delkey":
fmt.Println(deleteKey(args.path, args.deleteKey))
case "delval":
fmt.Println(deleteValue(args.path, args.deleteValue))
default:
fmt.Println("invaid argument, use -help")
}
}
func getSplitedParams(argSet string) []string {
var spl []string
var out []string
if string(argSet[0]) == "[" && string(argSet[len(argSet)-1]) == "]" && strings.Contains(argSet, ";") {
spl = strings.Split(string(argSet[1:len(argSet)-1]), ";")
for _, p := range spl {
if p != "" {
out = append(out, p)
}
}
} else {
out = append(out, argSet)
}
return out
}
func (args *CommandArgs) chekArgs() string {
if args.set != "" {
return "set"
}
if args.replace != "" {
return "replace"
}
if args.get != false {
return "get"
}
if args.contain != "" {
return "contain"
}
if args.deleteKey != "" {
return "delkey"
}
if args.deleteValue != "" {
return "delval"
}
if args.createKey != "" {
return "create"
}
return ""
}
func getExistValueType(fullPath, value string) uint32 {
key := openKey(fullPath, Access["read"])
_, typ, err := key.GetValue(value, make([]byte, 0, 0))
if err != nil {
return 0
}
defer key.Close()
return typ
}
func getStringFromInterface(i interface{}) string {
return i.(string)
}
func getUint64FromInterface(i interface{}) uint64 {
v := reflect.ValueOf(i)
return v.Interface().(uint64)
}
func getUint32FromInterface(i interface{}) uint32 {
v := reflect.ValueOf(i)
return v.Interface().(uint32)
}
func getStringsFromInterface(i interface{}) []string {
src := reflect.ValueOf(i)
srcArr := src.Interface().([]string)
return srcArr
}
func replaceParams(fullPath, value string, param []string) (was interface{}, now interface{}, typ uint32, err error) {
argsToReplace := strings.Split(param[0], "=>")
typ = getExistValueType(fullPath, value)
if typ == 0 {
return nil, nil, 0, errors.New(value + " is not exist")
}
srcInterface, _ := getParams(fullPath, value)
switch typ {
case 1:
src := getStringFromInterface(srcInterface)
re := regexp.MustCompile(argsToReplace[0])
ss := re.ReplaceAllString(src, argsToReplace[1])
i, typ, err := setParams(fullPath, value, "", []string{ss})
return srcInterface, i, typ, err
case 2:
src := getStringFromInterface(srcInterface)
re := regexp.MustCompile(argsToReplace[0])
ss := re.ReplaceAllString(src, argsToReplace[1])
i, typ, err := setParams(fullPath, value, "", []string{ss})
return srcInterface, i, typ, err
case 7:
src := getStringsFromInterface(srcInterface)
re := regexp.MustCompile(argsToReplace[0])
var outArr []string
for _, line := range src {
ss := re.ReplaceAllString(line, argsToReplace[1])
outArr = append(outArr, ss)
}
i, typ, err := setParams(fullPath, value, "", []string{"[" + strings.Join(outArr, ";") + "]"})
return srcInterface, i, typ, err
default:
return nil, nil, 0, errors.New("Can't replace DWORD,QWORD,BINARY parametrs of value, only set")
}
}
func set(fullPath, value string, valType uint32, param []string) (interface{}, error) {
var err error
key := openKey(fullPath, Access["write"])
switch valType {
case 1:
err = key.SetStringValue(value, param[0])
case 2:
err = key.SetExpandStringValue(value, param[0])
case 4:
i, err2 := strconv.ParseUint(param[0], 10, 32)
if err2 != nil {
return nil, err2
}
err = key.SetDWordValue(value, uint32(i))
case 11:
i, err2 := strconv.ParseUint(param[0], 10, 64)
if err2 != nil {
return nil, err2
}
err = key.SetQWordValue(value, uint64(i))
case 7:
err = key.SetStringsValue(value, param)
}
key.Close()
i, _ := getParams(fullPath, value)
return i, err
}
func setParams(fullPath, value string, valType string, param []string) (interface{}, uint32, error) {
spl := getSplitedParams(param[0])
typ := getExistValueType(fullPath, value)
var i interface{}
var err error
if typ == 0 {
if valType != "" {
i, err = set(fullPath, value, regTypes[valType], spl)
typ = regTypes[valType]
return i, typ, err
}
fmt.Println("Value is not exist, use -help to know how create value")
} else {
i, err = set(fullPath, value, typ, spl)
}
return i, typ, err
}
func deleteKey(fullPath, path string) string {
key := openKey(fullPath, Access["delete"])
err := registry.DeleteKey(key, path)
if err != nil {
return "Key " + path + " not deleted:\n" + err.Error()
}
return "Key " + path + " delete successful"
}
func deleteValue(fullPath, value string) string {
key := openKey(fullPath, Access["delete"])
err := key.DeleteValue(value)
if err != nil {
return "Value " + value + " not deleted:\n" + err.Error()
}
return "Value " + value + " deleted successful"
}
func createKey(fullPath, subKey string) string {
key := openKey(fullPath, Access["create"])
_, opened, err := registry.CreateKey(key, subKey, registry.CREATE_SUB_KEY)
if err != nil {
return err.Error()
}
if opened {
return "Key alredy exist"
}
return fullPath + "\\" + subKey + " created"
}
func getParams(fullPath, value string) (interface{}, uint32) {
typ := getExistValueType(fullPath, value)
if typ == 0 {
return nil, 0
}
key := openKey(fullPath, Access["read"])
switch typ {
case 1, 2:
str, _, _ := key.GetStringValue(value)
return str, typ
case 4:
num, _, _ := key.GetIntegerValue(value)
return uint32(num), typ
case 11:
num, _, _ := key.GetIntegerValue(value)
return num, typ
case 7:
strArr, _, _ := key.GetStringsValue(value)
return strArr, typ
}
key.Close()
return nil, 0
}
func getHKEY(fullPath string) string {
return strings.Split(fullPath, "\\")[0]
}
func getKeyPath(fullPath string) string {
return strings.Join(strings.Split(fullPath, "\\")[1:], "\\")
}
func openKey(fullPath string, access uint32) registry.Key {
var k registry.Key
var err error
switch hkey := getHKEY(fullPath); hkey {
case "HKEY_LOCAL_MACHINE":
k, err = registry.OpenKey(registry.LOCAL_MACHINE, getKeyPath(fullPath), access)
case "HKEY_CURRENT_USER":
k, err = registry.OpenKey(registry.CURRENT_USER, getKeyPath(fullPath), access)
case "HKEY_CLASSES_ROOT":
k, err = registry.OpenKey(registry.CLASSES_ROOT, getKeyPath(fullPath), access)
case "HKEY_USERS":
k, err = registry.OpenKey(registry.USERS, getKeyPath(fullPath), access)
case "HKEY_CURRENT_CONFIG":
k, err = registry.OpenKey(registry.CURRENT_CONFIG, getKeyPath(fullPath), access)
}
if err != nil {
log.Fatal(err.Error() + "\npath = " + fullPath)
}
return k
}
| true |
2a32aa136e1be9b1a7364d6c9d4864ac7ce47762
|
Go
|
yfedoruk/gogof
|
/cmd/adapter/main.go
|
UTF-8
| 324 | 2.640625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
api "github.com/yfedoruck/gogof/pkg/adapter"
)
func main() {
fb := api.FacebookAdapter{
Messenger: api.Facebook{},
}
tw := api.TwitterAdapter{
Messenger: api.Twitter{},
}
for _, messenger := range []api.Messenger{fb, tw} {
fmt.Println(
messenger.Send("Hello World!"),
)
}
}
| true |
afb20d74f1b1ac4121d50e18bd95f9c2ab6970ab
|
Go
|
mipo47/WinterIsComing
|
/core/zombie.go
|
UTF-8
| 1,279 | 3.71875 | 4 |
[] |
no_license
|
[] |
no_license
|
package core
import (
"math/rand"
"strconv"
)
type Zombie struct {
Name string
X int
Y int
IsDead bool // Dead zombie = zombie that can't move anymore
}
// Returns true if zombie passes the wall (client lose)
func (zombie *Zombie) Move(width, height int) bool {
if zombie.IsDead {
return false
}
// move to random direction
rnd := rand.Float32()
if rnd < 0.5 { // go right (to the wall)
zombie.X++
if zombie.X >= width {
return true
}
} else if rnd < 0.7 { // go down
zombie.Y++
if zombie.Y >= height {
zombie.Y--
}
} else if rnd < 0.9 { // go up
zombie.Y--
if zombie.Y < 0 {
zombie.Y++
}
} else if zombie.X > 0 { // go left (step back)
zombie.X--
}
return false
}
func CreateZombies(maxX, maxY, zombieCount int) []Zombie {
zombies := make([]Zombie, zombieCount, zombieCount)
for i := 0; i < len(zombies); i++ {
var x, y int
// Find unique coordinates
for unique := false; !unique; {
x = rand.Intn(maxX)
y = rand.Intn(maxY)
unique = true
for _, zombie := range (zombies) {
if zombie.X == x && zombie.Y == y {
unique = false
break
}
}
}
zombies[i] = Zombie{
Name: "Zombie" + strconv.Itoa(i+1),
X: x,
Y: y,
IsDead: false,
}
}
return zombies
}
| true |
b572939740e792b552b29d66a31e1fef45f9ad8a
|
Go
|
HannahStroble/work-minimega
|
/src/plumbing/normal/normal.go
|
UTF-8
| 705 | 2.84375 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"bufio"
"flag"
"fmt"
"math/rand"
"os"
"strconv"
"time"
)
var (
f_stddev = flag.Float64("stddev", 0.0, "standard deviation")
f_seed = flag.Int64("seed", -1, "standard deviation")
)
func main() {
flag.Parse()
var s rand.Source
if *f_seed != -1 {
s = rand.NewSource(*f_seed)
} else {
s = rand.NewSource(time.Now().UnixNano())
}
r := rand.New(s)
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
f, err := strconv.ParseFloat(scanner.Text(), 64)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
fout := r.NormFloat64()**f_stddev + f
fmt.Println(fout)
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, err)
}
}
| true |
5e6e90aebdc0fea60d9f3d8535bc758df331713c
|
Go
|
ravlio/numericalgo
|
/integrate/simpson.go
|
UTF-8
| 816 | 3.203125 | 3 |
[] |
no_license
|
[] |
no_license
|
package integrate
import (
"fmt"
"github.com/askanium/numericalgo"
)
// Simpson is a function which accepts function, left, right bounds and n number of subdivisions. It returns the integration
// value of the function in the given bounds using simpson rule.
func Simpson(f func(float64) float64, l, r float64, n int) (float64, error) {
var eval, evalOdd, evalEven numericalgo.Vector
var x float64
if n == 0 {
return 0, fmt.Errorf("Number of subdivisions n cannot be 0")
}
h := (r - l) / float64(n)
for i := 0; i <= n; i++ {
x = l + h*float64(i)
eval = append(eval, f(x))
}
for i := 1; i < n; i++ {
if i%2 == 0 {
evalEven = append(evalEven, eval[i])
} else {
evalOdd = append(evalOdd, eval[i])
}
}
return h / 3 * (eval[0] + eval[n] + 4*evalOdd.Sum() + 2*evalEven.Sum()), nil
}
| true |
33683cedc6e01f8d9d2105eebd35648ffd82e9c2
|
Go
|
masnursalim/belajar-go
|
/15_function/03_function_return/function_named_return.go
|
UTF-8
| 219 | 3.390625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
func myFunc(x int, y int) (result int) {
result = x + y
return
// or with below
// return result
}
func main() {
fmt.Println(myFunc(10,5))
result := myFunc(10,5)
fmt.Println(result)
}
| true |
5ce3faf51dcc5833bdcc530f8b8ef715be13b90c
|
Go
|
arnaudjolly/aoc2019-go
|
/intcode/intcode.go
|
UTF-8
| 6,635 | 3.40625 | 3 |
[] |
no_license
|
[] |
no_license
|
package intcode
import (
"errors"
"strconv"
)
// ProgramCreator allows you to create an instance of Program
func ProgramCreator(state []int) func() *Program {
// keep the initial sequence safe
safeBackup := make([]int, len(state))
copy(safeBackup, state)
return func() *Program {
attempt := make([]int, len(safeBackup))
copy(attempt, safeBackup)
return &Program{program: attempt}
}
}
// Program contains the input data
type Program struct {
program []int
instrPtr int
extraMemory map[int]int
input chan int
output chan int
halted bool
relativeBase int
}
// Run executes the program
func (p *Program) Run(in, out, quit chan int) error {
p.input = in
p.output = out
for !p.halted {
err := p.ExecuteNextInstruction()
if err != nil {
return err
}
}
quit <- 0
return nil
}
// MemorySlice returns a slice of memory
// mixing program and extraMemory storage
func (p *Program) MemorySlice(start, end int) []int {
result := make([]int, end-start)
for idx := range result {
result[idx] = p.MemoryAt(start + idx)
}
return result
}
// MemoryAt returns the value at a specific address
// this allows to retrieve values outside program memory space
func (p *Program) MemoryAt(address int) int {
if address < len(p.program) {
return p.program[address]
}
return p.extraMemory[address-len(p.program)]
}
// SetMemory allows to set a value at address mixing program and extraMemory
func (p *Program) SetMemory(address int, v int) {
if address < len(p.program) {
p.program[address] = v
} else {
if p.extraMemory == nil {
p.extraMemory = make(map[int]int)
}
p.extraMemory[address-len(p.program)] = v
}
}
// IsCompleted informs about the completeness of the program
func (p *Program) IsCompleted() bool {
return p.MemoryAt(p.instrPtr) == 99
}
// ExecuteNextInstruction identifies instruction to execute and do it
func (p *Program) ExecuteNextInstruction() error {
instrCode := p.MemoryAt(p.instrPtr)
opcode := instrCode % 100
switch opcode {
case 1:
p.ExecuteAdd()
case 2:
p.ExecuteMultiply()
case 3:
p.ExecuteInput()
case 4:
p.ExecuteOutput()
case 5:
p.ExecuteJumpIfTrue()
case 6:
p.ExecuteJumpIfFalse()
case 7:
p.ExecuteLessThan()
case 8:
p.ExecuteEquals()
case 9:
p.ExecuteRelativeBaseOffset()
case 99:
close(p.output)
p.halted = true
default:
return errors.New("unknown opcode: " + strconv.Itoa(opcode))
}
return nil
}
// ExecuteRelativeBaseOffset adjusts the relative base
func (p *Program) ExecuteRelativeBaseOffset() {
inst := p.MemorySlice(p.instrPtr, p.instrPtr+2)
paramModes := getParamModes(inst[0])
firstParam := p.resolveParam(0, inst, paramModes)
p.relativeBase += firstParam
p.instrPtr += 2
}
// ExecuteEquals stores 1 in third if first == second else 0
func (p *Program) ExecuteEquals() {
inst := p.MemorySlice(p.instrPtr, p.instrPtr+4)
paramModes := getParamModes(inst[0])
firstParam := p.resolveParam(0, inst, paramModes)
secondParam := p.resolveParam(1, inst, paramModes)
dest := p.resolveDestination(2, inst, paramModes)
if firstParam == secondParam {
p.SetMemory(dest, 1)
} else {
p.SetMemory(dest, 0)
}
p.instrPtr += 4
}
// ExecuteLessThan stores 1 in third if first < second else 0
func (p *Program) ExecuteLessThan() {
inst := p.MemorySlice(p.instrPtr, p.instrPtr+4)
paramModes := getParamModes(inst[0])
firstParam := p.resolveParam(0, inst, paramModes)
secondParam := p.resolveParam(1, inst, paramModes)
dest := p.resolveDestination(2, inst, paramModes)
if firstParam < secondParam {
p.SetMemory(dest, 1)
} else {
p.SetMemory(dest, 0)
}
p.instrPtr += 4
}
// ExecuteJumpIfTrue jump to firstParam if non-zero
func (p *Program) ExecuteJumpIfTrue() {
inst := p.MemorySlice(p.instrPtr, p.instrPtr+3)
paramModes := getParamModes(inst[0])
firstParam := p.resolveParam(0, inst, paramModes)
secondParam := p.resolveParam(1, inst, paramModes)
if firstParam != 0 {
p.instrPtr = secondParam
} else {
p.instrPtr += 3
}
}
// ExecuteJumpIfFalse jump to firstParam if zero
func (p *Program) ExecuteJumpIfFalse() {
inst := p.MemorySlice(p.instrPtr, p.instrPtr+3)
paramModes := getParamModes(inst[0])
firstParam := p.resolveParam(0, inst, paramModes)
secondParam := p.resolveParam(1, inst, paramModes)
if firstParam == 0 {
p.instrPtr = secondParam
} else {
p.instrPtr += 3
}
}
// ExecuteInput simulate a "read" and insert input at the address coming next
func (p *Program) ExecuteInput() {
inst := p.MemorySlice(p.instrPtr, p.instrPtr+2)
paramModes := getParamModes(inst[0])
dest := p.resolveDestination(0, inst, paramModes)
p.SetMemory(dest, <-p.input)
p.instrPtr += 2
}
// ExecuteOutput simulate a print
func (p *Program) ExecuteOutput() {
inst := p.MemorySlice(p.instrPtr, p.instrPtr+2)
paramModes := getParamModes(inst[0])
firstParam := p.resolveParam(0, inst, paramModes)
p.output <- firstParam
p.instrPtr += 2
}
// ExecuteAdd handles addition opcode
func (p *Program) ExecuteAdd() {
inst := p.MemorySlice(p.instrPtr, p.instrPtr+4)
paramModes := getParamModes(inst[0])
firstParam := p.resolveParam(0, inst, paramModes)
secondParam := p.resolveParam(1, inst, paramModes)
dest := p.resolveDestination(2, inst, paramModes)
p.SetMemory(dest, firstParam+secondParam)
p.instrPtr += 4
}
func getParamModes(opCodeInstr int) map[int]int {
result := make(map[int]int)
modeOpCode := strconv.Itoa(opCodeInstr)
for i := len(modeOpCode) - 3; i >= 0; i-- {
switch modeOpCode[i] {
case '0':
result[len(modeOpCode)-3-i] = 0
case '1':
result[len(modeOpCode)-3-i] = 1
case '2':
result[len(modeOpCode)-3-i] = 2
}
}
return result
}
// ExecuteMultiply handles multiplication opcode
func (p *Program) ExecuteMultiply() {
inst := p.MemorySlice(p.instrPtr, p.instrPtr+4)
paramModes := getParamModes(inst[0])
firstParam := p.resolveParam(0, inst, paramModes)
secondParam := p.resolveParam(1, inst, paramModes)
dest := p.resolveDestination(2, inst, paramModes)
p.SetMemory(dest, firstParam*secondParam)
p.instrPtr += 4
}
func (p *Program) resolveParam(i int, instruction []int, modes map[int]int) int {
mode, found := modes[i]
if !found {
mode = 0
}
param := instruction[i+1]
switch mode {
case 0:
// address mode
return p.MemoryAt(param)
case 1:
// immediate mode
return param
case 2:
// relative mode
return p.MemoryAt(p.relativeBase + param)
default:
// should never happens
return 0
}
}
func (p *Program) resolveDestination(i int, instruction []int, modes map[int]int) int {
dest := instruction[i+1]
if modes[i] == 2 {
dest += p.relativeBase
}
return dest
}
| true |
5bc0772f89aa03040446db334105da15a38b6dcf
|
Go
|
RyanConnell/tracker
|
/scrape/scraper_test.go
|
UTF-8
| 860 | 3.234375 | 3 |
[] |
no_license
|
[] |
no_license
|
package scrape
import (
"fmt"
"io/ioutil"
"testing"
)
type attrs = map[string]string
func TestLinkGathering(t *testing.T) {
bytes, err := ioutil.ReadFile("testdata/simple-test.html")
if err != nil {
t.Fatalf("Unable to read file; %v", err)
}
scraper, err := Create(bytes)
if err != nil {
t.Fatalf("Unable to create scraper; %v", err)
}
body := scraper.FindFirst("p", attrs{"class": "content"})
links := body.FindAll("a", attrs{"class": "target"})
if len(links) != 3 {
t.Fatalf("Expected to match 3 links. Instead found %d", len(links))
}
for i, link := range links {
expected := fmt.Sprintf("http://testlink-%d", i+1)
actual, ok := link.GetAttr("href")
if !ok {
t.Fatalf("Returned tag has no href attribute")
}
if actual != expected {
t.Fatalf("Expected link to equal '%s' but found '%s'", expected, actual)
}
}
}
| true |
8eeaa3bc3a2f1874d69f9aa2ea9b8f172ae3166e
|
Go
|
joaosoft/go-money-backend
|
/app/storage_db_postgres.go
|
UTF-8
| 21,425 | 2.953125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package gomoney
import (
"database/sql"
"github.com/joaosoft/errors"
"github.com/joaosoft/manager"
"github.com/lib/pq"
)
// storagePostgres ...
type storagePostgres struct {
conn manager.IDB
}
// newStoragePostgres ...
func newStoragePostgres(connection manager.IDB) *storagePostgres {
return &storagePostgres{
conn: connection,
}
}
// getUsers ...
func (storage *storagePostgres) getUsers() ([]*user, error) {
rows, err := storage.conn.Get().Query(`
SELECT
user_id,
name,
email,
password,
description,
updated_at,
created_at
FROM money.users
`)
defer rows.Close()
if err != nil {
return nil, errors.New(errors.LevelError, 1, err)
}
users := make([]*user, 0)
for rows.Next() {
user := &user{}
if err := rows.Scan(
&user.UserID,
&user.Name,
&user.Email,
&user.Password,
&user.Token,
&user.Description,
&user.UpdatedAt,
&user.CreatedAt); err != nil {
if err != sql.ErrNoRows {
return nil, errors.New(errors.LevelError, 1, err)
}
return nil, nil
}
users = append(users, user)
}
return users, nil
}
// getUser ...
func (storage *storagePostgres) getUser(userID string) (*user, error) {
row := storage.conn.Get().QueryRow(`
SELECT
name,
email,
password,
token,
description,
updated_at,
created_at
FROM money.users
WHERE user_id = $1
`, userID)
user := &user{UserID: userID}
if err := row.Scan(
&user.Name,
&user.Email,
&user.Password,
&user.Token,
&user.Description,
&user.UpdatedAt,
&user.CreatedAt); err != nil {
if err != sql.ErrNoRows {
return nil, errors.New(errors.LevelError, 1, err)
}
return nil, nil
}
return user, nil
}
// getUserByEmail ...
func (storage *storagePostgres) getUserByEmail(email string) (*user, error) {
row := storage.conn.Get().QueryRow(`
SELECT
user_id,
name,
password,
token,
description,
updated_at,
created_at
FROM money.users
WHERE email = $1
`, email)
user := &user{Email: email}
if err := row.Scan(
&user.UserID,
&user.Name,
&user.Password,
&user.Token,
&user.Description,
&user.UpdatedAt,
&user.CreatedAt); err != nil {
if err != sql.ErrNoRows {
return nil, errors.New(errors.LevelError, 1, err)
}
return nil, nil
}
return user, nil
}
// createUser ...
func (storage *storagePostgres) createUser(newUser *user) (*user, error) {
if result, err := storage.conn.Get().Exec(`
INSERT INTO money.users(user_id, name, email, password, token, description)
VALUES($1, $2, $3, $4, $5, $6)
`, newUser.UserID, newUser.Name, newUser.Email, newUser.Password, newUser.Token, newUser.Description); err != nil {
return nil, errors.New(errors.LevelError, 1, err)
} else if rows, _ := result.RowsAffected(); rows > 0 {
return storage.getUser(newUser.UserID)
}
return nil, nil
}
// updateUser ...
func (storage *storagePostgres) updateUser(user *user) (*user, error) {
if result, err := storage.conn.Get().Exec(`
UPDATE money.users SET
name = $1,
email = $2,
password = $3,
token = $4,
description = $5
WHERE user_id = $6
`, user.Name, user.Email, user.Password, user.Token, user.Description, user.UserID); err != nil {
return nil, errors.New(errors.LevelError, 1, err)
} else if rows, _ := result.RowsAffected(); rows > 0 {
return storage.getUser(user.UserID)
}
return nil, nil
}
// deleteUser ...
func (storage *storagePostgres) deleteUser(userID string) error {
if _, err := storage.conn.Get().Exec(`
DELETE
FROM money.users
WHERE user_id = $1
`, userID); err != nil {
return errors.New(errors.LevelError, 1, err)
}
return nil
}
// getSessions ...
func (storage *storagePostgres) getSessions(userID string) ([]*session, error) {
rows, err := storage.conn.Get().Query(`
SELECT
session_id,
original,
token,
description,
updated_at,
created_at
FROM money.sessions
WHERE user_id = $1
`, userID)
defer rows.Close()
if err != nil {
return nil, errors.New(errors.LevelError, 1, err)
}
sessions := make([]*session, 0)
for rows.Next() {
session := &session{UserID: userID}
if err := rows.Scan(
&session.SessionID,
&session.Original,
&session.Token,
&session.Description,
&session.UpdatedAt,
&session.CreatedAt); err != nil {
if err != sql.ErrNoRows {
return nil, errors.New(errors.LevelError, 1, err)
}
return nil, nil
}
sessions = append(sessions, session)
}
return sessions, nil
}
// getSession ...
func (storage *storagePostgres) getSession(userID string, token string) (*session, error) {
row := storage.conn.Get().QueryRow(`
SELECT
session_id,
original,
description,
updated_at,
created_at
FROM money.sessions
WHERE user_id = $1 AND token = $2
`, userID, token)
session := &session{UserID: userID, Token: token}
if err := row.Scan(
&session.SessionID,
&session.Original,
&session.Description,
&session.UpdatedAt,
&session.CreatedAt); err != nil {
if err != sql.ErrNoRows {
return nil, errors.New(errors.LevelError, 1, err)
}
return nil, nil
}
return session, nil
}
// createSession ...
func (storage *storagePostgres) createSession(newSession *session) (*session, error) {
if result, err := storage.conn.Get().Exec(`
INSERT INTO money.sessions(session_id, user_id, original, token, description)
VALUES($1, $2, $3, $4, $5)
`, newSession.SessionID, newSession.UserID, newSession.Original, newSession.Token, newSession.Description); err != nil {
return nil, errors.New(errors.LevelError, 1, err)
} else if rows, _ := result.RowsAffected(); rows > 0 {
return storage.getSession(newSession.UserID, newSession.Token)
}
return nil, nil
}
// deleteSession ...
func (storage *storagePostgres) deleteSession(userID string, token string) error {
if _, err := storage.conn.Get().Exec(`
DELETE
FROM money.sessions
WHERE user_id = $1 AND token = $2
`, userID, token); err != nil {
return errors.New(errors.LevelError, 1, err)
}
return nil
}
// deleteSessions ...
func (storage *storagePostgres) deleteSessions(userID string) error {
if _, err := storage.conn.Get().Exec(`
DELETE
FROM money.sessions
WHERE user_id = $1
`, userID); err != nil {
return errors.New(errors.LevelError, 1, err)
}
return nil
}
// getWallets ...
func (storage *storagePostgres) getWallets(userID string) ([]*wallet, error) {
rows, err := storage.conn.Get().Query(`
SELECT
wallet_id,
name,
description,
password,
updated_at,
created_at
FROM money.wallets
WHERE user_id = $1
`, userID)
defer rows.Close()
if err != nil {
return nil, errors.New(errors.LevelError, 1, err)
}
wallets := make([]*wallet, 0)
for rows.Next() {
wallet := &wallet{
UserID: userID,
}
if err := rows.Scan(
&wallet.WalletID,
&wallet.Name,
&wallet.Description,
&wallet.Password,
&wallet.UpdatedAt,
&wallet.CreatedAt); err != nil {
if err != sql.ErrNoRows {
return nil, errors.New(errors.LevelError, 1, err)
}
return nil, nil
}
wallets = append(wallets, wallet)
}
return wallets, nil
}
// getWallet ...
func (storage *storagePostgres) getWallet(userID string, walletID string) (*wallet, error) {
row := storage.conn.Get().QueryRow(`
SELECT
name,
description,
password,
updated_at,
created_at
FROM money.wallets
WHERE user_id = $1 AND wallet_id = $2
`, userID, walletID)
wallet := &wallet{
WalletID: walletID,
UserID: userID,
}
if err := row.Scan(
&wallet.Name,
&wallet.Description,
&wallet.Password,
&wallet.UpdatedAt,
&wallet.CreatedAt); err != nil {
if err != sql.ErrNoRows {
return nil, errors.New(errors.LevelError, 1, err)
}
return nil, nil
}
return wallet, nil
}
// createWallets ...
func (storage *storagePostgres) createWallets(newWallets []*wallet) ([]*wallet, error) {
tx, err := storage.conn.Get().Begin()
if err != nil {
tx.Rollback()
return nil, errors.New(errors.LevelError, 1, err)
}
stmt, errItem := tx.Prepare(pq.CopyInSchema("money", "wallets", "wallet_id", "user_id", "name", "description", "password"))
if errItem != nil {
tx.Rollback()
return nil, errors.New(errors.LevelError, 1, err)
}
for _, newWallet := range newWallets {
if _, err := stmt.Exec(newWallet.WalletID, newWallet.UserID, newWallet.Name, newWallet.Description, newWallet.Password); err != nil {
tx.Rollback()
return nil, errors.New(errors.LevelError, 1, err)
}
}
if _, err := stmt.Exec(); err != nil {
tx.Rollback()
return nil, errors.New(errors.LevelError, 1, err)
}
if err := stmt.Close(); err != nil {
tx.Rollback()
return nil, errors.New(errors.LevelError, 1, err)
}
tx.Commit()
// get created wallets
createdWallets := make([]*wallet, 0)
for _, newWallet := range newWallets {
wallet, err := storage.getWallet(newWallet.UserID, newWallet.WalletID)
if err != nil {
return nil, errors.New(errors.LevelError, 1, err)
}
createdWallets = append(createdWallets, wallet)
}
return createdWallets, nil
}
// updateWallet ...
func (storage *storagePostgres) updateWallet(wallet *wallet) (*wallet, error) {
if result, err := storage.conn.Get().Exec(`
UPDATE money.wallets SET
name = $1,
description = $2,
password = $3
WHERE user_id = $4 AND wallet_id = $5
`, wallet.Name, wallet.Description, wallet.Password, wallet.UserID, wallet.WalletID); err != nil {
return nil, errors.New(errors.LevelError, 1, err)
} else if rows, _ := result.RowsAffected(); rows > 0 {
return storage.getWallet(wallet.UserID, wallet.WalletID)
}
return nil, nil
}
// deleteWallet ...
func (storage *storagePostgres) deleteWallet(userID string, walletID string) error {
if _, err := storage.conn.Get().Exec(`
DELETE
FROM money.wallets
WHERE user_id = $1 AND wallet_id = $2
`, userID, walletID); err != nil {
return errors.New(errors.LevelError, 1, err)
}
return nil
}
// getImages ...
func (storage *storagePostgres) getImages(userID string) ([]*image, error) {
rows, err := storage.conn.Get().Query(`
SELECT
image_id,
name,
description,
url,
file_name,
format,
raw_image,
updated_at,
created_at
FROM money.images
WHERE user_id = $1
`, userID)
defer rows.Close()
if err != nil {
return nil, errors.New(errors.LevelError, 1, err)
}
images := make([]*image, 0)
for rows.Next() {
image := &image{
UserID: userID,
}
if err := rows.Scan(
&image.ImageID,
&image.Name,
&image.Description,
&image.Url,
&image.FileName,
&image.Format,
&image.RawImage,
&image.UpdatedAt,
&image.CreatedAt); err != nil {
if err != sql.ErrNoRows {
return nil, errors.New(errors.LevelError, 1, err)
}
return nil, nil
}
images = append(images, image)
}
return images, nil
}
// getImage ...
func (storage *storagePostgres) getImage(userID string, imageID string) (*image, error) {
row := storage.conn.Get().QueryRow(`
SELECT
name,
description,
url,
file_name,
format,
raw_image,
updated_at,
created_at
FROM money.images
WHERE user_id = $1 AND image_id = $2
`, userID, imageID)
image := &image{
UserID: userID,
ImageID: imageID,
}
if err := row.Scan(
&image.Name,
&image.Description,
&image.Url,
&image.FileName,
&image.Format,
&image.RawImage,
&image.UpdatedAt,
&image.CreatedAt); err != nil {
if err != sql.ErrNoRows {
return nil, errors.New(errors.LevelError, 1, err)
}
return nil, nil
}
return image, nil
}
// createImage ...
func (storage *storagePostgres) createImage(newImage *image) (*image, error) {
if result, err := storage.conn.Get().Exec(`
INSERT INTO money.images(image_id, user_id, name, description, url, file_name, format, raw_image)
VALUES($1, $2, $3, $4, $5, $6, $7, $8)
`, newImage.ImageID, newImage.UserID, newImage.Name, newImage.Description, newImage.Url, newImage.FileName, newImage.Format, newImage.RawImage); err != nil {
return nil, errors.New(errors.LevelError, 1, err)
} else if rows, _ := result.RowsAffected(); rows > 0 {
return storage.getImage(newImage.UserID, newImage.ImageID)
}
return nil, nil
}
// updateImage ...
func (storage *storagePostgres) updateImage(updImage *image) (*image, error) {
if result, err := storage.conn.Get().Exec(`
UPDATE money.images SET
name = $1,
description = $2,
url = $3,
file_name = $4,
format = $5,
raw_image = $6
WHERE user_id = $7 AND image_id = $8
`, updImage.Name, updImage.Description, updImage.Url, updImage.FileName, updImage.Format, updImage.RawImage, updImage.UserID, updImage.ImageID); err != nil {
return nil, errors.New(errors.LevelError, 1, err)
} else if rows, _ := result.RowsAffected(); rows > 0 {
return storage.getImage(updImage.UserID, updImage.ImageID)
}
return nil, nil
}
// deleteImage ...
func (storage *storagePostgres) deleteImage(userID string, imageID string) error {
if _, err := storage.conn.Get().Exec(`
DELETE
FROM money.images
WHERE user_id = $1 AND image_id = $2
`, userID, imageID); err != nil {
return errors.New(errors.LevelError, 1, err)
}
return nil
}
// getCategories ...
func (storage *storagePostgres) getCategories(userID string) ([]*category, error) {
rows, err := storage.conn.Get().Query(`
SELECT
category_id,
image_id,
name,
description,
updated_at,
created_at
FROM money.categories
WHERE user_id = $1
`, userID)
defer rows.Close()
if err != nil {
return nil, errors.New(errors.LevelError, 1, err)
}
categories := make([]*category, 0)
for rows.Next() {
category := &category{
UserID: userID,
}
if err := rows.Scan(
&category.CategoryID,
&category.ImageID,
&category.Name,
&category.Description,
&category.UpdatedAt,
&category.CreatedAt); err != nil {
if err != sql.ErrNoRows {
return nil, errors.New(errors.LevelError, 1, err)
}
return nil, nil
}
categories = append(categories, category)
}
return categories, nil
}
// getCategory ...
func (storage *storagePostgres) getCategory(userID string, categoryID string) (*category, error) {
row := storage.conn.Get().QueryRow(`
SELECT
image_id,
name,
description,
updated_at,
created_at
FROM money.categories
WHERE user_id = $1 AND category_id = $2
`, userID, categoryID)
category := &category{
CategoryID: categoryID,
UserID: userID,
}
if err := row.Scan(
&category.ImageID,
&category.Name,
&category.Description,
&category.UpdatedAt,
&category.CreatedAt); err != nil {
if err != sql.ErrNoRows {
return nil, errors.New(errors.LevelError, 1, err)
}
return nil, nil
}
return category, nil
}
// createCategories ...
func (storage *storagePostgres) createCategories(newCategories []*category) ([]*category, error) {
tx, err := storage.conn.Get().Begin()
if err != nil {
tx.Rollback()
return nil, errors.New(errors.LevelError, 1, err)
}
stmt, errItem := tx.Prepare(pq.CopyInSchema("money", "categories", "category_id", "user_id", "image_id", "name", "description"))
if errItem != nil {
tx.Rollback()
return nil, errors.New(errors.LevelError, 1, err)
}
for _, newCategory := range newCategories {
if _, err := stmt.Exec(newCategory.CategoryID, newCategory.UserID, newCategory.ImageID, newCategory.Name, newCategory.Description); err != nil {
tx.Rollback()
return nil, errors.New(errors.LevelError, 1, err)
}
}
if _, err := stmt.Exec(); err != nil {
tx.Rollback()
return nil, errors.New(errors.LevelError, 1, err)
}
if err := stmt.Close(); err != nil {
tx.Rollback()
return nil, errors.New(errors.LevelError, 1, err)
}
tx.Commit()
// get created categories
createdCategories := make([]*category, 0)
for _, newCategory := range newCategories {
category, err := storage.getCategory(newCategory.UserID, newCategory.CategoryID)
if err != nil {
return nil, errors.New(errors.LevelError, 1, err)
}
createdCategories = append(createdCategories, category)
}
return createdCategories, nil
}
// updateCategory ...
func (storage *storagePostgres) updateCategory(category *category) (*category, error) {
if result, err := storage.conn.Get().Exec(`
UPDATE money.categories SET
image_id = $1
name = $2,
description = $3,
WHERE user_id = $4 AND category_id = $5
`, category.ImageID, category.Name, category.Description, category.UserID, category.CategoryID); err != nil {
return nil, errors.New(errors.LevelError, 1, err)
} else if rows, _ := result.RowsAffected(); rows > 0 {
return storage.getCategory(category.UserID, category.CategoryID)
}
return nil, nil
}
// deleteCategory ...
func (storage *storagePostgres) deleteCategory(userID string, categoryID string) error {
if _, err := storage.conn.Get().Exec(`
DELETE
FROM money.categories
WHERE user_id = $1 AND category_id = $2
`, userID, categoryID); err != nil {
return errors.New(errors.LevelError, 1, err)
}
return nil
}
// getTransactions ...
func (storage *storagePostgres) getTransactions(userID string) ([]*transaction, error) {
rows, err := storage.conn.Get().Query(`
SELECT
wallet_id,
transaction_id,
category_id,
price,
description,
date,
updated_at,
created_at
FROM money.transactions
WHERE user_id = $1
`, userID)
defer rows.Close()
if err != nil {
return nil, errors.New(errors.LevelError, 1, err)
}
transactions := make([]*transaction, 0)
for rows.Next() {
transaction := &transaction{
UserID: userID,
}
if err := rows.Scan(
&transaction.WalletID,
&transaction.TransactionID,
&transaction.CategoryID,
&transaction.Price,
&transaction.Description,
&transaction.Date,
&transaction.UpdatedAt,
&transaction.CreatedAt); err != nil {
if err != sql.ErrNoRows {
return nil, errors.New(errors.LevelError, 1, err)
}
return nil, nil
}
transactions = append(transactions, transaction)
}
return transactions, nil
}
// getTransaction ...
func (storage *storagePostgres) getTransaction(userID string, walletID string, transactionID string) (*transaction, error) {
row := storage.conn.Get().QueryRow(`
SELECT
category_id,
price,
description,
date,
updated_at,
created_at
FROM money.transactions
WHERE user_id = $1 AND wallet_id = $2 AND transaction_id = $3
`, userID, walletID, transactionID)
transaction := &transaction{
UserID: userID,
WalletID: walletID,
TransactionID: transactionID,
}
if err := row.Scan(
&transaction.CategoryID,
&transaction.Price,
&transaction.Description,
&transaction.Date,
&transaction.UpdatedAt,
&transaction.CreatedAt); err != nil {
if err != sql.ErrNoRows {
return nil, errors.New(errors.LevelError, 1, err)
}
return nil, nil
}
return transaction, nil
}
// createTransactions ...
func (storage *storagePostgres) createTransactions(newTransactions []*transaction) ([]*transaction, error) {
tx, err := storage.conn.Get().Begin()
if err != nil {
tx.Rollback()
return nil, errors.New(errors.LevelError, 1, err)
}
stmt, errItem := tx.Prepare(pq.CopyInSchema("money", "transactions", "transaction_id", "user_id", "wallet_id", "category_id", "price", "description", "date"))
if errItem != nil {
tx.Rollback()
return nil, errors.New(errors.LevelError, 1, err)
}
for _, newTransaction := range newTransactions {
if _, err := stmt.Exec(newTransaction.TransactionID, newTransaction.UserID, newTransaction.WalletID, newTransaction.CategoryID, newTransaction.Price, newTransaction.Description, newTransaction.Date); err != nil {
tx.Rollback()
return nil, errors.New(errors.LevelError, 1, err)
}
}
if _, err := stmt.Exec(); err != nil {
tx.Rollback()
return nil, errors.New(errors.LevelError, 1, err)
}
if err := stmt.Close(); err != nil {
tx.Rollback()
return nil, errors.New(errors.LevelError, 1, err)
}
tx.Commit()
// get created transactions
createdTransactions := make([]*transaction, 0)
for _, newTransaction := range newTransactions {
transaction, err := storage.getTransaction(newTransaction.UserID, newTransaction.WalletID, newTransaction.TransactionID)
if err != nil {
return nil, errors.New(errors.LevelError, 1, err)
}
createdTransactions = append(createdTransactions, transaction)
}
return createdTransactions, nil
}
// updateTransaction ...
func (storage *storagePostgres) updateTransaction(transaction *transaction) (*transaction, error) {
if result, err := storage.conn.Get().Exec(`
UPDATE money.transactions SET
category_id = $1,
price = $2,
description = $3,
date = $4
WHERE user_id = $5 AND wallet_id = $6 AND transaction_id = $7
`, transaction.CategoryID, transaction.Price, transaction.Description, transaction.Date, transaction.UserID, transaction.WalletID, transaction.TransactionID); err != nil {
return nil, errors.New(errors.LevelError, 1, err)
} else if rows, _ := result.RowsAffected(); rows > 0 {
return storage.getTransaction(transaction.UserID, transaction.WalletID, transaction.TransactionID)
}
return nil, nil
}
// deleteTransaction ...
func (storage *storagePostgres) deleteTransaction(userID string, walletID string, transactionID string) error {
if _, err := storage.conn.Get().Exec(`
DELETE
FROM money.transactions
WHERE user_id = $1 AND wallet_id = $2 AND transaction_id = $3
`, userID, walletID, transactionID); err != nil {
return errors.New(errors.LevelError, 1, err)
}
return nil
}
| true |
fabe4bb3586962063ae06f70c92471e612a4f8c9
|
Go
|
kataras/iris
|
/sessions/sessions.go
|
UTF-8
| 10,458 | 2.65625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
[
"BSD-3-Clause"
] |
permissive
|
package sessions
import (
"net/http"
"net/url"
"time"
"github.com/kataras/iris/v12/context"
"github.com/kataras/iris/v12/core/host"
)
func init() {
context.SetHandlerName("iris/sessions.*Handler", "iris.session")
}
// A Sessions manager should be responsible to Start/Get a sesion, based
// on a Context, which returns a *Session, type.
// It performs automatic memory cleanup on expired sessions.
// It can accept a `Database` for persistence across server restarts.
// A session can set temporary values (flash messages).
type Sessions struct {
config Config
provider *provider
cookieOptions []context.CookieOption // options added on each session cookie action.
}
// New returns a new fast, feature-rich sessions manager
// it can be adapted to an iris station
func New(cfg Config) *Sessions {
var cookieOptions []context.CookieOption
if cfg.AllowReclaim {
cookieOptions = append(cookieOptions, context.CookieAllowReclaim(cfg.Cookie))
}
if !cfg.DisableSubdomainPersistence {
cookieOptions = append(cookieOptions, context.CookieAllowSubdomains(cfg.Cookie))
}
if cfg.CookieSecureTLS {
cookieOptions = append(cookieOptions, context.CookieSecure)
}
if cfg.Encoding != nil {
cookieOptions = append(cookieOptions, context.CookieEncoding(cfg.Encoding, cfg.Cookie))
}
return &Sessions{
cookieOptions: cookieOptions,
config: cfg.Validate(),
provider: newProvider(),
}
}
// UseDatabase adds a session database to the manager's provider,
// a session db doesn't have write access
func (s *Sessions) UseDatabase(db Database) {
db.SetLogger(s.config.Logger) // inject the logger.
host.RegisterOnInterrupt(func() {
db.Close()
})
s.provider.RegisterDatabase(db)
}
// GetCookieOptions returns the cookie options registered
// for this sessions manager based on the configuration.
func (s *Sessions) GetCookieOptions() []context.CookieOption {
return s.cookieOptions
}
// updateCookie gains the ability of updating the session browser cookie to any method which wants to update it
func (s *Sessions) updateCookie(ctx *context.Context, sid string, expires time.Duration, options ...context.CookieOption) {
cookie := &http.Cookie{}
// The RFC makes no mention of encoding url value, so here I think to encode both sessionid key and the value using the safe(to put and to use as cookie) url-encoding
cookie.Name = s.config.Cookie
cookie.Value = sid
cookie.Path = "/"
cookie.HttpOnly = true
// MaxAge=0 means no 'Max-Age' attribute specified.
// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
// MaxAge>0 means Max-Age attribute present and given in seconds
if expires >= 0 {
if expires == 0 { // unlimited life
cookie.Expires = context.CookieExpireUnlimited
} else { // > 0
cookie.Expires = time.Now().Add(expires)
}
cookie.MaxAge = int(time.Until(cookie.Expires).Seconds())
}
s.upsertCookie(ctx, cookie, options)
}
func (s *Sessions) upsertCookie(ctx *context.Context, cookie *http.Cookie, cookieOptions []context.CookieOption) {
opts := s.cookieOptions
if len(cookieOptions) > 0 {
opts = append(opts, cookieOptions...)
}
ctx.UpsertCookie(cookie, opts...)
}
func (s *Sessions) getCookieValue(ctx *context.Context, cookieOptions []context.CookieOption) string {
c := s.getCookie(ctx, cookieOptions)
if c == nil {
return ""
}
return c.Value
}
func (s *Sessions) getCookie(ctx *context.Context, cookieOptions []context.CookieOption) *http.Cookie {
opts := s.cookieOptions
if len(cookieOptions) > 0 {
opts = append(opts, cookieOptions...)
}
cookie, err := ctx.GetRequestCookie(s.config.Cookie, opts...)
if err != nil {
return nil
}
cookie.Value, _ = url.QueryUnescape(cookie.Value)
return cookie
}
// Start creates or retrieves an existing session for the particular request.
// Note that `Start` method will not respect configuration's `AllowReclaim`, `DisableSubdomainPersistence`, `CookieSecureTLS`,
// and `Encoding` settings.
// Register sessions as a middleware through the `Handler` method instead,
// which provides automatic resolution of a *sessions.Session input argument
// on MVC and APIContainer as well.
//
// NOTE: Use `app.Use(sess.Handler())` instead, avoid using `Start` manually.
func (s *Sessions) Start(ctx *context.Context, cookieOptions ...context.CookieOption) *Session {
// cookieValue := s.getCookieValue(ctx, cookieOptions)
cookie := s.getCookie(ctx, cookieOptions)
if cookie != nil {
sid := cookie.Value
if sid == "" { // rare case: a client may contains a cookie with session name but with empty value.
// ctx.RemoveCookie(cookie.Name)
cookie = nil
} else if cookie.Expires.Add(time.Second).After(time.Now()) { // rare case: of custom clients that may hold expired cookies.
s.DestroyByID(sid)
// ctx.RemoveCookie(cookie.Name)
cookie = nil
} else {
// rare case: new expiration configuration that it's lower
// than the previous setting.
expiresTime := time.Now().Add(s.config.Expires)
if cookie.Expires.After(expiresTime) {
s.DestroyByID(sid)
// ctx.RemoveCookie(cookie.Name)
cookie = nil
} else {
// untilExpirationDur := time.Until(cookie.Expires)
// ^ this should be
return s.provider.Read(s, sid, s.config.Expires) // cookie exists and it's valid, let's return its session.
}
}
}
// Cookie doesn't exist, let's generate a session and set a cookie.
sid := s.config.SessionIDGenerator(ctx)
sess := s.provider.Init(s, sid, s.config.Expires)
// n := s.provider.db.Len(sid)
// fmt.Printf("db.Len(%s) = %d\n", sid, n)
// if n > 0 {
// s.provider.db.Visit(sid, func(key string, value interface{}) {
// fmt.Printf("%s=%s\n", key, value)
// })
// }
s.updateCookie(ctx, sid, s.config.Expires, cookieOptions...)
return sess
}
const sessionContextKey = "iris.session"
// Handler returns a sessions middleware to register on application routes.
// To return the request's Session call the `Get(ctx)` package-level function.
//
// Call `Handler()` once per sessions manager.
func (s *Sessions) Handler(requestOptions ...context.CookieOption) context.Handler {
return func(ctx *context.Context) {
session := s.Start(ctx, requestOptions...) // this cookie's end-developer's custom options.
ctx.Values().Set(sessionContextKey, session)
ctx.Next()
s.provider.EndRequest(ctx, session)
}
}
// Get returns a *Session from the same request life cycle,
// can be used inside a chain of handlers of a route.
//
// The `Sessions.Start` should be called previously,
// e.g. register the `Sessions.Handler` as middleware.
// Then call `Get` package-level function as many times as you want.
// Note: It will return nil if the session got destroyed by the same request.
// If you need to destroy and start a new session in the same request you need to call
// sessions manager's `Start` method after Destroy.
func Get(ctx *context.Context) *Session {
if v := ctx.Values().Get(sessionContextKey); v != nil {
if sess, ok := v.(*Session); ok {
return sess
}
}
// ctx.Application().Logger().Debugf("Sessions: Get: no session found, prior Destroy(ctx) calls in the same request should follow with a Start(ctx) call too")
return nil
}
// StartWithPath same as `Start` but it explicitly accepts the cookie path option.
func (s *Sessions) StartWithPath(ctx *context.Context, path string) *Session {
return s.Start(ctx, context.CookiePath(path))
}
// ShiftExpiration move the expire date of a session to a new date
// by using session default timeout configuration.
// It will return `ErrNotImplemented` if a database is used and it does not support this feature, yet.
func (s *Sessions) ShiftExpiration(ctx *context.Context, cookieOptions ...context.CookieOption) error {
return s.UpdateExpiration(ctx, s.config.Expires, cookieOptions...)
}
// UpdateExpiration change expire date of a session to a new date
// by using timeout value passed by `expires` receiver.
// It will return `ErrNotFound` when trying to update expiration on a non-existence or not valid session entry.
// It will return `ErrNotImplemented` if a database is used and it does not support this feature, yet.
func (s *Sessions) UpdateExpiration(ctx *context.Context, expires time.Duration, cookieOptions ...context.CookieOption) error {
cookieValue := s.getCookieValue(ctx, cookieOptions)
if cookieValue == "" {
return ErrNotFound
}
// we should also allow it to expire when the browser closed
err := s.provider.UpdateExpiration(cookieValue, expires)
if err == nil || expires == -1 {
s.updateCookie(ctx, cookieValue, expires, cookieOptions...)
}
return err
}
// DestroyListener is the form of a destroy listener.
// Look `OnDestroy` for more.
type DestroyListener func(sid string)
// OnDestroy registers one or more destroy listeners.
// A destroy listener is fired when a session has been removed entirely from the server (the entry) and client-side (the cookie).
// Note that if a destroy listener is blocking, then the session manager will delay respectfully,
// use a goroutine inside the listener to avoid that behavior.
func (s *Sessions) OnDestroy(listeners ...DestroyListener) {
for _, ln := range listeners {
s.provider.registerDestroyListener(ln)
}
}
// Destroy removes the session data, the associated cookie
// and the Context's session value.
// Next calls of `sessions.Get` will occur to a nil Session,
// use `Sessions#Start` method for renewal
// or use the Session's Destroy method which does keep the session entry with its values cleared.
func (s *Sessions) Destroy(ctx *context.Context) {
cookieValue := s.getCookieValue(ctx, nil)
if cookieValue == "" { // nothing to destroy
return
}
ctx.Values().Remove(sessionContextKey)
ctx.RemoveCookie(s.config.Cookie, s.cookieOptions...)
s.provider.Destroy(cookieValue)
}
// DestroyByID removes the session entry
// from the server-side memory (and database if registered).
// Client's session cookie will still exist but it will be reseted on the next request.
//
// It's safe to use it even if you are not sure if a session with that id exists.
//
// Note: the sid should be the original one (i.e: fetched by a store )
// it's not decoded.
func (s *Sessions) DestroyByID(sid string) {
s.provider.Destroy(sid)
}
// DestroyAll removes all sessions
// from the server-side memory (and database if registered).
// Client's session cookie will still exist but it will be reseted on the next request.
func (s *Sessions) DestroyAll() {
s.provider.DestroyAll()
}
| true |
719a666fab8daec3f477e246a2180e04668b75b4
|
Go
|
gessnerfl/terraform-provider-instana
|
/instana/restapi/sli-config-api_test.go
|
UTF-8
| 4,773 | 2.53125 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package restapi_test
import (
"testing"
. "github.com/gessnerfl/terraform-provider-instana/instana/restapi"
"github.com/stretchr/testify/assert"
)
const (
sliConfigID = "sli-config-id"
sliConfigName = "sli-config-name"
sliConfigInitialEvaluationTimestamp = 0
sliConfigMetricName = "sli-config-metric-name"
sliConfigMetricAggregation = "sli-config-metric-aggregation"
sliConfigMetricThreshold = 1.0
sliConfigEntityType = "application"
sliConfigEntityApplicationID = "sli-config-entity-application-id"
sliConfigEntityServiceID = "sli-config-entity-service-id"
sliConfigEntityEndpointID = "sli-config-entity-endpoint-id"
sliConfigEntityBoundaryScope = "ALL"
)
func TestMinimalSliConfig(t *testing.T) {
sliConfig := SliConfig{
ID: sliConfigID,
Name: sliConfigName,
MetricConfiguration: MetricConfiguration{
Name: sliConfigMetricName,
Aggregation: sliConfigMetricAggregation,
Threshold: sliConfigMetricThreshold,
},
SliEntity: SliEntity{
Type: sliConfigEntityType,
BoundaryScope: sliConfigEntityBoundaryScope,
},
}
assert.Equal(t, sliConfigID, sliConfig.GetIDForResourcePath())
err := sliConfig.Validate()
assert.Nil(t, err)
}
func TestValidFullSliConfig(t *testing.T) {
sliConfig := SliConfig{
ID: sliConfigID,
Name: sliConfigName,
InitialEvaluationTimestamp: sliConfigInitialEvaluationTimestamp,
MetricConfiguration: MetricConfiguration{
Name: sliConfigMetricName,
Aggregation: sliConfigMetricAggregation,
Threshold: sliConfigMetricThreshold,
},
SliEntity: SliEntity{
Type: sliConfigEntityType,
ApplicationID: sliConfigEntityApplicationID,
ServiceID: sliConfigEntityServiceID,
EndpointID: sliConfigEntityEndpointID,
BoundaryScope: sliConfigEntityBoundaryScope,
},
}
assert.Equal(t, sliConfigID, sliConfig.GetIDForResourcePath())
err := sliConfig.Validate()
assert.Nil(t, err)
}
func TestInvalidSliConfigBecauseOfMissingID(t *testing.T) {
sliConfig := SliConfig{
Name: sliConfigName,
}
err := sliConfig.Validate()
assert.NotNil(t, err)
assert.Contains(t, err.Error(), "id")
}
func TestInvalidSliConfigBecauseOfMissingName(t *testing.T) {
sliConfig := SliConfig{
ID: sliConfigID,
}
err := sliConfig.Validate()
assert.NotNil(t, err)
assert.Contains(t, err.Error(), "name")
}
func TestInvalidSliConfigBecauseOfMissingMetricName(t *testing.T) {
sliConfig := SliConfig{
ID: sliConfigID,
Name: sliConfigName,
}
err := sliConfig.Validate()
assert.NotNil(t, err)
assert.Contains(t, err.Error(), "metric name")
}
func TestInvalidSliConfigBecauseOfMissingMetricAggregation(t *testing.T) {
sliConfig := SliConfig{
ID: sliConfigID,
Name: sliConfigName,
MetricConfiguration: MetricConfiguration{
Name: sliConfigMetricName,
},
}
err := sliConfig.Validate()
assert.NotNil(t, err)
assert.Contains(t, err.Error(), "aggregation")
}
func TestInvalidSliConfigBecauseOfMissingMetricThreshold(t *testing.T) {
sliConfig := SliConfig{
ID: sliConfigID,
Name: sliConfigName,
MetricConfiguration: MetricConfiguration{
Name: sliConfigMetricName,
Aggregation: sliConfigMetricAggregation,
},
}
err := sliConfig.Validate()
assert.NotNil(t, err)
assert.Contains(t, err.Error(), "threshold")
}
func TestInvalidSliConfigBecauseOfInvalidMetricThreshold(t *testing.T) {
sliConfig := SliConfig{
ID: sliConfigID,
Name: sliConfigName,
MetricConfiguration: MetricConfiguration{
Name: sliConfigMetricName,
Aggregation: sliConfigMetricAggregation,
Threshold: -1.0,
},
}
err := sliConfig.Validate()
assert.NotNil(t, err)
assert.Contains(t, err.Error(), "threshold")
}
func TestInvalidSliConfigBecauseOfMissingSliEntityType(t *testing.T) {
sliConfig := SliConfig{
ID: sliConfigID,
Name: sliConfigName,
MetricConfiguration: MetricConfiguration{
Name: sliConfigMetricName,
Aggregation: sliConfigMetricAggregation,
Threshold: sliConfigMetricThreshold,
},
}
err := sliConfig.Validate()
assert.NotNil(t, err)
assert.Contains(t, err.Error(), "sli type")
}
func TestInvalidSliConfigBecauseOfMissingSliEntityBoundaryScope(t *testing.T) {
sliConfig := SliConfig{
ID: sliConfigID,
Name: sliConfigName,
MetricConfiguration: MetricConfiguration{
Name: sliConfigMetricName,
Aggregation: sliConfigMetricAggregation,
Threshold: sliConfigMetricThreshold,
},
SliEntity: SliEntity{
Type: sliConfigEntityType,
},
}
err := sliConfig.Validate()
assert.NotNil(t, err)
assert.Contains(t, err.Error(), "boundary scope")
}
| true |
f33dee7a7055d8eb3f697066eb08ec5ebbfe60ca
|
Go
|
cxuhua/xginx
|
/pow.go
|
UTF-8
| 1,442 | 2.515625 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package xginx
import (
"errors"
)
// CheckProofOfWork whether a block hash satisfies the proof-of-work requirement specified by nBits
func CheckProofOfWork(hash HASH256, bits uint32) bool {
h := UINT256{}
n, o := h.SetCompact(bits)
if n {
return false
}
if h.IsZero() {
return false
}
if o {
return false
}
if h.Cmp(conf.LimitHash) > 0 {
return false
}
ch := hash.ToU256()
return ch.Cmp(h) <= 0
}
//GetMinPowBits Minimum difficulty
func GetMinPowBits() uint32 {
return NewUINT256(conf.PowLimit).Compact(false)
}
//CheckProofOfWorkBits 检测难度值是否正确
func CheckProofOfWorkBits(bits uint32) bool {
h := UINT256{}
n, o := h.SetCompact(bits)
if n {
return false
}
if h.IsZero() {
return false
}
if o {
return false
}
return h.Cmp(conf.LimitHash) <= 0
}
//CalculateWorkRequired 计算工作难度
//ct = lastBlock blockTime
//pt = lastBlock - 2016 + 1 blockTime
//pw = lastBlock's bits
func CalculateWorkRequired(ct uint32, pt uint32, pw uint32) uint32 {
span := uint32(conf.PowTime)
limit := conf.LimitHash
sub := ct - pt
if sub <= 0 {
panic(errors.New("ct pt error"))
}
if sv := span / 4; sub < sv {
sub = sv
}
if sv := span * 4; sub > sv {
sub = sv
}
n := UINT256{}
n.SetCompact(pw)
n = n.MulUInt32(sub)
n = n.Div(NewUINT256(span))
if n.Cmp(limit) > 0 {
n = limit
}
return n.Compact(false)
}
| true |
d34084c369b2e26fcafcd945e9e0e3c5dff2d556
|
Go
|
richluby/analysis
|
/analysis.go
|
UTF-8
| 2,087 | 3.140625 | 3 |
[] |
no_license
|
[] |
no_license
|
// this package implements pretty printing of data
package main
import (
"flag"
"fmt"
"os"
"time"
)
// Set at compile time
var (
Version string
BuildTime string
)
var config ConfigCLI
// displays the help and exits the program
func printHelp() {
fmt.Printf("\nData presenter, Version %s, Build %s\n", Version, BuildTime)
fmt.Printf("Usage: %s [options] [csv_files]\n", os.Args[0])
flag.PrintDefaults()
os.Exit(0)
}
// initializes the command-line arguments for the progam
func initCLIArgs() ConfigCLI {
config := ConfigCLI{}
// informational args
flag.Usage = printHelp
flag.StringVar(&config.DatabaseFile, "database", "data/transaction.db", "the sqlite3 file that contains the transactions")
// date/time args
defaultInterval := time.Duration(3) * time.Hour * 24
flag.StringVar(&config.StartDate, "start-date", "", "the first date to include the display")
flag.StringVar(&config.EndDate, "end-date", "", "the last date to include the display")
flag.DurationVar(&config.Interval, "time-slice", defaultInterval, "the interval at which to aggregate disparate data points for graphing. accepts any format parsable by time.ParseDuration")
// performance args
flag.IntVar(&config.MaxBufferedTransactions, "max-buffer", 5000, "the maximum number of transactions to buffer in memory while reading CSV entries")
// Output args
flag.StringVar(&config.OutputDirectory, "out", "output", "the directory in which to save output")
flag.StringVar(&config.GraphTypes, "graphs", "", "the comma-delimited list of graphs to create")
flag.StringVar(&config.Categories, "category", "", "the list of categories to include in the analysis")
// helper args
flag.BoolVar(&config.Version, "version", false, "print version information and exit")
flag.Parse()
config.CSV = flag.Args()
return config
}
// the entry point of the program
func main() {
config = initCLIArgs()
if config.Version {
printHelp()
}
transactionChannel := make(chan Transaction, config.MaxBufferedTransactions)
go readData(config.CSV, transactionChannel)
initDB()
enterData(transactionChannel)
}
| true |
4c0e7d122d8e20ba75cfbf2b2e8856608efee07c
|
Go
|
infoslack/coinmarketcap
|
/marketcap.go
|
UTF-8
| 1,190 | 2.890625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
)
const apiURL = "https://api.coinmarketcap.com/v1/ticker/"
type Coin struct {
ID string `json:"id"`
Name string `json:"name"`
Symbol string `json:"symbol"`
Rank string `json:"rank"`
PriceUsd string `json:"price_usd"`
PriceBtc string `json:"price_btc"`
Two4HVolumeUsd string `json:"24h_volume_usd"`
MarketCapUsd string `json:"market_cap_usd"`
AvailableSupply string `json:"available_supply"`
TotalSupply string `json:"total_supply"`
MaxSupply string `json:"max_supply"`
PercentChange1H string `json:"percent_change_1h"`
PercentChange24H string `json:"percent_change_24h"`
PercentChange7D string `json:"percent_change_7d"`
LastUpdated string `json:"last_updated"`
}
func getCoins(name string) Coin {
resp, err := http.Get(apiURL + name + "/")
if err != nil {
log.Fatalf("Error retrieving data: %s\n", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Error reading data: %s\n", err)
}
var coin []Coin
json.Unmarshal(body, &coin)
return coin[0]
}
| true |
9dafbfa44f1b0cdc012efba1bf35a3f501364293
|
Go
|
chenqi146/code
|
/easy/IntReverse.go
|
UTF-8
| 316 | 3.578125 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"math"
)
func reverse(x int) int {
temp := 0
for x != 0 {
// 每次乘10且加上取余数
temp = temp*10 + x%10
x = x / 10
// 判断是否溢出
if temp < math.MinInt32 || temp > math.MaxInt32 {
return 0
}
}
return temp
}
func main() {
fmt.Print(reverse(123))
}
| true |
1d0a68ce72de58e0100716b5b629e575b211538e
|
Go
|
trungtran1512/golang-training
|
/week1-exercise/helper/slice_test.go
|
UTF-8
| 1,436 | 3.375 | 3 |
[] |
no_license
|
[] |
no_license
|
package helper
import (
"reflect"
"testing"
)
func TestLast(t *testing.T) {
arr := []int{1, 2, 3}
actual := Last(arr)
var expected int
expected = 3
if actual != expected {
t.Error("Value should be ", expected)
}
}
func TestFilter(t *testing.T) {
// _.filter(users, function(o) { return !o.active; });
t.Run("Filter with Func", func(t *testing.T) {
arr := []int{1, 2, 3}
actual := Filter(arr, func(ele int) bool {
return ele%2 == 0
})
expected := []int{2}
if !reflect.DeepEqual(expected, actual) {
t.Error("Value should be ", expected)
}
})
// _.filter(users, 'active');
t.Run("Filter with Field", func(t *testing.T) {
type User struct {
Name string
Age int
Active bool
}
users := []User{
User{"barney", 36, true},
User{"fred", 40, false},
}
actual := Filter(users, "Active")
expected := []User{
User{"barney", 36, true},
}
if !reflect.DeepEqual(expected, actual) {
t.Error("Value should be ", expected)
}
})
// _.filter(users, ['active', false]);
t.Run("Filter with Field", func(t *testing.T) {
type User struct {
Name string
Age int
Active bool
}
users := []User{
User{"barney", 36, true},
User{"fred", 40, false},
}
actual := Filter(users, []interface{}{"Active", false})
expected := []User{
User{"fred", 40, false},
}
if !reflect.DeepEqual(expected, actual) {
t.Error("Value should be ", expected)
}
})
}
| true |
5a177298dddfb76a2a0f446ba417e9914a267702
|
Go
|
TorChrEriksen/TTK4145
|
/Exercise_6/main.go
|
UTF-8
| 5,458 | 3.03125 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import(
"fmt"
"os"
"os/signal"
"os/exec"
"time"
"syscall"
"strconv"
"bufio"
"strings"
)
const (
SECONDARY = 0
PRIMARY = 1
)
const (
NO_INFO = 0
INFO = 1
)
var PRINT_INFO bool = false
var TIMEOUT = time.Duration(time.Second * 5)
// Only for debugging/testing
func killProc() {
proc, err := os.FindProcess(os.Getpid())
if err != nil {
fmt.Println(err.Error())
return
}
err = proc.Kill()
if err != nil {
fmt.Println(err.Error())
return
}
}
func takeOver() {
spawn, err := spawnCopy()
if err != nil {
fmt.Println(err.Error())
os.Exit(0)
}
go continueOperation()
ch := make(chan int)
go notifyAlive(spawn, ch)
if PRINT_INFO {
fmt.Println("Secondary is now Primary")
}
for i := range ch {
fmt.Println(i)
}
}
func waitForAlive(waiter chan int) {
if PRINT_INFO {
fmt.Println("waitforAlive")
}
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGHUP)
timer := time.NewTimer(TIMEOUT)
go func() {
<-timer.C
if PRINT_INFO {
fmt.Println("Timer Expired, Secondary is taking over")
}
close(ch)
takeOver()
}()
for sig := range ch {
if PRINT_INFO {
fmt.Println("Signal received: ", sig)
} else {
_ = sig
}
timer.Reset(TIMEOUT)
}
}
func spawnCopy() (*os.Process, error) {
if PRINT_INFO {
fmt.Println("Spawning copy of ourself")
}
argv := []string{os.Args[0], strconv.Itoa(SECONDARY), os.Args[2]}
attr := new(os.ProcAttr)
attr.Files = []*os.File{nil, os.Stdout, os.Stderr}
proc, err := os.StartProcess("main", argv, attr)
return proc, err
}
func notifyAlive(p *os.Process, waiter chan int) {
for {
if PRINT_INFO {
fmt.Println("Notifying")
}
time.Sleep(time.Second)
p.Signal(syscall.SIGHUP)
}
}
func operate() {
var i int = 0
pwd, err := os.Getwd()
if err != nil {
fmt.Println("Error: ", err.Error())
return
}
app := "sh"
arg0 := pwd + "/test.sh"
for {
i++
arg1 := strconv.Itoa(i)
cmd := exec.Command(app, arg0, arg1)
_, err := cmd.Output()
if err != nil {
fmt.Println("Error: ", err.Error())
}
fmt.Println(i)
time.Sleep(time.Second)
}
}
func continueOperation() {
// Read last operation from file
file, err := os.Open("testfile")
if err != nil {
fmt.Println("Error: ", err.Error())
}
reader := bufio.NewReader(file)
lastValue, _ := reader.ReadString('\n')
lastValue = strings.Trim(lastValue, "\n")
i, err := strconv.Atoi(lastValue)
if err != nil {
fmt.Println("Error: ", err.Error())
}
pwd, err := os.Getwd()
if err != nil {
fmt.Println("Error: ", err.Error())
return
}
app := "sh"
arg0 := pwd + "/test.sh"
for {
i++
arg1 := strconv.Itoa(i)
cmd := exec.Command(app, arg0, arg1)
_, err := cmd.Output()
if err != nil {
fmt.Println("Error: ", err.Error())
}
fmt.Println(i)
time.Sleep(time.Second)
}
}
func main() {
// fmt.Println("Welcome to the redundant Go app...")
// fmt.Println(len(os.Args), os.Args)
if len(os.Args) == 3 {
arg1, err1 := strconv.Atoi(os.Args[1])
arg2, err2 := strconv.Atoi(os.Args[2])
if err1 != nil {
fmt.Println("Invalid argument (1)")
os.Exit(0)
} else if err2 != nil {
fmt.Println("Invalid argument (2)")
os.Exit(0)
} else {
if arg1 == PRIMARY {
if arg2 == NO_INFO {
PRINT_INFO = false
} else if arg2 == INFO {
PRINT_INFO = true
} else {
fmt.Println("Invalid argument (2)")
os.Exit(0)
}
if PRINT_INFO {
fmt.Println("Primary")
}
spawn, err := spawnCopy()
if err != nil {
fmt.Println(err.Error())
os.Exit(0)
}
// Nasty that program is still alive if main thread dies?
ch := make(chan int)
go notifyAlive(spawn, ch)
go operate()
for i := range ch {
fmt.Println(i)
}
} else if arg1 == SECONDARY {
if arg2 == NO_INFO {
PRINT_INFO = false
} else if arg2 == INFO {
PRINT_INFO = true
} else {
fmt.Println("Invalid argument (2)")
os.Exit(0)
}
if PRINT_INFO {
fmt.Println("Secondary")
}
ch := make(chan int)
go waitForAlive(ch)
for i := range ch {
fmt.Println(i)
}
} else {
fmt.Println("Invalid argument (1)")
os.Exit(0)
}
}
} else {
fmt.Println("Invalid number of arguments")
os.Exit(0)
}
}
| true |
7490365a3c8521eaeabe90a91fff803b6453b6f0
|
Go
|
spf13/afero
|
/zipfs/zipfs_test.go
|
UTF-8
| 2,653 | 3.03125 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package zipfs
import (
"archive/zip"
"path/filepath"
"reflect"
"testing"
"github.com/spf13/afero"
)
func TestZipFS(t *testing.T) {
zrc, err := zip.OpenReader("testdata/t.zip")
if err != nil {
t.Fatal(err)
}
zfs := New(&zrc.Reader)
a := &afero.Afero{Fs: zfs}
buf, err := a.ReadFile("testFile")
if err != nil {
t.Error(err)
}
if len(buf) != 8192 {
t.Errorf("short read: %d != 8192", len(buf))
}
buf = make([]byte, 8)
f, err := a.Open("testFile")
if err != nil {
t.Error(err)
}
if n, err := f.ReadAt(buf, 4092); err != nil {
t.Error(err)
} else if n != 8 {
t.Errorf("expected to read 8 bytes, got %d", n)
} else if string(buf) != "aaaabbbb" {
t.Errorf("expected to get <aaaabbbb>, got <%s>", string(buf))
}
d, err := a.Open("/")
if d == nil {
t.Error(`Open("/") returns nil`)
}
if err != nil {
t.Errorf(`Open("/"): err = %v`, err)
}
if s, _ := d.Stat(); !s.IsDir() {
t.Error(`expected root ("/") to be a directory`)
}
if n := d.Name(); n != string(filepath.Separator) {
t.Errorf("Wrong Name() of root directory: Expected: '%c', got '%s'", filepath.Separator, n)
}
buf = make([]byte, 8192)
if n, err := f.Read(buf); err != nil {
t.Error(err)
} else if n != 8192 {
t.Errorf("expected to read 8192 bytes, got %d", n)
} else if buf[4095] != 'a' || buf[4096] != 'b' {
t.Error("got wrong contents")
}
for _, s := range []struct {
path string
dir bool
}{
{"/", true},
{"testDir1", true},
{"testDir1/testFile", false},
{"testFile", false},
{"sub", true},
{"sub/testDir2", true},
{"sub/testDir2/testFile", false},
} {
if dir, _ := a.IsDir(s.path); dir == s.dir {
t.Logf("%s: directory check ok", s.path)
} else {
t.Errorf("%s: directory check NOT ok: %t, expected %t", s.path, dir, s.dir)
}
}
for _, s := range []struct {
glob string
entries []string
}{
{filepath.FromSlash("/*"), []string{filepath.FromSlash("/sub"), filepath.FromSlash("/testDir1"), filepath.FromSlash("/testFile")}},
{filepath.FromSlash("*"), []string{filepath.FromSlash("sub"), filepath.FromSlash("testDir1"), filepath.FromSlash("testFile")}},
{filepath.FromSlash("sub/*"), []string{filepath.FromSlash("sub/testDir2")}},
{filepath.FromSlash("sub/testDir2/*"), []string{filepath.FromSlash("sub/testDir2/testFile")}},
{filepath.FromSlash("testDir1/*"), []string{filepath.FromSlash("testDir1/testFile")}},
} {
entries, err := afero.Glob(zfs, s.glob)
if err != nil {
t.Error(err)
}
if reflect.DeepEqual(entries, s.entries) {
t.Logf("glob: %s: glob ok", s.glob)
} else {
t.Errorf("glob: %s: got %#v, expected %#v", s.glob, entries, s.entries)
}
}
}
| true |
7e762c5b05b12b1899841dbe10eb493118ab88c3
|
Go
|
m3db/m3
|
/src/query/graphite/native/summarize_test.go
|
UTF-8
| 6,093 | 2.515625 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
// Copyright (c) 2019 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package native
import (
"testing"
"time"
"github.com/m3db/m3/src/query/graphite/common"
"github.com/m3db/m3/src/query/graphite/ts"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestSummarize(t *testing.T) {
// NB(mmihic): Intentionally not aligned on summarization boundaries
var (
start = time.Unix(131, 0)
end = time.Unix(251, 0)
ctx = common.NewContext(common.ContextOptions{Start: start, End: end})
vals = ts.NewValues(ctx, 10000, 12)
series = []*ts.Series{ts.NewSeries(ctx, "foo", start, vals)}
)
defer ctx.Close()
// 0+1+2
// 3+4+5
// 6+7+8
// 9+10+11
for i := 0; i < vals.Len(); i++ {
vals.SetValueAt(i, float64(i))
}
tests := []struct {
name string
interval string
fname string
alignToFrom bool
expectedStart time.Time
expectedEnd time.Time
expectedVals []float64
}{
{"summarize(foo, \"30s\", \"sum\")", "30s", "", false,
time.Unix(120, 0), time.Unix(270, 0),
[]float64{1, 9, 18, 27, 11},
},
{"summarize(foo, \"30s\", \"sum\", true)", "30s", "", true,
start, end,
[]float64{3, 12, 21, 30},
},
{"summarize(foo, \"1min\", \"sum\")", "1min", "", false,
time.Unix(120, 0), time.Unix(300, 0),
[]float64{10, 45, 11},
},
{"summarize(foo, \"1min\", \"sum\", true)", "1min", "", true,
start, end,
[]float64{15, 51},
},
{"summarize(foo, \"1min\", \"avg\")", "1min", "avg", false,
time.Unix(120, 0), time.Unix(300, 0),
[]float64{2, 7.5, 11},
},
{"summarize(foo, \"1min\", \"last\")", "1min", "last", false,
start.Truncate(time.Minute), end.Truncate(time.Minute).Add(time.Minute),
[]float64{4, 10, 11},
},
}
for _, test := range tests {
outSeries, err := summarize(ctx, singlePathSpec{
Values: series,
}, test.interval, test.fname, test.alignToFrom)
require.NoError(t, err)
require.Equal(t, 1, len(outSeries.Values))
out := outSeries.Values[0]
assert.Equal(t, test.name, out.Name(), "incorrect name for %s", test.name)
assert.Equal(t, test.expectedStart, out.StartTime(), "incorrect start for %s", test.name)
assert.Equal(t, test.expectedEnd, out.EndTime(), "incorrect end for %s", test.name)
require.Equal(t, len(test.expectedVals), out.Len(), "incorrect len for %s", test.name)
for i := 0; i < out.Len(); i++ {
assert.Equal(t, test.expectedVals[i], out.ValueAt(i), "incorrect val %d for %s", i, test.name)
}
}
_, err := summarize(ctx, singlePathSpec{
Values: series,
}, "0min", "avg", false)
require.Error(t, err)
}
func TestSmartSummarize(t *testing.T) {
var (
start = time.Unix(131, 0)
end = time.Unix(251, 0)
ctx = common.NewContext(common.ContextOptions{Start: start, End: end})
vals = ts.NewValues(ctx, 10000, 12)
series = []*ts.Series{ts.NewSeries(ctx, "foo", start, vals)}
)
defer ctx.Close()
// 0+1+2
// 3+4+5
// 6+7+8
// 9+10+11
for i := 0; i < vals.Len(); i++ {
vals.SetValueAt(i, float64(i))
}
tests := []struct {
name string
interval string
fname string
expectedStart time.Time
expectedEnd time.Time
expectedVals []float64
}{
{"smartSummarize(foo, \"30s\", \"sum\")",
"30s",
"",
start, end,
[]float64{3, 12, 21, 30},
},
{"smartSummarize(foo, \"1min\", \"sum\")",
"1min",
"",
start,
end,
[]float64{15, 51},
},
{"smartSummarize(foo, \"40s\", \"median\")",
"40s",
"median",
start,
end,
[]float64{1.5, 5.5, 9.5},
},
{"smartSummarize(foo, \"30s\", \"median\")",
"30s",
"median",
start,
end,
[]float64{1, 4, 7, 10},
},
}
for _, test := range tests {
outSeries, err := smartSummarize(ctx, singlePathSpec{
Values: series,
}, test.interval, test.fname)
require.NoError(t, err)
require.Equal(t, 1, len(outSeries.Values))
out := outSeries.Values[0]
assert.Equal(t, test.name, out.Name(), "incorrect name for %s", test.name)
assert.Equal(t, test.expectedStart, out.StartTime(), "incorrect start for %s", test.name)
assert.Equal(t, test.expectedEnd, out.EndTime(), "incorrect end for %s", test.name)
require.Equal(t, len(test.expectedVals), out.Len(), "incorrect len for %s", test.name)
for i := 0; i < out.Len(); i++ {
assert.Equal(t, test.expectedVals[i], out.ValueAt(i), "incorrect val %d for %s", i, test.name)
}
}
_, err := smartSummarize(ctx, singlePathSpec{
Values: series,
}, "0min", "avg")
require.Error(t, err)
}
func TestSummarizeInvalidInterval(t *testing.T) {
var (
start = time.Unix(131, 0)
end = time.Unix(251, 0)
ctx = common.NewContext(common.ContextOptions{Start: start, End: end})
vals = ts.NewValues(ctx, 10000, 12)
series = []*ts.Series{ts.NewSeries(ctx, "foo", start, vals)}
)
defer ctx.Close()
_, err := summarize(ctx, singlePathSpec{
Values: series,
}, "0min", "avg", false)
require.Error(t, err)
_, err = summarize(ctx, singlePathSpec{
Values: series,
}, "-1hour", "avg", false)
require.Error(t, err)
}
| true |
dd86b46938b35b647f79a2ae8e10694c3f0e419e
|
Go
|
justxuewei/rpc-demos
|
/rpcctx/hello_service.go
|
UTF-8
| 626 | 2.859375 | 3 |
[] |
no_license
|
[] |
no_license
|
package rpcctx
import (
"fmt"
"log"
"net"
)
type HelloService struct {
conn net.Conn
isLogin bool
}
func NewHelloService(conn net.Conn) *HelloService {
return &HelloService{
conn: conn,
isLogin: false,
}
}
func (p *HelloService) Login(request string, reply *string) error {
if request != "usr:pwd" {
return fmt.Errorf("auth failed")
}
log.Println("login ok")
p.isLogin = true
return nil
}
func (p *HelloService) Hello(request string, reply *string) error {
if !p.isLogin {
return fmt.Errorf("please login")
}
*reply = "hello: " + request + ", from " + p.conn.RemoteAddr().String()
return nil
}
| true |
280f196de035dd1c03f3c8bb915f698c1c471f45
|
Go
|
tidepool-org/platform
|
/test/closer.go
|
UTF-8
| 612 | 3.234375 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
[
"BSD-2-Clause"
] |
permissive
|
package test
type Closer struct {
CloseInvocations int
CloseStub func() error
CloseOutputs []error
CloseOutput *error
}
func NewCloser() *Closer {
return &Closer{}
}
func (c *Closer) Close() error {
c.CloseInvocations++
if c.CloseStub != nil {
return c.CloseStub()
}
if len(c.CloseOutputs) > 0 {
output := c.CloseOutputs[0]
c.CloseOutputs = c.CloseOutputs[1:]
return output
}
if c.CloseOutput != nil {
return *c.CloseOutput
}
panic("Close has no output")
}
func (c *Closer) AssertOutputsEmpty() {
if len(c.CloseOutputs) > 0 {
panic("CloseOutputs is not empty")
}
}
| true |
45fa4776c41b5eaedb5918a695e758ad09711975
|
Go
|
ViBiOh/mailer
|
/pkg/model/mail_test.go
|
UTF-8
| 2,491 | 3.390625 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package model
import (
"errors"
"strings"
"testing"
)
func noop() {
// Do nothing
}
func TestCheck(t *testing.T) {
t.Parallel()
cases := map[string]struct {
instance MailRequest
wantErr error
}{
"empty": {
NewMailRequest(),
errors.New("from email is required"),
},
"no recipients": {
NewMailRequest().From("[email protected]"),
errors.New("recipients are required"),
},
"empty recipients": {
NewMailRequest().From("[email protected]").To("[email protected]", "").To("[email protected]"),
errors.New("recipient at index 1 is empty"),
},
"empty template": {
NewMailRequest().From("[email protected]").To("[email protected]"),
errors.New("template name is required"),
},
"valid": {
NewMailRequest().From("[email protected]").To("[email protected]").WithSubject("test").Template("test"),
nil,
},
}
for intention, testCase := range cases {
intention, testCase := intention, testCase
t.Run(intention, func(t *testing.T) {
t.Parallel()
gotErr := testCase.instance.Check()
failed := false
if testCase.wantErr == nil && gotErr != nil {
failed = true
} else if testCase.wantErr != nil && gotErr == nil {
failed = true
} else if testCase.wantErr != nil && !strings.Contains(gotErr.Error(), testCase.wantErr.Error()) {
failed = true
}
if failed {
t.Errorf("Check() = `%s`, want `%s`", gotErr, testCase.wantErr)
}
})
}
}
func TestGetSubject(t *testing.T) {
t.Parallel()
type args struct {
subject string
payload any
}
cases := map[string]struct {
args args
want string
}{
"simple": {
args{
subject: "All is fine",
payload: map[string]any{
"Name": noop,
},
},
"All is fine",
},
"invalid template": {
args{
subject: "All is fine {{-. toto}",
payload: map[string]any{
"Name": noop,
},
},
"All is fine {{-. toto}",
},
"invalid exec": {
args{
subject: "All is fine Mr {{ .Name.Test }}",
payload: map[string]any{
"Name": noop,
},
},
"All is fine Mr {{ .Name.Test }}",
},
"valid exec": {
args{
subject: "All is fine Mr {{ .Name }}",
payload: map[string]any{
"Name": "Test",
},
},
"All is fine Mr Test",
},
}
for intention, testCase := range cases {
intention, testCase := intention, testCase
t.Run(intention, func(t *testing.T) {
t.Parallel()
if got := getSubject(testCase.args.subject, testCase.args.payload); got != testCase.want {
t.Errorf("getSubject() = `%s`, want `%s`", got, testCase.want)
}
})
}
}
| true |
bb994cfeb248dc9c3dd433c67686c4b3378c177f
|
Go
|
harryge00/myGo
|
/closeChanWithContext.go
|
UTF-8
| 900 | 3.390625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"context"
"log"
"sync"
"time"
)
func main() {
ctx, _ := context.WithCancel(context.Background())
wg := sync.WaitGroup{}
wg.Add(3)
stopCh := make(chan struct{})
go func() {
defer wg.Done()
for {
select {
case <-stopCh:
log.Println("Close stopCh 1")
return
// msg from other goroutine finish
case <-ctx.Done():
// end
log.Println("Close 1")
return
}
}
}()
go func() {
defer wg.Done()
for {
select {
case <-stopCh:
log.Println("Close stopCh 2")
return
// msg from other goroutine finish
case <-ctx.Done():
// end
log.Println("Close 2")
return
}
}
}()
go func() {
defer wg.Done()
// your operation
// call cancel when this goroutine ends
log.Println("Sleep 3")
time.Sleep(3 * time.Second)
log.Println("Going to cancel")
//cancel()
close(stopCh)
}()
wg.Wait()
}
| true |
bff224b75891b17b4e66eb56e7bf3ec377aedd32
|
Go
|
grebnetiew/aoc2017
|
/10/puzzle10b.go
|
UTF-8
| 1,275 | 3.515625 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"bufio"
"fmt"
"os"
)
type CircList []int
func (l CircList) reverse(begin, length int) {
for i := 0; i < length/2; i++ {
temp := l.get(begin + i)
l.set(begin+i, l.get(begin+length-i-1))
l.set(begin+length-i-1, temp)
}
}
func (l CircList) get(idx int) int {
return l[idx%len(l)]
}
func (l CircList) set(idx, val int) {
l[idx%len(l)] = val
}
func main() {
r := bufio.NewReader(os.Stdin)
for {
bytes, err := r.ReadBytes('\n')
if err != nil {
fmt.Println(err)
break
}
// The last one is now '\n', so..
arbitrarySuffix := []byte{17, 31, 73, 47, 23}
bytes = append(bytes[0:len(bytes)-1], arbitrarySuffix...)
hash := knotHash(bytes)
for i := 0; i < 16; i++ {
fmt.Printf("%02x", hash[i])
}
fmt.Println()
}
}
func knotHash(bytes []byte) []int {
var circList CircList = make([]int, 256)
for i := range circList {
circList[i] = i
}
// The 64 hashes
var cursor, skipSize int
for i := 0; i < 64; i++ {
for _, v := range bytes {
length := int(v)
circList.reverse(cursor, length)
cursor += skipSize + length
skipSize++
}
}
// Now reduce it
denseHash := make([]int, 16)
for i := 0; i < 16; i++ {
for j := 0; j < 16; j++ {
denseHash[i] ^= circList[16*i+j]
}
}
return denseHash
}
| true |
d10de2fb8caf4d15b8540eb7853fddcff70208b2
|
Go
|
RyazMax/SuperSet
|
/src/auth/simple_auth.go
|
UTF-8
| 2,281 | 3.078125 | 3 |
[] |
no_license
|
[] |
no_license
|
package auth
import (
"log"
"golang.org/x/crypto/bcrypt"
"../models"
"../repos/session"
"../repos/user"
"github.com/google/uuid"
)
// SimpleAuth simple implementation of auth
type SimpleAuth struct {
userRepo user.Repo
sessionRepo session.Repo
}
// Init inits
func (auth *SimpleAuth) Init(ur user.Repo, sr session.Repo) error {
auth.userRepo = ur
auth.sessionRepo = sr
// For testing
auth.NewUser(&models.User{Login: "User", PasswordShadow: "user"})
return nil
}
// Login logins
func (auth *SimpleAuth) Login(login string, pass string) (*models.Session, error) {
user, err := auth.userRepo.GetByLogin(login)
if err != nil {
log.Println("Can't login", err)
return nil, err
}
if user == nil || bcrypt.CompareHashAndPassword([]byte(user.PasswordShadow), []byte(pass)) != nil {
return nil, nil
}
session := &models.Session{ID: uuid.New().String(), UserLogin: login}
err = auth.sessionRepo.Insert(session)
if err != nil {
log.Println("Can't login", err)
return nil, err
}
return session, nil
}
// Logout logouts
func (auth *SimpleAuth) Logout(id string) error {
err := auth.sessionRepo.DeleteByID(id)
if err != nil {
log.Println("Can't logout", err)
}
return err
}
// CheckSession checks
func (auth *SimpleAuth) CheckSession(id string) (*models.Session, error) {
sess, err := auth.sessionRepo.GetByID(id)
if err != nil {
log.Println("Can't check session", err)
return nil, err
}
return sess, nil
}
// NewUser new user
func (auth *SimpleAuth) NewUser(u *models.User) (*models.Session, error) {
u.ID = uint(uuid.New().ID())
pass, err := bcrypt.GenerateFromPassword([]byte(u.PasswordShadow), 6)
if err != nil {
log.Println("Can't create user", err)
return nil, err
}
u.PasswordShadow = string(pass)
err = auth.userRepo.Insert(u)
if err != nil {
log.Println("Can't create user", err)
return nil, err
}
session := &models.Session{ID: uuid.New().String(), UserLogin: u.Login}
err = auth.sessionRepo.Insert(session)
if err != nil {
log.Println("Can't login", err)
return nil, err
}
return session, nil
}
// DeleteUser deletes
func (auth *SimpleAuth) DeleteUser(login string) error {
err := auth.userRepo.DeleteByLogin(login)
if err != nil {
log.Println("Can't delete", err)
}
return err
}
| true |
74695232d7d9f99f6605b8bc908bafda0293b172
|
Go
|
filecoin-project/specs-actors
|
/actors/util/math/ln_test.go
|
UTF-8
| 1,798 | 2.8125 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
package math_test
import (
"fmt"
"testing"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/specs-actors/v8/actors/util/math"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNaturalLog(t *testing.T) {
lnInputs := math.Parse([]string{
"340282366920938463463374607431768211456", // Q.128 format of 1
"924990000000000000000000000000000000000", // Q.128 format of e (rounded up in 5th decimal place to handle truncation)
"34028236692093846346337460743176821145600000000000000000000", // Q.128 format of 100e18
"6805647338418769269267492148635364229120000000000000000000000", // Q.128 format of 2e22
"204169000000000000000000000000000000", // Q.128 format of 0.0006
"34028236692093846346337460743", // Q.128 format of 1e-10
})
expectedLnOutputs := math.Parse([]string{
"0", // Q.128 format of 0 = ln(1)
"340282366920938463463374607431768211456", // Q.128 format of 1 = ln(e)
"15670582109617661336106769654068947397831", // Q.128 format of 46.051... = ln(100e18)
"17473506083804940763855390762239996622013", // Q.128 format of 51.35... = ln(2e22)
"-2524410000000000000000000000000000000000", // Q.128 format of -7.41.. = ln(0.0006)
"-7835291054808830668053384827034473698915", // Q.128 format of -23.02.. = ln(1e-10)
})
fmt.Printf("%v %v\n", lnInputs, expectedLnOutputs)
require.Equal(t, len(lnInputs), len(expectedLnOutputs))
for i := 0; i < len(lnInputs); i++ {
z := big.NewFromGo(lnInputs[i])
lnOfZ := math.Ln(z)
expectedZ := big.NewFromGo(expectedLnOutputs[i])
assert.Equal(t, big.Rsh(expectedZ, math.Precision128), big.Rsh(lnOfZ, math.Precision128), "failed ln of %v", z)
}
}
| true |
a345248d09d431820cd8e8b4863e361c81c77bd0
|
Go
|
askeladdk/cube
|
/cfg.go
|
UTF-8
| 2,431 | 2.984375 | 3 |
[] |
no_license
|
[] |
no_license
|
package cube
func reachable(root *BasicBlock, blocks []*BasicBlock) []*BasicBlock {
visited := map[*BasicBlock]struct{}{}
var result []*BasicBlock
var recurse func(*BasicBlock)
recurse = func(blk *BasicBlock) {
if _, hasvisited := visited[blk]; !hasvisited {
visited[blk] = struct{}{}
result = append(result, blk)
for _, succ := range blk.successors {
if succ != nil {
recurse(succ)
}
}
}
}
recurse(root)
return result
}
func predecessors(blocks []*BasicBlock) []*BasicBlock {
for _, blk := range blocks {
blk.predecessors = nil
}
for _, blk := range blocks {
s0 := blk.successors[0]
s1 := blk.successors[1]
if s0 != nil {
s0.predecessors = append(s0.predecessors, blk)
}
if s1 != nil && s0 != s1 {
s1.predecessors = append(s1.predecessors, blk)
}
}
return blocks
}
// tarjan's strongly connected components algorithm
func topologicalSort(blocks []*BasicBlock) []*BasicBlock {
var stack []*BasicBlock
var result []*BasicBlock
index := 0
onstack := map[*BasicBlock]struct{}{}
lowlinks := map[*BasicBlock]int{}
indices := map[*BasicBlock]int{}
var strongconnect func(*BasicBlock)
strongconnect = func(blk *BasicBlock) {
indices[blk] = index
lowlinks[blk] = index
onstack[blk] = struct{}{}
stack = append(stack, blk)
index += 1
for _, succ := range blk.successors {
if succ == nil {
continue
} else if _, visited := indices[succ]; !visited {
strongconnect(succ)
if lowlinks[succ] < lowlinks[blk] {
lowlinks[blk] = lowlinks[succ]
}
} else if _, isonstack := onstack[succ]; isonstack {
if indices[succ] < lowlinks[blk] {
lowlinks[blk] = indices[succ]
}
}
}
sccomponent := 0
if lowlinks[blk] == indices[blk] {
var item *BasicBlock
end := len(stack)
for ok := true; ok; ok = item != blk {
end -= 1
item = stack[end]
item.sccomponent = sccomponent
result = append(result, item)
delete(onstack, item)
}
stack = stack[:end]
sccomponent += 1
}
}
for _, blk := range blocks {
if _, visited := indices[blk]; !visited {
strongconnect(blk)
}
}
for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 {
result[i], result[j] = result[j], result[i]
}
return result
}
func Pass_BuildCFG(proc *Procedure) *Procedure {
blks1 := reachable(proc.entryPoint, proc.blocks)
blks2 := predecessors(blks1)
proc.blocks = topologicalSort(blks2)
return proc
}
| true |
cc88737f8b593db241d8e06c9b20ed40698f261e
|
Go
|
sunshu/learn_go_baisc
|
/demo01/201goSql/mysql/sqldemo.go
|
UTF-8
| 365 | 2.6875 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
type DbWorker struct {
//mysql data source name
Dsn string
}
func main() {
dbw := DbWorker{
Dsn: "root:root@tcp(123.206.95.89:3306)/user",
}
db, err := sql.Open("mysql",
dbw.Dsn)
if err != nil {
panic(err)
return
}
fmt.Println("打开成功")
defer db.Close()
}
| true |
78a26ce4e6c938a16718154bae71a8907cd0848d
|
Go
|
stakater/jx-release-version
|
/main_test.go
|
UTF-8
| 3,368 | 2.53125 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package main
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestMakefile(t *testing.T) {
c := config{
dir: "test-resources/make",
}
v, err := getVersion(c)
assert.NoError(t, err)
assert.Equal(t, "1.2.0-SNAPSHOT", v, "error with getVersion for a Makefile")
}
func TestPomXML(t *testing.T) {
c := config{
dir: "test-resources/java",
}
v, err := getVersion(c)
assert.NoError(t, err)
assert.Equal(t, "1.0-SNAPSHOT", v, "error with getVersion for a pom.xml")
}
func TestChart(t *testing.T) {
c := config{
dir: "test-resources/helm",
}
v, err := getVersion(c)
assert.NoError(t, err)
assert.Equal(t, "0.0.1-SNAPSHOT", v, "error with getVersion for a pom.xml")
}
//func TestGetGithubTag(t *testing.T) {
//
// c := config{
// ghOwner: "rawlingsj",
// ghRepository: "test432317675",
// }
// v, err := getLatestTag(c)
//
// assert.NoError(t, err)
//
// assert.Equal(t, "2.0.0", v, "error with getLatestGithubTag for a Makefile")
//}
func TestGetGitTag(t *testing.T) {
// first get the expeted version from github as test above passed
c := config{
ghOwner: "rawlingsj",
ghRepository: "semver-release-version",
}
expectedVersion, err := getLatestTag(c)
assert.NoError(t, err)
c = config{
debug: true,
}
v, err := getLatestTag(c)
assert.NoError(t, err)
assert.Equal(t, expectedVersion, v, "error with getLatestGithubTag for a Makefile")
}
//func TestGetNewVersionFromTag(t *testing.T) {
//
// c := config{
// dryrun: false,
// debug: true,
// dir: "test-resources/make",
// ghOwner: "rawlingsj",
// ghRepository: "test432317675",
// }
//
// v, err := getNewVersionFromTag(c)
//
// assert.NoError(t, err)
// assert.Equal(t, "2.0.1", v, "error bumping a patch version")
//}
func TestGetNewVersionFromTagCurrentRepo(t *testing.T) {
c := config{
dryrun: false,
debug: true,
dir: "test-resources/make",
}
v, err := getNewVersionFromTag(c)
assert.NoError(t, err)
assert.Equal(t, "1.2.0", v, "error bumping a patch version")
}
func TestGetGitOwner(t *testing.T) {
rs := getCurrentGitOwnerRepo("[email protected]:rawlingsj/semver-release-version.git")
assert.Equal(t, "rawlingsj", rs[0])
assert.Equal(t, "semver-release-version", rs[1])
//rs = getCurrentGitOwnerRepo("https://github.com/rawlingsj/semver-release-number.git")
//assert.Equal(t, "rawlingsj", rs[0])
//assert.Equal(t, "semver-release-number", rs[1])
//assertParseGitRepositoryInfo("git://host.xz/org/repo", "host.xz", "org", "repo");
//assertParseGitRepositoryInfo("git://host.xz/org/repo.git", "host.xz", "org", "repo");
//assertParseGitRepositoryInfo("git://host.xz/org/repo.git/", "host.xz", "org", "repo");
//assertParseGitRepositoryInfo("git://github.com/jstrachan/npm-pipeline-test-project.git", "github.com", "jstrachan", "npm-pipeline-test-project");
//assertParseGitRepositoryInfo("https://github.com/fabric8io/foo.git", "github.com", "fabric8io", "foo");
//assertParseGitRepositoryInfo("https://github.com/fabric8io/foo", "github.com", "fabric8io", "foo");
//assertParseGitRepositoryInfo("[email protected]:jstrachan/npm-pipeline-test-project.git", "github.com", "jstrachan", "npm-pipeline-test-project");
//assertParseGitRepositoryInfo("[email protected]:bar/foo.git", "github.com", "bar", "foo");
//assertParseGitRepositoryInfo("[email protected]:bar/foo", "github.com", "bar", "foo");
}
| true |
d1fc64e8cc0ec0a41ab1ca76035ffc882b525990
|
Go
|
heetch/felice
|
/producer/murmur2_test.go
|
UTF-8
| 2,473 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
// This file was copied from https://github.com/burdiyan/kafkautil/blob/3e3bfeae0ffaf3b3d9b431463d9e58f840173188/partitioner_test.go
//
// It was licensed under the MIT license. Original copyright notice:
//
// MIT License
//
// Copyright (c) 2019 Alexandr Burdiyan
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package producer
import (
"hash"
"testing"
)
func TestHashInterface(t *testing.T) {
var _ hash.Hash32 = MurmurHasher()
}
func TestMurmur2(t *testing.T) {
// Test cases are generated offline using JVM Kafka client for version 1.0.0.
cases := []struct {
Input []byte
Expected int32
ExpectedPositive uint32
}{
{[]byte("21"), -973932308, 1173551340},
{[]byte("foobar"), -790332482, 1357151166},
{[]byte{12, 42, 56, 24, 109, 111}, 274204207, 274204207},
{[]byte("a-little-bit-long-string"), -985981536, 1161502112},
{[]byte("a-little-bit-longer-string"), -1486304829, 661178819},
{[]byte("lkjh234lh9fiuh90y23oiuhsafujhadof229phr9h19h89h8"), -58897971, 2088585677},
{[]byte{'a', 'b', 'c'}, 479470107, 479470107},
}
hasher := MurmurHasher()
for _, c := range cases {
if res := murmur2(c.Input); res != c.Expected {
t.Errorf("for %q expected: %d, got: %d", c.Input, c.Expected, res)
}
hasher.Reset()
hasher.Write(c.Input)
if res2 := hasher.Sum32(); res2 != uint32(c.ExpectedPositive) {
t.Errorf("hasher: for %q expected: %d, got: %d", c.Input, c.ExpectedPositive, res2)
}
}
}
| true |
c1efdef72df8d5f0308f4834d22d4ee928df25d8
|
Go
|
zacharyworks/huddle-data
|
/rest/user.go
|
UTF-8
| 1,913 | 2.671875 | 3 |
[] |
no_license
|
[] |
no_license
|
package rest
import (
"encoding/json"
"github.com/gorilla/mux"
"github.com/zacharyworks/huddle-data/shared"
"github.com/zacharyworks/huddle-data/sql"
"github.com/zacharyworks/huddle-shared/data"
"io/ioutil"
"net/http"
)
// AddUserHandlers adds the handlers for user functions
func AddUserHandlers(router *mux.Router) {
router.Handle("/user/{id}", Handler(GetUser)).Methods("GET")
router.Handle("/user", Handler(PutUser)).Methods("PUT")
router.Handle("/user", Handler(PostUser)).Methods("POST")
}
// GetUser get single to-do
func GetUser(w http.ResponseWriter, r *http.Request) *shared.AppError {
oauthID := mux.Vars(r)["id"]
// Attempt to select to-do from database
user, e := sql.SelectUser(oauthID)
if e != nil {
return e
}
if e = respond(w, user); e != nil {
return e
}
return nil
}
// PostUser creates a new user
func PostUser(w http.ResponseWriter, r *http.Request) *shared.AppError {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return shared.ErrorProcessingBody(err)
}
// Get map of user values from body from their keys
var user types.User
if err = json.Unmarshal([]byte(body), &user); err != nil {
return shared.ErrorProcessingJSON(err)
}
// Attempt to create todo
newUser, e := sql.InsertUser(user)
if e != nil {
return e
}
if e = respond(w, newUser); e != nil {
return e
}
return nil
}
// PostUser creates a new user
func PutUser(w http.ResponseWriter, r *http.Request) *shared.AppError {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return shared.ErrorProcessingBody(err)
}
// Get map of user values from body from their keys
var user types.User
if err = json.Unmarshal([]byte(body), &user); err != nil {
return shared.ErrorProcessingJSON(err)
}
// Attempt to update the user
updatedUser, e := sql.UpdateUser(user)
if e != nil {
return e
}
if e = respond(w, updatedUser); e != nil {
return e
}
return nil
}
| true |
56badb2845b6dc3b0cb55f23bcb77367b6a093f1
|
Go
|
TesterCC/learngo
|
/imooc_go_python/c06/main.go
|
UTF-8
| 664 | 3.578125 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
// 5-1
func main() {
// 字符串基本操作
// 1.求解字符串的长度
// 返回的是字节长度
// 涉及到中文问题就产生了变化
// unicode字符集 ,存储的时候需要编码
// utf8编码是一个动态的编码规则,能用一个字节表示英文,go语言采用的是utf8编码规则
//var name string = "SecCodeCat:" // 正常
var name string = "SecCodeCat:渗透测试" // python正常
fmt.Println(len(name))
// 类型转换
name_arr := []rune(name) // rune 即 int32,将其转换成数组array
//name_arr := []int32(name) // return same result
fmt.Println(len(name_arr)) // 15
}
| true |
0d0cd1135875ec75b4c97ec54a0b9a04d6660599
|
Go
|
lovefcaaa/snk.dev-assistant
|
/data/snippets/github.com/distributed-vision/go-ddapp-resources/resolvers/resolvers.go
|
UTF-8
| 5,891 | 2.75 | 3 |
[] |
no_license
|
[] |
no_license
|
package resolvers
import (
"context"
"fmt"
"sync"
"github.com/distributed-vision/go-resources/ids"
)
type Selector interface {
Type() ids.TypeIdentifier
Key() interface{}
Test(entity interface{}) bool
}
type Resolver interface {
Get(resolutionContext context.Context, selector Selector) (interface{}, error)
Resolve(resolutionContext context.Context, selector Selector) (chan interface{}, chan error)
ResolverInfo() ResolverInfo
}
type MutableResolver interface {
Resolver
Put(resolutionContext context.Context, entity interface{}) (interface{}, error)
Post(resolutionContext context.Context, entity interface{}) (interface{}, error)
Delete(resolutionContext context.Context, selector Selector) error
}
type ResolverInfo interface {
ResolverType() ids.TypeIdentifier
IsMutable() bool
ResolvableTypes() []ids.TypeIdentifier
ResolvableDomains() []ids.Domain
KeyExtractor() KeyExtractor
Matches(selector Selector) bool
Value(key interface{}) interface{}
WithValue(key, value interface{}) ResolverInfo
WithValues(values map[interface{}]interface{}) ResolverInfo
WithExtractor(keyExtractor KeyExtractor) ResolverInfo
DerivedCopy() ResolverInfo
}
type ResolverFactory interface {
ResolverType() ids.TypeIdentifier
ResolverInfo() ResolverInfo
New(resolutionContext context.Context) (Resolver, error)
}
type KeyExtractor func(entity ...interface{}) (interface{}, bool)
var RootInfo = NewResolverInfo(nil, nil, nil, nil, nil)
var rootResolver, _ = NewCompositeResolver(RootInfo)
func Get(resolutionContext context.Context, selector Selector) (entity interface{}, err error) {
return rootResolver.Get(resolutionContext, selector)
}
func Resolve(resolutionContext context.Context, selector Selector) (chan interface{}, chan error) {
return rootResolver.Resolve(resolutionContext, selector)
}
func RegisterResolver(resolver Resolver) {
rootResolver.RegisterComponent(resolver)
}
func RegisterFactory(resolverFactory ResolverFactory) {
rootResolver.RegisterComponentFactory(resolverFactory, false)
}
type NewFactoryFunction func(resolverInfo ResolverInfo) (ResolverFactory, error)
var newFactoryFunctionRegistry map[string]NewFactoryFunction = make(map[string]NewFactoryFunction)
var newFactoryFunctionRegistryMutex = &sync.Mutex{}
func NewResolverFactory(resolverInfo ResolverInfo) (ResolverFactory, error) {
newFactoryFunctionRegistryMutex.Lock()
defer newFactoryFunctionRegistryMutex.Unlock()
//fmt.Printf("Getting func for: %v\n", resolverInfo.ResolverType())
if newFactoryFunction, ok := newFactoryFunctionRegistry[string(resolverInfo.ResolverType().Value())]; ok {
return newFactoryFunction(resolverInfo)
}
return nil, fmt.Errorf("No factory function availible for: %s", string(resolverInfo.ResolverType().Id()))
}
func ResisterNewFactoryFunction(resolverType ids.TypeIdentifier, newFactoryFunction NewFactoryFunction) {
newFactoryFunctionRegistryMutex.Lock()
//fmt.Printf("Regestering func for: %v\n", resolverType)
newFactoryFunctionRegistry[string(resolverType.Value())] = newFactoryFunction
newFactoryFunctionRegistryMutex.Unlock()
}
type resolverInfo struct {
resolverType ids.TypeIdentifier
resolvableTypes []ids.TypeIdentifier
resolvableDomains []ids.Domain
keyExtractor KeyExtractor
values map[interface{}]interface{}
parent ResolverInfo
}
func NewResolverInfo(resolverType ids.TypeIdentifier, resolvableTypes []ids.TypeIdentifier, resolvableDomains []ids.Domain, keyExtractor KeyExtractor, values map[interface{}]interface{}) ResolverInfo {
return &resolverInfo{resolverType, resolvableTypes, resolvableDomains, keyExtractor, values, nil}
}
func (this *resolverInfo) ResolverType() ids.TypeIdentifier {
return this.resolverType
}
func (this *resolverInfo) ResolvableTypes() []ids.TypeIdentifier {
return this.resolvableTypes
}
func (this *resolverInfo) IsMutable() bool {
return false
}
func (this *resolverInfo) ResolvableDomains() []ids.Domain {
return this.resolvableDomains
}
func (this *resolverInfo) Value(key interface{}) (res interface{}) {
if this.values != nil {
res = this.values[key]
}
if res == nil && this.parent != nil {
res = this.parent.Value(key)
}
//fmt.Printf("value[%s]=%v\n", key, res)
return res
}
func (this *resolverInfo) Matches(selector Selector) bool {
if this.resolvableTypes != nil && selector.Type() != nil {
for _, resolvableType := range this.resolvableTypes {
if resolvableType.Equals(selector.Type()) {
return true
}
}
} else {
return true
}
return false
}
func (this *resolverInfo) KeyExtractor() KeyExtractor {
return this.keyExtractor
}
func (this *resolverInfo) DerivedCopy() ResolverInfo {
var resolvableTypes []ids.TypeIdentifier
var resolvableDomains []ids.Domain
if this.resolvableTypes != nil {
resolvableTypes = make([]ids.TypeIdentifier, len(this.ResolvableTypes()))
copy(resolvableTypes, this.ResolvableTypes())
}
if resolvableDomains != nil {
resolvableDomains = make([]ids.Domain, len(this.ResolvableDomains()))
copy(resolvableDomains, this.ResolvableDomains())
}
return &resolverInfo{this.resolverType,
resolvableTypes,
resolvableDomains,
this.keyExtractor,
nil, this}
}
func (this *resolverInfo) WithExtractor(keyExtractor KeyExtractor) ResolverInfo {
return &resolverInfo{this.resolverType,
this.resolvableTypes,
this.resolvableDomains,
keyExtractor, nil, this}
}
func (this *resolverInfo) WithValue(key, value interface{}) ResolverInfo {
values := make(map[interface{}]interface{})
values[key] = value
return &resolverInfo{this.resolverType,
this.resolvableTypes,
this.resolvableDomains,
this.keyExtractor, values, this}
}
func (this *resolverInfo) WithValues(values map[interface{}]interface{}) ResolverInfo {
return &resolverInfo{this.resolverType,
this.resolvableTypes,
this.resolvableDomains,
this.keyExtractor,
values, this}
}
| true |
2b8e42b6e0a3a0e37fdb6a774203c8e247c2097a
|
Go
|
ivahaev/mongofil
|
/regexmatcher.go
|
UTF-8
| 1,110 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package mongofil
import (
"errors"
"regexp"
"github.com/buger/jsonparser"
)
var (
errInvalidRegex = errors.New("invalid regex")
)
type regexMatcher struct {
propName string
regex *regexp.Regexp
}
func newRegexMatcher(propName string, in interface{}) (Matcher, error) {
condition, ok := in.(map[string]interface{})
if !ok {
return nil, errInvalidRegex
}
_expr, ok := condition["$regex"]
if !ok {
return nil, errInvalidRegex
}
expr, ok := _expr.(string)
if !ok {
return nil, errInvalidRegex
}
var options string
if _opt, ok := condition["$options"]; ok {
options, ok = _opt.(string)
if !ok {
return nil, errInvalidRegex
}
}
var rgx *regexp.Regexp
var err error
if options == "" {
rgx, err = regexp.Compile(expr)
} else {
rgx, err = regexp.Compile("(?" + options + ")" + expr)
}
if err != nil {
return nil, err
}
m := regexMatcher{propName, rgx}
return &m, nil
}
func (m *regexMatcher) Match(doc []byte) bool {
val, typ, _, err := jsonparser.Get(doc, m.propName)
if err != nil || typ != jsonparser.String {
return false
}
return m.regex.Match(val)
}
| true |
f233431c0c358fcba3aee175a51b7314f98df42a
|
Go
|
gorilla001/swan-old
|
/scheduler/resources_test.go
|
UTF-8
| 753 | 2.515625 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package scheduler
import (
"github.com/Dataman-Cloud/swan/scheduler/mock"
"github.com/stretchr/testify/assert"
"testing"
)
func TestCreateScaleResource(t *testing.T) {
resource := createScalarResource("cpu", 0.1)
assert.Equal(t, *resource.Name, "cpu")
assert.Equal(t, *resource.Scalar.Value, 0.1)
}
func TestCreateRangeResource(t *testing.T) {
resource := createRangeResource("ports", 1000, 10001)
assert.Equal(t, *resource.Name, "ports")
}
func TestBuildResource(t *testing.T) {
sched := NewScheduler("x.x.x.x:yyyy", nil, &mock.Store{}, "xxxx", nil, nil)
resources := sched.BuildResources(0.1, 16, 10)
assert.Equal(t, *resources[0].Name, "cpus")
assert.Equal(t, *resources[1].Name, "mem")
assert.Equal(t, *resources[2].Name, "disk")
}
| true |
1058a3e1d56b3587515c9039fe258c6d756b477a
|
Go
|
arriqaaq/flashdb
|
/store_test.go
|
UTF-8
| 539 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package flashdb
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func TestFlashDB_StringStore(t *testing.T) {
s := newStrStore()
for i := 1; i <= 1000; i++ {
key := fmt.Sprintf("key_%d", i)
value := fmt.Sprintf("value_%d", i)
s.Insert([]byte(key), []byte(value))
}
keys := s.Keys()
assert.Equal(t, 1000, len(keys))
for i := 1; i <= 1000; i++ {
key := fmt.Sprintf("key_%d", i)
value := fmt.Sprintf("value_%d", i)
val, err := s.get(key)
assert.NoError(t, err)
assert.NotEqual(t, value, val)
}
}
| true |
39cb3a07f1fce0a40ced649bfc966524fe981e2d
|
Go
|
hanksudo/go-101
|
/others/file-upload/server/server.go
|
UTF-8
| 419 | 2.828125 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.Handle("/upload", http.HandlerFunc(upload))
http.ListenAndServe(":9090", nil)
}
func upload(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(32 << 20)
file, handler, err := r.FormFile("file")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
fmt.Fprintf(w, "%v", handler.Header)
log.Println(handler.Header)
}
| true |
9b515042f98cf2a43723318bd5cafc315a5fee25
|
Go
|
ricallinson/stackr
|
/response_time.go
|
UTF-8
| 560 | 3.09375 | 3 |
[] |
no_license
|
[] |
no_license
|
package stackr
import (
"strconv"
"time"
)
/*
Adds the X-Response-Time header displaying the response duration in milliseconds.
Example:
stackr.CreateServer().Use(stackr.ResponseTime())
*/
func ResponseTime() func(*Request, *Response, func()) {
return func(req *Request, res *Response, next func()) {
start := time.Now().UnixNano()
res.On("header", func() {
duration := time.Now().UnixNano() - start
res.SetHeader("X-Response-Time", strconv.FormatInt(int64(time.Duration(duration)/time.Millisecond), 10)+"ms")
})
next()
}
}
| true |
c9a5629a536323c6cc0ea79ea3acbe6272929e79
|
Go
|
yidane/algorithm
|
/leetcode/problems/119.pascals-triangle-ii_1_test.go
|
UTF-8
| 318 | 2.5625 | 3 |
[] |
no_license
|
[] |
no_license
|
package problems
import (
"fmt"
"testing"
)
func Test_getRow(t *testing.T) {
tests := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
for _, tt := range tests {
pascals := generate(30)
t.Run(fmt.Sprint(tt), func(t *testing.T) {
got := getRow(tt)
if !SameArray(got, pascals[tt]) {
t.Fatal()
}
})
}
}
| true |
ee60f73f776669606810ea0ed19c81e33594eefb
|
Go
|
rwcarlsen/fem
|
/sparse/sparse_test.go
|
UTF-8
| 2,307 | 2.984375 | 3 |
[] |
no_license
|
[] |
no_license
|
package sparse
import (
"fmt"
"math/rand"
"testing"
"github.com/gonum/matrix/mat64"
)
func TestSparse(t *testing.T) {
const tol = 1e-6
size := 6
nfill := 3
s := randSparse(size, nfill, 0)
fmt.Printf("% .2v\n", mat64.Formatted(s))
}
func randSparse(size, fillPerRow int, off float64) Matrix {
s := NewSparse(size)
for i := 0; i < size; i++ {
s.Set(i, i, float64(fillPerRow))
}
for i := 0; i < size; i++ {
nfill := fillPerRow / 2
if i%7 == 0 {
nfill = fillPerRow / 3
}
for n := 0; n < nfill; n++ {
j := rand.Intn(size)
if i == j {
continue
}
v := off
if v == 0 {
v = rand.Float64()
}
s.Set(i, j, v)
s.Set(j, i, v)
}
}
return s
}
func TestRCM_big(t *testing.T) {
size := 35
nfill := 6
big := randSparse(size, nfill, 8)
mapping := RCM(big)
permuted := NewSparse(size)
Permute(permuted, big, mapping)
t.Logf("original=\n% v\n", mat64.Formatted(big))
t.Logf("permuted=\n% v\n", mat64.Formatted(permuted))
}
func TestRCM(t *testing.T) {
return
var tests = []struct {
size int
vals []float64
wantmap []int
}{
{
size: 4,
vals: []float64{
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1,
},
wantmap: []int{3, 2, 1, 0},
}, {
size: 4,
vals: []float64{
0, 1, 0, 0,
1, 0, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1,
},
wantmap: []int{3, 2, 1, 0},
}, {
size: 4,
vals: []float64{
1, 1, 0, 0,
1, 1, 1, 0,
0, 1, 1, 1,
0, 0, 1, 1,
},
wantmap: []int{1, 3, 2, 0},
}, {
size: 4,
vals: []float64{
1, 1, 0, 1,
1, 1, 0, 1,
0, 0, 1, 1,
1, 1, 1, 1,
},
wantmap: []int{2, 1, 0, 3},
},
}
for i, test := range tests {
A := NewSparse(test.size)
for i := 0; i < test.size; i++ {
for j := 0; j < test.size; j++ {
A.Set(i, j, test.vals[i*test.size+j])
}
}
got := RCM(A)
failed := false
for i := range got {
if test.wantmap[i] != got[i] {
failed = true
break
}
}
if failed {
permuted := NewSparse(test.size)
Permute(permuted, A, got)
t.Errorf("test %v: A=%v", i+1, mat64.Formatted(A, mat64.Prefix(" ")))
t.Errorf(" A_perm=%v", mat64.Formatted(permuted, mat64.Prefix(" ")))
t.Errorf(" mapping: got %v, want %v", got, test.wantmap)
}
}
}
| true |
6803913c00e984c349965fb68204cff0e914b882
|
Go
|
bytefly/leetcode
|
/401.go
|
UTF-8
| 504 | 3.09375 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
)
func readBinaryWatch(num int) []string {
var ans []string
var j uint
var hour, minute int //4 bits(&0x0F) and 6 bits(&0x3F)
for i := 0; i < 1024; i++ {
no1Num := 0
for j = 0; j < 10; j++ {
if (i>>j)&1 == 1 {
no1Num++
}
}
if no1Num == num {
hour, minute = i&0xF, (i&0x3F0)>>4
if hour < 12 && minute < 60 {
ans = append(ans, fmt.Sprintf("%d:%02d", hour, minute))
}
}
}
return ans
}
func main() {
fmt.Println(readBinaryWatch(2))
}
| true |
b25b6d0dc9df5483da11dcd974fabc1433aa8971
|
Go
|
ArnavBiswas16/codingPractise
|
/Array/findDuplicate.go
|
UTF-8
| 323 | 3.375 | 3 |
[] |
no_license
|
[] |
no_license
|
// https://www.geeksforgeeks.org/find-duplicates-in-on-time-and-constant-extra-space/
package main
import "fmt"
func main() {
arr := [...]int{0, 4, 3, 2, 7, 8, 2, 3, 1}
len := len(arr)
for _, val := range arr {
arr[val%len] += len
}
for i, val := range arr {
if val >= len*2 {
fmt.Print(i, ", ")
}
}
}
| true |
9c4bc59cb2216030a31c94104f6ddcfe4bf38145
|
Go
|
agungdwiprasetyo/reverse-proxy
|
/helper/color_test.go
|
UTF-8
| 2,245 | 3.234375 | 3 |
[] |
no_license
|
[] |
no_license
|
package helper
import (
"testing"
)
func TestColorForStatus(t *testing.T) {
tests := []struct {
name string
args int
want string
}{
{
name: "Testcase #1: Return Green",
args: 200,
want: Green,
},
{
name: "Testcase #2: Return White",
args: 300,
want: White,
},
{
name: "Testcase #3: Return Yellow",
args: 400,
want: Yellow,
},
{
name: "Testcase #4: Return Red",
args: 500,
want: Red,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := ColorForStatus(tt.args); got != tt.want {
t.Errorf("ColorForStatus() = %v, want %v", got, tt.want)
}
})
}
}
func TestColorForMethod(t *testing.T) {
tests := []struct {
name string
args string
want string
}{
{
name: "Testcase #1: Return Blue",
args: "GET",
want: Blue,
},
{
name: "Testcase #2: Return Cyan",
args: "POST",
want: Cyan,
},
{
name: "Testcase #3: Return Yellow",
args: "PUT",
want: Yellow,
},
{
name: "Testcase #4: Return Red",
args: "DELETE",
want: Red,
},
{
name: "Testcase #5: Return Green",
args: "PATCH",
want: Green,
},
{
name: "Testcase #6: Return Magenta",
args: "HEAD",
want: Magenta,
},
{
name: "Testcase #7: Return White",
args: "OPTIONS",
want: White,
},
{
name: "Testcase #8: Return RESET",
args: "RESET",
want: Reset,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := ColorForMethod(tt.args); got != tt.want {
t.Errorf("ColorForMethod() = %v, want %v", got, tt.want)
}
})
}
}
func TestColorString(t *testing.T) {
t.Run("Test String Red", func(t *testing.T) {
if got := StringRed("String Red"); got != "\x1b[31;1mString Red\x1b[0m" {
t.Errorf("StringRed() = %v, want %v", got, "String Red")
}
})
t.Run("Test String Green", func(t *testing.T) {
if got := StringGreen("String Green"); got != "\x1b[32;1mString Green\x1b[0m" {
t.Errorf("StringGreen() = %v, want %v", got, "String Green")
}
})
t.Run("Test String Yellow", func(t *testing.T) {
if got := StringYellow("String Yellow"); got != "\x1b[33;1mString Yellow\x1b[0m" {
t.Errorf("StringYellow() = %v, want %v", got, "String Yellow")
}
})
}
| true |
7e70c3a1fe872d18d93db150f4701168aedb88c1
|
Go
|
Xjs/reverse
|
/reverse.go
|
UTF-8
| 360 | 3.203125 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
sc := bufio.NewScanner(os.Stdin)
var lines []string
for sc.Scan() {
if err := sc.Err(); err != nil {
log.Fatal(err)
}
lines = append(lines, sc.Text())
}
if err := sc.Err(); err != nil {
log.Fatal(err)
}
for i := len(lines) - 1; i >= 0; i-- {
fmt.Println(lines[i])
}
}
| true |
2c773cd430b252513511c1e937f1f473260c210e
|
Go
|
bohdanlisovskyi/goschool
|
/lesson2/presentation/arrays_declare.go
|
UTF-8
| 148 | 3.0625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
func main() {
var a [2]int
a[0] = 23
a[1] = 44
fmt.Println(a[0], a[1])
fmt.Println(&a[0], &a[1])
fmt.Println(a)
}
| true |
449f24af3888d64da24f751ba9131034b891698d
|
Go
|
Jabst/golang
|
/index_xorm.go
|
UTF-8
| 1,401 | 2.84375 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"log"
"net/http"
"fmt"
)
type SyncUser struct {
Id int64
Name string `xorm:"unique"`
Contact string
}
var engine *xorm.Engine
func postgresEngine() (*xorm.Engine, error){
return xorm.NewEngine("postgres", "dbname=golang user=golang password=123123 sslmode=disable")
}
type engineFunc func() (*xorm.Engine, error)
func sync(engine *xorm.Engine) error {
return engine.Sync(&SyncUser{}, &SyncUser{})
}
func main() {
var router = NewRouter()
//engine, err = xorm.NewEngine("postgres", "dbname=golang sslmode=disable")
engines := []engineFunc{postgresEngine}
for _, enginefunc := range engines {
Orm, err := enginefunc()
fmt.Println("--------", Orm.DriverName(), "----------")
if err != nil {
fmt.Println(err)
return
}
Orm.ShowSQL(true)
err = sync(Orm)
if err != nil {
fmt.Println(err)
}
_, err = Orm.Where("id > 0").Delete(&SyncUser{})
if err != nil {
fmt.Println(err)
}
user := &SyncUser{
Name: "BLALBA",
Contact: "AKDAD",
}
_, err = Orm.Insert(user)
if err != nil {
fmt.Println(err)
return
}
isexist, err := Orm.IsTableExist("Users")
if err != nil {
fmt.Println(err)
return
}
if !isexist {
fmt.Println("sync_user2 is not exist")
return
}
}
log.Fatal(http.ListenAndServe(":8081", router))
}
| true |
e71cd862e5ff950f65471f1fc3ab918a38f630a1
|
Go
|
kjk/kjkpub
|
/concat-yoga/concat-yoga.go
|
UTF-8
| 2,802 | 3.078125 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"bufio"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"os/user"
"path/filepath"
"strings"
)
func fatalIfErr(err error) {
if err != nil {
panic(err.Error())
}
}
// userHomeDir returns $HOME diretory of the user
func userHomeDir() string {
// user.Current() returns nil if cross-compiled e.g. on mac for linux
if usr, _ := user.Current(); usr != nil {
return usr.HomeDir
}
return os.Getenv("HOME")
}
// expandTildeInPath converts ~ to $HOME
func expandTildeInPath(s string) string {
if strings.HasPrefix(s, "~/") {
return userHomeDir() + s[1:]
}
return s
}
func dirExists(dir string) bool {
s, err := os.Stat(dir)
if err != nil {
return false
}
return s.Mode().IsDir()
}
func runCmdMust(name string, args ...string) {
cmd := exec.Command(name, args...)
err := cmd.Run()
fatalIfErr(err)
}
func readLinesMust(path string) []string {
f, err := os.Open(path)
fatalIfErr(err)
defer f.Close()
scanner := bufio.NewScanner(f)
var lines []string
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
fatalIfErr(scanner.Err())
return lines
}
// remove #include "foo.h" lines and #pragma once lines
func filterLines(a []string) []string {
var res []string
for _, s := range a {
if strings.HasPrefix(s, "#pragma once") {
continue
}
if strings.HasPrefix(s, `#include "`) {
continue
}
res = append(res, s)
}
return res
}
func readFilteredLinesMust(path string) []string {
lines := readLinesMust(path)
nLines := len(lines)
lines = filterLines(lines)
fmt.Printf("%s: %d lines, %d filtered lines\n", path, nLines, len(lines))
return lines
}
func writeLinesMust(dstPath string, args ...interface{}) {
var lines []string
for _, arg := range args {
a := arg.([]string)
lines = append(lines, a...)
}
s := strings.Join(lines, "\n")
err := ioutil.WriteFile(dstPath, []byte(s), 0644)
fatalIfErr(err)
fmt.Printf("Wrote %s (%d lines)\n", dstPath, len(lines))
}
func main() {
dir := expandTildeInPath("~/src/yoga")
if !dirExists(dir) {
log.Fatalf("dir '%s' doesn't exist\n", dir)
}
runCmdMust("git", "pull")
srcDir := filepath.Join(dir, "yoga")
{
lines1 := readFilteredLinesMust(filepath.Join(srcDir, "YGMacros.h"))
lines2 := readFilteredLinesMust(filepath.Join(srcDir, "YGEnums.h"))
lines3 := readFilteredLinesMust(filepath.Join(srcDir, "Yoga.h"))
lines4 := readFilteredLinesMust(filepath.Join(srcDir, "YGNodeList.h"))
writeLinesMust("yoga.h", lines1, lines2, lines3, lines4)
}
{
lines1 := readFilteredLinesMust(filepath.Join(srcDir, "YGEnums.c"))
lines2 := readFilteredLinesMust(filepath.Join(srcDir, "YGNodeList.c"))
lines3 := readFilteredLinesMust(filepath.Join(srcDir, "Yoga.c"))
lines := []string{`#include "yoga.h"`}
writeLinesMust("yoga.c", lines, lines1, lines2, lines3)
}
}
| true |
088fd5d22f5479e32c1b6e31527229d830354a60
|
Go
|
heimonsy/k8s-learn
|
/frontend/main.go
|
UTF-8
| 916 | 2.8125 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"io/ioutil"
"log"
"net/http"
"os"
)
func main() {
hostname, _ := os.Hostname()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Printf("[frontend] request from: %s", r.RemoteAddr)
geted, err := http.Get("http://backend-service:18080/")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
defer geted.Body.Close()
data, err := ioutil.ReadAll(geted.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
resp := "---------------------------\n"
resp += "frontend " + hostname + "\n"
resp += "---------------------------\n"
for _, env := range os.Environ() {
resp += env + "\n"
}
w.Write([]byte(resp))
w.Write([]byte("response from backend >>>>>>>>>>>\n"))
w.Write(data)
})
http.ListenAndServe(":8080", nil)
}
| true |
fe87636988ac58cb0a679bf728c8361d42e438e6
|
Go
|
spkinger/speaker-server
|
/src/module/pub/func.go
|
UTF-8
| 2,042 | 3.125 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
[
"BSD-3-Clause"
] |
permissive
|
package pub
import (
"encoding/json"
"log"
"net/http"
"strconv"
"strings"
)
type RepBody struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
// 构建响应
func CommonRep(code int, writer http.ResponseWriter, msg string, data interface{}) {
rep := RepBody{
Code: code,
Msg: msg,
Data: data,
}
repJson, err := json.Marshal(rep)
if err != nil {
log.Println("repBody to json: ", err)
return
}
_, err = writer.Write(repJson)
if err != nil {
log.Println("write response: ", err)
}
}
// 权限验证失败响应
func AuthErrRep(writer http.ResponseWriter, msg string) {
CommonRep(4000, writer, msg, map[string]interface{}{})
}
// 构造错误响应
func ErrRep(writer http.ResponseWriter, msg string, data interface{}) {
CommonRep(10000, writer, msg, data)
}
// 成功响应
func SuccRep(writer http.ResponseWriter, msg string, data interface{}) {
CommonRep(0, writer, msg, data)
}
// 切片中查找字符串
func StrInSlice(s string, list []string) bool {
for _, item := range list {
if s == item {
return true
}
}
return false
}
// 获取get参数
func GetParam(request *http.Request, key string) (string, bool) {
query := request.URL.Query()
param, ok := query[key]
if !ok {
return "", ok
}
return strings.Join(param, ""), true
}
// 获取page参数组
func GetPageParam(writer http.ResponseWriter, request *http.Request) (int, int) {
var err error
pageDefault := 1
pageSizeDefault := 25
pageInt := pageDefault
pageSizeInt := pageSizeDefault
page, ok := GetParam(request, "page")
if ok {
pageInt, err = strconv.Atoi(page)
if err != nil {
log.Print("page to int err:", err)
pageInt = pageDefault
}
}
pageSize, ok := GetParam(request, "page_size")
if ok {
pageSizeInt, err = strconv.Atoi(pageSize)
if err != nil {
log.Print("page_size to int err:", err)
pageSizeInt = pageSizeDefault
}
}
if pageSizeInt < 10 {
pageSizeInt = 10
}
if pageSizeInt > 200 {
pageSizeInt = 200
}
return pageInt, pageSizeInt
}
| true |
3b3004583354491b5ac0d0511627c6d36534609b
|
Go
|
m1keil/golang_book
|
/ch8/ex5/main.go
|
UTF-8
| 1,446 | 3.671875 | 4 |
[
"Unlicense"
] |
permissive
|
[
"Unlicense"
] |
permissive
|
package main
/* Exercise 8.5: Take an existing CPU-bound sequential program, such as the
Mandelbrot program of Section 3.3 or the 3-D surface computation of Section 3.2,
and execute its main loop in parallel using channels for communication. How much
faster does it run on a multiprocessor machine? What is the optimal number of
goroutines to use? */
import (
"image"
"image/color"
"image/png"
"math/cmplx"
"os"
"sync"
)
func main() {
const (
xmin, ymin, xmax, ymax = -2, -2, +2, +2
width, height = 4096, 4096
concurrency = 4
)
img := image.NewRGBA(image.Rect(0, 0, width, height))
wg := sync.WaitGroup{}
for c := 0; c < concurrency; c++ {
offset := height / concurrency
start := offset * c
wg.Add(1)
go func(first, offset int) {
for py := first; py < first+offset; py++ {
y := float64(py)/height*(ymax-ymin) + ymin
for px := 0; px < width; px++ {
x := float64(px)/width*(xmax-xmin) + xmin
z := complex(x, y)
// Image point (px, py) represents complex value z.
img.Set(px, py, mandelbrot(z))
}
}
wg.Done()
}(start, offset)
}
wg.Wait()
png.Encode(os.Stdout, img) // NOTE: ignoring errors
}
func mandelbrot(z complex128) color.Color {
const iterations = 100
const contrast = 15
var v complex128
for n := uint8(0); n < iterations; n++ {
v = v*v + z
if cmplx.Abs(v) > 2 {
return color.Gray{255 - contrast*n}
}
}
return color.Black
}
| true |
b7671df74493f617b9eec40aef833490d8165ebf
|
Go
|
zaphinath/language
|
/compiler/debug/debug.go
|
UTF-8
| 457 | 3.078125 | 3 |
[] |
no_license
|
[] |
no_license
|
package debug
import (
"fmt"
"runtime"
)
func CallingFunction() string {
fn, fl := functionNameAndLine(3)
return fmt.Sprintf("calling function: %s %d", fn, fl)
}
func functionNameAndLine(n int) (string, int) {
ptr, _, _, _ := runtime.Caller(n)
f := runtime.FuncForPC(ptr)
_, fl := f.FileLine(ptr)
return f.Name(), fl
}
func PrintStackRange(n int) {
for si := 0; si < n; si++ {
fn, fl := functionNameAndLine(3 + si)
fmt.Println(fn, fl)
}
}
| true |
aef50e391edf5dd52c8db18cb701a0d65c0f4f90
|
Go
|
el-ideal-ideas/ellib
|
/elstr/bytes.go
|
UTF-8
| 2,869 | 3.25 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
// Copy from https://github.com/thinkeridea/go-extend
package elstr
import (
"strings"
"unicode/utf8"
)
// Replace strings but return []byte
func ReplaceToBytes(s, old, new string, n int) []byte {
if old == new || n == 0 {
return []byte(s) // avoid allocation
}
// Compute number of replacements.
if m := strings.Count(s, old); m == 0 {
return []byte(s) // avoid allocation
} else if n < 0 || m < n {
n = m
}
// Apply replacements to buffer.
t := make([]byte, len(s)+n*(len(new)-len(old)))
w := 0
start := 0
for i := 0; i < n; i++ {
j := start
if len(old) == 0 {
if i > 0 {
_, wid := utf8.DecodeRuneInString(s[start:])
j += wid
}
} else {
j += strings.Index(s[start:], old)
}
w += copy(t[w:], s[start:j])
w += copy(t[w:], new)
start = j + len(old)
}
w += copy(t[w:], s[start:])
return t[0:w]
}
// Replace strings but return []byte
// Dangerous!!
// This function is very dangerous (but really fast)
// If the string was written to your source code directly,
// Please don't use this function. Because it will cause a series error.
// If you want to use this function, Please check bytes.UnsafeToBytes
func UnsafeReplaceToBytes(s, old, new string, n int) []byte {
if old == new || n == 0 {
return UnsafeToBytes(s) // avoid allocation
}
// Compute number of replacements.
if m := strings.Count(s, old); m == 0 {
return UnsafeToBytes(s) // avoid allocation
} else if n < 0 || m < n {
n = m
}
// Apply replacements to buffer.
t := make([]byte, len(s)+n*(len(new)-len(old)))
w := 0
start := 0
for i := 0; i < n; i++ {
j := start
if len(old) == 0 {
if i > 0 {
_, wid := utf8.DecodeRuneInString(s[start:])
j += wid
}
} else {
j += strings.Index(s[start:], old)
}
w += copy(t[w:], s[start:j])
w += copy(t[w:], new)
start = j + len(old)
}
w += copy(t[w:], s[start:])
return t[0:w]
}
// Repeat the string but return []byte
// It panics if count is negative or if
// the result of (len(s) * count) overflows.
func RepeatToBytes(s string, count int) []byte {
// Since we cannot return an error on overflow,
// we should panic if the repeat will generate
// an overflow.
// See Issue golang.org/issue/16237
if count < 0 {
panic("strings: negative Repeat count")
} else if count > 0 && len(s)*count/count != len(s) {
panic("strings: Repeat count causes overflow")
}
b := make([]byte, len(s)*count)
bp := copy(b, s)
for bp < len(b) {
copy(b[bp:], b[:bp])
bp *= 2
}
return b
}
// Join strings but return []byte
func JoinToBytes(a []string, sep string) []byte {
switch len(a) {
case 0:
return []byte{}
case 1:
return []byte(a[0])
}
n := len(sep) * (len(a) - 1)
for i := 0; i < len(a); i++ {
n += len(a[i])
}
b := make([]byte, n)
bp := copy(b, a[0])
for _, s := range a[1:] {
bp += copy(b[bp:], sep)
bp += copy(b[bp:], s)
}
return b
}
| true |
770a97ea589fb34284378f5c0321173a2e3cb2b0
|
Go
|
KiameV/final-fantasy-vi-save-editor
|
/global/vars.go
|
UTF-8
| 1,433 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package global
import (
"io/fs"
"os"
"time"
)
const (
WindowWidth = 725
WindowHeight = 800
)
var (
PWD string
DirFiles []fs.FileInfo
FileName string
FileType SaveFileType
showing CurrentScreen
prevShow CurrentScreen
)
type CurrentScreen byte
const (
Blank CurrentScreen = iota
LoadSnes
SaveSnes
ShowSnes
LoadPR
SavePR
ShowPR
)
func RollbackShowing() CurrentScreen {
showing = prevShow
return showing
}
func GetCurrentShowing() CurrentScreen {
return showing
}
func SetShowing(s CurrentScreen) {
if showing != prevShow {
prevShow = showing
}
showing = s
}
func IsShowing(s CurrentScreen) bool {
return s == showing
}
func IsShowingPR() bool {
return showing == LoadPR || showing == SavePR || showing == ShowPR
}
// SaveFileType Defines the supported File Types
type SaveFileType byte
const (
// SRMSlot1 Save file slot 1
SRMSlot1 SaveFileType = iota
// SRMSlot2 Save file slot 2
SRMSlot2
// SRMSlot3 Save file slot 3
SRMSlot3
// ZnesSaveState ZNES save state
ZnesSaveState
// PixelRemastered Steam Remastered
PixelRemastered
/* Snes9xSaveState15 Snes9x v1.5 save state
//Snes9xSaveState15
// Snes9xSaveState16 Snes9x v1.6 save state offset 1
//Snes9xSaveState16*/
)
func init() {
var err error
if PWD, err = os.Getwd(); err != nil {
PWD = "."
}
}
func NowToTicks() uint64 {
return uint64(float64(time.Now().UnixNano())*0.01) + uint64(60*60*24*365*1970*10000000)
}
| true |
49835df9f2fc37a6dc864c8fbce3f11de4cf258d
|
Go
|
bionoren/thermostat
|
/system/monitor.go
|
UTF-8
| 760 | 3.109375 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
[
"BSD-3-Clause"
] |
permissive
|
package system
import (
"thermostat/db/setting"
"time"
)
func currentSetting(schedules []setting.Setting) setting.Setting {
now := time.Now().Round(time.Second) // rounding this lets me prevent instantaneous schedule overlap, while also preventing brief gaps in scheduling
var current setting.Setting
for _, s := range schedules {
if s.Priority < current.Priority {
continue
}
if s.DayOfWeek&setting.WeekdayMask(now.Weekday()) == 0 {
continue
}
if s.StartDay.After(now) || s.EndDay.Before(now) {
continue
}
sec := daySeconds(now)
if sec < s.StartTime || sec > s.EndTime {
continue
}
current = s
}
return current
}
func daySeconds(t time.Time) int {
hour, min, sec := t.Clock()
return hour*60*60 + min*60 + sec
}
| true |
8bbb5b7588eec1f09509e6f6bb0d46c2306b6c6e
|
Go
|
ytsiuryn/ds-audiomd
|
/release_flags_test.go
|
UTF-8
| 2,880 | 2.6875 | 3 |
[] |
no_license
|
[] |
no_license
|
package metadata
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestReleaseStatusMarshalAndUnmarshal(t *testing.T) {
data, err := json.Marshal(ReleaseStatus(0))
require.NoError(t, err)
assert.Equal(t, []byte(`""`), data)
rs := ReleaseStatusOfficial
data, err = json.Marshal(rs)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(data, &rs))
assert.Equal(t, ReleaseStatusOfficial, rs)
}
func TestReleaseStatusDecode(t *testing.T) {
var rs ReleaseStatus
for k, v := range StrToReleaseStatus {
rs.Decode(k)
assert.Equal(t, v, rs)
}
}
func TestReleaseStatusDecodeSlice(t *testing.T) {
var rs ReleaseStatus
rs.DecodeSlice(&[]string{"Text", "Oficial", "Another Text"})
assert.Equal(t, ReleaseStatusOfficial, rs)
}
func TestReleaseTypeMarshalAndUnmarshal(t *testing.T) {
data, err := json.Marshal(ReleaseType(0))
require.NoError(t, err)
assert.Equal(t, []byte(`""`), data)
rt := ReleaseTypeAlbum
data, err = json.Marshal(rt)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(data, &rt))
assert.Equal(t, ReleaseTypeAlbum, rt)
}
func TestReleaseTypeDecodeSlice(t *testing.T) {
var rt ReleaseType
rt.DecodeSlice(&[]string{"Text", "Album", "Another Text"})
assert.Equal(t, ReleaseTypeAlbum, rt)
}
func TestReleaseRepeatMarshalAndUnmarshal(t *testing.T) {
data, err := json.Marshal(ReleaseRepeat(0))
require.NoError(t, err)
assert.Equal(t, []byte(`""`), data)
rr := ReleaseRepeatRemake
data, err = json.Marshal(rr)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(data, &rr))
assert.Equal(t, ReleaseRepeatRemake, rr)
}
func TestReleaseRepeatDecodeSlice(t *testing.T) {
var rr ReleaseRepeat
rr.DecodeSlice(&[]string{"Text", "Repress", "Another Text"})
assert.Equal(t, ReleaseRepeatRepress, rr)
}
func TestReleaseRemakeMarshalAndUnmarshal(t *testing.T) {
data, err := json.Marshal(ReleaseRemake(0))
require.NoError(t, err)
assert.Equal(t, []byte(`""`), data)
rr := ReleaseRemakeRemastered
data, err = json.Marshal(rr)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(data, &rr))
assert.Equal(t, ReleaseRemakeRemastered, rr)
}
func TestReleaseRemakeDecodeSlice(t *testing.T) {
var rr ReleaseRemake
rr.DecodeSlice(&[]string{"Text", "Remastered", "Another Text"})
assert.Equal(t, ReleaseRemakeRemastered, rr)
}
func TestReleaseOriginMarshalAndUnmarshal(t *testing.T) {
data, err := json.Marshal(ReleaseOrigin(0))
require.NoError(t, err)
assert.Equal(t, []byte(`""`), data)
ro := ReleaseOriginStudio
data, err = json.Marshal(ro)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(data, &ro))
assert.Equal(t, ReleaseOriginStudio, ro)
}
func TestReleaseOriginDecodeSlice(t *testing.T) {
var ro ReleaseOrigin
ro.DecodeSlice(&[]string{"Text", "Studio", "Another Text"})
assert.Equal(t, ReleaseOriginStudio, ro)
}
| true |
2bfff7d69a83051426d7016ed3f760dcd634cb0e
|
Go
|
rootulp/exercism
|
/go/diffie-hellman/diffie_hellman_test.go
|
UTF-8
| 4,777 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package diffiehellman
import (
"math/big"
"testing"
)
type testCase struct {
g int64 // prime, generator
p *big.Int // prime, modulus
a, b *big.Int // private keys
A, B *big.Int // public keys
s *big.Int // secret key
}
// WP example
var smallTest = testCase{
5,
big.NewInt(23),
big.NewInt(6), big.NewInt(15),
big.NewInt(8), big.NewInt(19),
big.NewInt(2),
}
// 1024 bit example modulus from cryptopp.com wiki, random private keys
var biggerTest = testCase{
2,
mph("ab359aa76a6773ed7a93b214db0c25d0160817b8a893c001c761e198a3694509" +
"ebe87a5313e0349d95083e5412c9fc815bfd61f95ddece43376550fdc624e92f" +
"f38a415783b97261204e05d65731bba1ccff0e84c8cd2097b75feca1029261ae" +
"19a389a2e15d2939314b184aef707b82eb94412065181d23e04bf065f4ac413f"),
mph("2f6afe91cb53ecfa463d45cd800c948f7cb83bb9ddc62a07b5b3fd302d0cdf52" +
"18ae53ad015a632d137001a3b34239d54715606a292b6cf895b09d7dcf1bdf7a"),
mph("3651007bfa8a8b1cbaed2ae9326327599249c3bb6e9d8744b7407f3d4732cb8a" +
"0708d95c382747bad640d444f135e7e599618d11b15b9ef32e7ac7194e547f4b"),
mph("57d5489e3858cbd8fae75120907d1521f8e935cce2206d285b11762847e2a4c4" +
"a341a4eea18bdd8b40036c8d0004ffc323d5ae19da55176b08ff6f2d0ac97c65" +
"357c1f16756a6901ff926c8544c8af0a90ed2705966851f79a115cb77aac66be" +
"ceff569aadd7f02859539c28d55c08c62a03e45613bc52d205ace0704ea7c610"),
mph("6b189a36db5ca3ff83b66fb2c226078294c323f4c7cef35c506c237b0db7906d" +
"64cceb05af15a3603a30fd49834d3a6971d917f520d9a577c159d3b7d2bd8813" +
"5d19db47a9618340e4a51ec8845dbf5d50a4c6f14d6161def1eeaacecee8018f" +
"8816113a294959399989b759f4618e35dbffc570ab2a5a74ac59fccef35f684c"),
mph("64f74babc466f8e56d9b77ce2cc65d65fe1603b931c018b98a2a615d66172590" +
"803a94ac230db02de4b8ae567497c1844a6f7bd5bed69b95d3137acc1a6462d5" +
"aeba5b2b83a0e6b8ed4c072e5135a57c87b654ebe04cf128bbff49ee06df33b7" +
"8615e0067fdc9df22f7673b1e0501fb57598c7bff9ff173ddff47270fbd6f98f"),
}
// must parse hex, short name contrived just to make test data line up with
// tab width 4.
func mph(h string) *big.Int {
p, ok := new(big.Int).SetString(h, 16)
if !ok {
panic("invalid hex: " + h)
}
return p
}
var tests = []testCase{
smallTest,
biggerTest,
}
var _one = big.NewInt(1)
// test that PrivateKey returns numbers in range, returns different numbers.
func TestPrivateKey(t *testing.T) {
priv := func(p *big.Int) *big.Int {
a := PrivateKey(p)
if a.Cmp(_one) <= 0 || a.Cmp(p) >= 0 {
t.Fatalf("PrivateKey(%s) = %s, out of range (1, %s)", p.String(), a.String(), p.String())
}
return a
}
ms := map[string]bool{}
mb := map[string]bool{}
for i := 0; i < 100; i++ {
ms[priv(smallTest.p).String()] = true
mb[priv(biggerTest.p).String()] = true
}
if len(ms) == 1 {
t.Fatalf("For prime %s same key generated every time. "+
"Want random keys.", smallTest.p.String())
}
if len(mb) < 100 {
t.Fatalf("For prime %s duplicate keys generated. "+
"Want unique keys.", biggerTest.p.String())
}
}
// test that PublicKey returns known results.
func TestPublicKey(t *testing.T) {
tp := func(a, A, p *big.Int, g int64) {
if k := PublicKey(a, p, g); k.Cmp(A) != 0 {
t.Fatalf("PublicKey(%x,\n%x,\n%d)\n= %x,\nwant %x.",
a, p, g, k, A)
}
}
for _, test := range tests {
tp(test.a, test.A, test.p, test.g)
tp(test.b, test.B, test.p, test.g)
}
}
// test that SecretKey returns known results.
func TestSecretKeys(t *testing.T) {
tp := func(a, B, p, s *big.Int) {
if k := SecretKey(a, B, p); k.Cmp(s) != 0 {
t.Fatalf("SecretKey(%x,\n%x,\n%x)\n= %x,\nwant %x.",
a, B, p, k, s)
}
}
for _, test := range tests {
tp(test.a, test.B, test.p, test.s)
tp(test.b, test.A, test.p, test.s)
}
}
// test that NewPair produces working keys
func TestNewPair(t *testing.T) {
p, g := biggerTest.p, biggerTest.g
test := func(a, A *big.Int) {
if a.Cmp(_one) <= 0 || a.Cmp(p) >= 0 {
t.Fatalf("NewPair(%s, %d) private key = %s, out of range (1, %s)",
p.String(), g, a.String(), p.String())
}
if A.Cmp(_one) <= 0 || A.Cmp(p) >= 0 {
t.Fatalf("NewPair(%s, %d) public key = %s, out of range (1, %s)",
p.String(), g, A.String(), p.String())
}
}
a, A := NewPair(p, g)
test(a, A)
for i := 0; i < 20; i++ {
b, B := NewPair(p, g)
test(b, B)
sa := SecretKey(a, B, p)
sb := SecretKey(b, A, p)
if sa.Cmp(sb) != 0 {
t.Fatalf("SecretKey(%d, %d, %d) != SecretKey(%d, %d, %d)", a, B, p, b, A, p)
}
a, A = b, B
}
}
func BenchmarkPrivateKey(b *testing.B) {
if testing.Short() {
b.Skip("skipping benchmark in short mode.")
}
for i := 0; i < b.N; i++ {
PrivateKey(biggerTest.p)
}
}
func BenchmarkPublicKey(b *testing.B) {
if testing.Short() {
b.Skip("skipping benchmark in short mode.")
}
for i := 0; i < b.N; i++ {
PublicKey(biggerTest.a, biggerTest.p, biggerTest.g)
}
}
func BenchmarkNewPair(b *testing.B) {
if testing.Short() {
b.Skip("skipping benchmark in short mode.")
}
for i := 0; i < b.N; i++ {
NewPair(biggerTest.p, biggerTest.g)
}
}
func BenchmarkSecretKey(b *testing.B) {
if testing.Short() {
b.Skip("skipping benchmark in short mode.")
}
for i := 0; i < b.N; i++ {
SecretKey(biggerTest.a, biggerTest.B, biggerTest.p)
}
}
| true |
9a1d7ec814177b942e1aa014a1335e8aed8f8151
|
Go
|
mastercactapus/sdfx
|
/sdf/stl.go
|
UTF-8
| 1,658 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
//-----------------------------------------------------------------------------
/*
STL Load/Save
*/
//-----------------------------------------------------------------------------
package sdf
import (
"encoding/binary"
"os"
)
//-----------------------------------------------------------------------------
type STLHeader struct {
_ [80]uint8 // Header
Count uint32 // Number of triangles
}
type STLTriangle struct {
Normal, Vertex1, Vertex2, Vertex3 [3]float32
_ uint16 // Attribute byte count
}
//-----------------------------------------------------------------------------
func SaveSTL(path string, mesh *Mesh) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
header := STLHeader{}
header.Count = uint32(len(mesh.Triangles))
if err := binary.Write(file, binary.LittleEndian, &header); err != nil {
return err
}
for _, triangle := range mesh.Triangles {
n := triangle.Normal()
d := STLTriangle{}
d.Normal[0] = float32(n.X)
d.Normal[1] = float32(n.Y)
d.Normal[2] = float32(n.Z)
d.Vertex1[0] = float32(triangle.V[0].X)
d.Vertex1[1] = float32(triangle.V[0].Y)
d.Vertex1[2] = float32(triangle.V[0].Z)
d.Vertex2[0] = float32(triangle.V[1].X)
d.Vertex2[1] = float32(triangle.V[1].Y)
d.Vertex2[2] = float32(triangle.V[1].Z)
d.Vertex3[0] = float32(triangle.V[2].X)
d.Vertex3[1] = float32(triangle.V[2].Y)
d.Vertex3[2] = float32(triangle.V[2].Z)
if err := binary.Write(file, binary.LittleEndian, &d); err != nil {
return err
}
}
return nil
}
//-----------------------------------------------------------------------------
| true |
5eba2f1ea56fac97612f0896f796b4387f93d51b
|
Go
|
danilopolani/gosc
|
/number_test.go
|
UTF-8
| 1,176 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package gosc
import (
"testing"
)
// TestIsInt tests the IsInt function
func TestIsInt(t *testing.T) {
t.Parallel()
var tests = []struct {
data string
expected bool
}{
{"", false},
{"주", false},
{"nil", false},
{"null", false},
{"1", true},
{"0", true},
{"1111-", false},
{"-1", true},
{"5.3", false},
{"\u0031", true},
{"\x31", true},
}
for _, test := range tests {
actual := IsInt(test.data)
if actual != test.expected {
t.Errorf("Expected IsInt(%q) to be %v, got %v", test.data, test.expected, actual)
}
}
}
// TestIsFloat tests the IsFloat function
func TestIsFloat(t *testing.T) {
t.Parallel()
var tests = []struct {
data string
expected bool
}{
{"", false},
{"주", false},
{"nil", false},
{"null", false},
{"1", true},
{"0", true},
{"1111-", false},
{"-1", true},
{"-1.65", true},
{"5.3", true},
{"\u0031", true},
{"\x31", true},
{"\u0035\u002e\u0033", true},
{"\x35\x2e\x33", true},
}
for _, test := range tests {
actual := IsFloat(test.data)
if actual != test.expected {
t.Errorf("Expected IsFloat(%q) to be %v, got %v", test.data, test.expected, actual)
}
}
}
| true |
02644575031b236107aab7396ff1ae3990fd6093
|
Go
|
Alisahhh/singularity
|
/internal/pkg/client/cache/shub.go
|
UTF-8
| 1,499 | 2.734375 | 3 |
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
// Copyright (c) 2018-2019, Sylabs Inc. All rights reserved.
// This software is licensed under a 3-clause BSD license. Please consult the
// LICENSE.md file distributed with the sources of this project regarding your
// rights to use or distribute this software.
package cache
import (
"os"
"path/filepath"
)
const (
// ShubDir is the directory inside the cache.Dir where shub images are cached
ShubDir = "shub"
)
// Shub returns the directory inside the cache.Dir() where shub images are cached
func getShubCachePath(c *Handle) (string, error) {
// This function may act on an cache object that is not fully initialized
// so it is not a method on a Handle but rather an independent
// function
// updateCacheSubdir checks if the cache is valid, no need to check here
return updateCacheSubdir(c, ShubDir)
}
// ShubImage creates a directory inside cache.Dir() with the name of the SHA sum of the image
func (c *Handle) ShubImage(sum, name string) string {
if c.disabled {
return ""
}
_, err := updateCacheSubdir(c, filepath.Join(ShubDir, sum))
if err != nil {
return ""
}
return filepath.Join(c.Shub, sum, name)
}
// ShubImageExists returns whether the image with the SHA sum exists in the ShubImage cache
func (c *Handle) ShubImageExists(sum, name string) (bool, error) {
if c.disabled {
return false, nil
}
_, err := os.Stat(c.ShubImage(sum, name))
if os.IsNotExist(err) {
return false, nil
} else if err != nil {
return false, err
}
return true, nil
}
| true |
f6b950ad60e1edcc63e59716a7bfa37a67a10d70
|
Go
|
go-graphite/carbonapi
|
/expr/holtwinters/hw.go
|
UTF-8
| 4,574 | 2.921875 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
[
"BSD-2-Clause"
] |
permissive
|
package holtwinters
// This holt-winters code copied from graphite's functions.py)
// It's "mostly" the same as a standard HW forecast
import (
"math"
)
const (
DefaultSeasonality = 86400 // Seconds in 1 day
DefaultBootstrapInterval = 604800 // Seconds in 7 days
SecondsPerDay = 86400
)
func holtWintersIntercept(alpha, actual, lastSeason, lastIntercept, lastSlope float64) float64 {
return alpha*(actual-lastSeason) + (1-alpha)*(lastIntercept+lastSlope)
}
func holtWintersSlope(beta, intercept, lastIntercept, lastSlope float64) float64 {
return beta*(intercept-lastIntercept) + (1-beta)*lastSlope
}
func holtWintersSeasonal(gamma, actual, intercept, lastSeason float64) float64 {
return gamma*(actual-intercept) + (1-gamma)*lastSeason
}
func holtWintersDeviation(gamma, actual, prediction, lastSeasonalDev float64) float64 {
if math.IsNaN(prediction) {
prediction = 0
}
return gamma*math.Abs(actual-prediction) + (1-gamma)*lastSeasonalDev
}
// HoltWintersAnalysis do Holt-Winters Analysis
func HoltWintersAnalysis(series []float64, step int64, seasonality int64) ([]float64, []float64) {
const (
alpha = 0.1
beta = 0.0035
gamma = 0.1
)
seasonLength := seasonality / step
// seasonLength needs to be at least 2, so we force it
// GraphiteWeb has the same problem, still needs fixing https://github.com/graphite-project/graphite-web/issues/2780
if seasonLength < 2 {
seasonLength = 2
}
var (
intercepts []float64
slopes []float64
seasonals []float64
predictions []float64
deviations []float64
)
getLastSeasonal := func(i int) float64 {
j := i - int(seasonLength)
if j >= 0 {
return seasonals[j]
}
return 0
}
getLastDeviation := func(i int) float64 {
j := i - int(seasonLength)
if j >= 0 {
return deviations[j]
}
return 0
}
var nextPred = math.NaN()
for i, actual := range series {
if math.IsNaN(actual) {
// missing input values break all the math
// do the best we can and move on
intercepts = append(intercepts, math.NaN())
slopes = append(slopes, 0)
seasonals = append(seasonals, 0)
predictions = append(predictions, nextPred)
deviations = append(deviations, 0)
nextPred = math.NaN()
continue
}
var (
lastSlope float64
lastIntercept float64
prediction float64
)
if i == 0 {
lastIntercept = actual
lastSlope = 0
// seed the first prediction as the first actual
prediction = actual
} else {
lastIntercept = intercepts[len(intercepts)-1]
lastSlope = slopes[len(slopes)-1]
if math.IsNaN(lastIntercept) {
lastIntercept = actual
}
prediction = nextPred
}
lastSeasonal := getLastSeasonal(i)
nextLastSeasonal := getLastSeasonal(i + 1)
lastSeasonalDev := getLastDeviation(i)
intercept := holtWintersIntercept(alpha, actual, lastSeasonal, lastIntercept, lastSlope)
slope := holtWintersSlope(beta, intercept, lastIntercept, lastSlope)
seasonal := holtWintersSeasonal(gamma, actual, intercept, lastSeasonal)
nextPred = intercept + slope + nextLastSeasonal
deviation := holtWintersDeviation(gamma, actual, prediction, lastSeasonalDev)
intercepts = append(intercepts, intercept)
slopes = append(slopes, slope)
seasonals = append(seasonals, seasonal)
predictions = append(predictions, prediction)
deviations = append(deviations, deviation)
}
return predictions, deviations
}
// HoltWintersConfidenceBands do Holt-Winters Confidence Bands
func HoltWintersConfidenceBands(series []float64, step int64, delta float64, bootstrapInterval int64, seasonality int64) ([]float64, []float64) {
var lowerBand, upperBand []float64
predictions, deviations := HoltWintersAnalysis(series, step, seasonality)
windowPoints := int(bootstrapInterval / step)
var (
predictionsOfInterest []float64
deviationsOfInterest []float64
)
if len(predictions) < windowPoints || len(deviations) < windowPoints {
predictionsOfInterest = predictions
deviationsOfInterest = deviations
} else {
predictionsOfInterest = predictions[windowPoints:]
deviationsOfInterest = deviations[windowPoints:]
}
for i := range predictionsOfInterest {
if math.IsNaN(predictionsOfInterest[i]) || math.IsNaN(deviationsOfInterest[i]) {
lowerBand = append(lowerBand, math.NaN())
upperBand = append(upperBand, math.NaN())
} else {
scaledDeviation := delta * deviationsOfInterest[i]
lowerBand = append(lowerBand, predictionsOfInterest[i]-scaledDeviation)
upperBand = append(upperBand, predictionsOfInterest[i]+scaledDeviation)
}
}
return lowerBand, upperBand
}
| true |
5fddaf376237ae936b270fa2fcb79ab94c89a662
|
Go
|
rmahidhar/graph
|
/adjlist/adjlist.go
|
UTF-8
| 3,233 | 3.21875 | 3 |
[] |
no_license
|
[] |
no_license
|
package adjlist
import (
"fmt"
"github.com/rmahidhar/graph"
)
type vertex struct {
id uint32
name string
outEdges map[string]*edge
inEdges map[string]*edge
//outEdges []*edge
//inEdges []*edge
}
type edge struct {
src string
dst string
property map[string]interface{}
}
type AdjList struct {
numVertices uint32
numEdges uint32
vertexmap map[string]*vertex
}
func New() graph.Graph {
return new(AdjList).Init()
}
func (g *AdjList) Init() graph.Graph {
g.numVertices = 0
g.numEdges = 0
g.vertexmap = make(map[string]*vertex)
return g
}
func (g *AdjList) AddVertex(name string) {
g.numVertices += 1
v := &vertex{
id: g.numVertices,
name: name,
outEdges: make(map[string]*edge),
inEdges: make(map[string]*edge),
}
g.vertexmap[name] = v
}
func (g *AdjList) AddEdge(src string, dst string) error {
v, srcexist := g.vertexmap[src]
_, dstexist := g.vertexmap[dst]
if srcexist && dstexist {
e := &edge{
src: src,
dst: dst,
property: make(map[string]interface{}),
}
//v.outEdges = append(v.outEdges, e)
//v.inEdges = append(v.inEdges, e)
v.outEdges[dst] = e
v.inEdges[dst] = e
return nil
} else {
if srcexist {
return fmt.Errorf("dst vertex %s doesnt exist", dst)
} else if dstexist {
return fmt.Errorf("src vertex %s doesnt exist", src)
} else {
return fmt.Errorf("src %s and dst %s vertex doesnt exist", src, dst)
}
}
}
func (g *AdjList) SetEdgeProperty(src string, dst string, name string, val interface{}) error {
v, srcexist := g.vertexmap[src]
_, dstexist := g.vertexmap[dst]
if srcexist && dstexist {
v.outEdges[dst].property[name] = val
v.inEdges[dst].property[name] = val
return nil
} else {
if srcexist {
return fmt.Errorf("dst vertex %s doesnt exist", dst)
} else if dstexist {
return fmt.Errorf("src vertex %s doesnt exist", src)
} else {
return fmt.Errorf("src %s and dst %s vertex doesnt exist", src, dst)
}
}
}
func (g *AdjList) GetEdgeProperty(src string, dst string, name string) (interface{}, error) {
v, vexist := g.vertexmap[src]
if vexist {
e, exist := v.outEdges[dst]
if exist {
p, valid := e.property[name]
if valid {
return p, nil
} else {
return nil, fmt.Errorf("property %s doesnt exist", name)
}
} else {
return nil, fmt.Errorf("edge %s -> %s doesnt exist", src, dst)
}
} else {
return nil, fmt.Errorf("src vertex %s doesnt exist", src)
}
}
func Keys(m map[string]*edge) []string {
/*
v := reflect.ValueOf(m)
if v.Kind() != reflect.Map {
return nil
}
return v.MapKeys()
*/
var keys []string
for k := range m {
keys = append(keys, k)
}
return keys
}
func (g *AdjList) GetInEdges(name string) ([]string, error) {
v, exist := g.vertexmap[name]
if exist {
return Keys(v.inEdges), nil
}
return nil, fmt.Errorf("vertext %s doesn't exist", name)
}
func (g *AdjList) GetOutEdges(name string) ([]string, error) {
v, exist := g.vertexmap[name]
if exist {
return Keys(v.outEdges), nil
}
return nil, fmt.Errorf("vertext %s doesn't exist", name)
}
func (g *AdjList) GetNumVertices() uint32 {
return g.numVertices
}
func (g *AdjList) GetNumEdges() uint32 {
return g.numEdges
}
| true |
52f162cd8dbaa78b07ec3500706acdfb61974b07
|
Go
|
mardongvo/checkis
|
/docx_template.go
|
UTF-8
| 3,453 | 2.96875 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"archive/zip"
"io"
"log"
"strings"
"github.com/beevik/etree"
)
const DOCUMENT_CONTENT = "word/document.xml"
type DocxTemplate struct {
source *zip.ReadCloser
content *etree.Document //"word/document.xml"
}
func OpenTemplate(path string) (DocxTemplate, error) {
var docx DocxTemplate
var err error
docx.source, err = zip.OpenReader(path)
if err != nil {
return docx, err
}
for _, f := range docx.source.File {
if f.Name != DOCUMENT_CONTENT {
continue
}
rc, err := f.Open()
if err != nil {
return docx, err
}
docx.content = etree.NewDocument()
docx.content.ReadFrom(rc)
rc.Close()
}
return docx, nil
}
func (docx *DocxTemplate) Close() error {
return docx.source.Close()
}
func (docx *DocxTemplate) Write(output io.Writer) error {
writer := zip.NewWriter(output)
for _, fsource := range docx.source.File {
fout, err := writer.Create(fsource.Name)
if err != nil {
return err
}
if fsource.Name == DOCUMENT_CONTENT {
docx.content.WriteTo(fout)
} else {
fin, err := fsource.Open()
if err != nil {
return err
}
defer fin.Close()
_, err = io.Copy(fout, fin)
if err != nil {
return err
}
}
}
err := writer.Close()
if err != nil {
return err
}
return nil
}
type TreeWalkFunction func(e *etree.Element)
func walkTree(root *etree.Element, callback TreeWalkFunction) {
for _, r := range root.ChildElements() {
callback(r)
walkTree(r, callback)
}
}
//walk tree, replace text in <t> elements
//replacementPairs = []string{"#template_var1#", "value1", "#template_var2#", "value2"...}
func (docx *DocxTemplate) Replace(replacementPairs []string) {
replacer := strings.NewReplacer(replacementPairs...)
walkTree(docx.content.Root(), func(e *etree.Element) {
if e.Tag == "t" {
e.SetText(replacer.Replace(e.Text()))
}
})
}
func (docx *DocxTemplate) ReplaceToList(parent_tag string, marker string, replacementList [][]string) {
var multilineT []*etree.Element = make([]*etree.Element, 0)
var multilineP *etree.Element = nil
var multilineParent *etree.Element = nil
var multilinePos int = -1
//1. находим все <t>, содержащий #marker#
walkTree(docx.content.Root(), func(e *etree.Element) {
if e.Tag == "t" {
if strings.Index(e.Text(), marker) >= 0 {
multilineT = append(multilineT, e)
}
}
})
if len(multilineT) == 0 {
return
}
for _, mT := range multilineT {
//2. находим ближайшего предка <t> с тегом parent_tag
multilineP = mT.Parent()
for {
if multilineP == nil {
log.Printf("ReplaceToList: (%v) no parent (multilineP)", mT)
goto CONT
}
if multilineP.Tag == parent_tag {
break
}
multilineP = multilineP.Parent()
}
multilineParent = multilineP.Parent()
if multilineParent == nil {
log.Printf("ReplaceToList: (%v) no parent (multilineParent)", mT)
goto CONT
}
multilinePos = multilineP.Index()
//создаем копии parent_tag, заменяем в них поля, вставляем перед parent_tag
for _, replPairs := range replacementList {
copyP := multilineP.Copy()
replacer := strings.NewReplacer(replPairs...)
walkTree(copyP, func(e *etree.Element) {
if e.Tag == "t" {
e.SetText(replacer.Replace(e.Text()))
}
})
multilineParent.InsertChildAt(multilinePos, copyP)
multilinePos += 1
}
multilineParent.RemoveChildAt(multilinePos)
CONT:
{
}
}
}
| true |
53587671802f04ec923ad52cb6e4a5acffab8828
|
Go
|
oswystan/bitmain
|
/controller/util.go
|
UTF-8
| 1,219 | 2.59375 | 3 |
[] |
no_license
|
[] |
no_license
|
//===============================================================================
// Copyright (C) 2017 wystan
//
// filename: util.go
// description:
// created: 2017-06-10 14:55:17
// author: wystan
//
//===============================================================================
package controller
import (
"encoding/json"
"io"
"io/ioutil"
"net/http"
"github.com/oswystan/bitmain/utils"
)
var logger = utils.Logger()
func sendResponse(w http.ResponseWriter, v interface{}, code int) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
if v == nil {
w.WriteHeader(code)
return
}
bs, err := json.MarshalIndent(v, "", "\t")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
bs = append(bs, '\n')
w.WriteHeader(code)
w.Write(bs)
}
func decodeBody(r *http.Request, v ...interface{}) error {
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 8192))
if err != nil {
return err
}
r.Body.Close()
for i := 0; i < len(v); i++ {
if err = json.Unmarshal(body, v[i]); err != nil {
return err
}
}
return nil
}
//==================================== END ======================================
| true |
5ea31b6a5d679ffafc475c51a4d30eee6f479a5a
|
Go
|
gugulee/practice
|
/pkg/list/single/cycle/list.go
|
UTF-8
| 2,233 | 3.84375 | 4 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package cycle
import "fmt"
type ListNode struct {
Next *ListNode
value interface{}
}
type LinkList struct {
head *ListNode
len uint32
}
// create list node
func NewNode(value interface{}) *ListNode {
return &ListNode{value: value}
}
// create list
func NewLinkList() *LinkList {
list := &LinkList{NewNode(nil), 0}
list.head.Next = list.head
return list
}
func (l *LinkList) Length() uint32 {
return l.len
}
func (l *LinkList) Head() *ListNode {
return l.head
}
func (n *ListNode) Value() interface{} {
return n.value
}
// insert new node at list head
func (l *LinkList) InsertHead(value string) {
head := l.head
l.InsertAfter(head, value)
}
// insert new node at list tail
func (l *LinkList) InsertTail(value string) {
head := l.head
node := head
for ; node.Next != head; node = node.Next {
}
l.InsertAfter(node, value)
}
// insert new node after node
func (l *LinkList) InsertAfter(node *ListNode, value string) {
newNode := NewNode(value)
newNode.Next = node.Next
node.Next = newNode
l.len++
}
// SearchListBynode determine whether the node is in the list, return true when exist, otherwise return false
func (l *LinkList) SearchListBynode(target *ListNode) bool {
if nil == target {
return false
}
node := l.head.Next
for ; node != l.head; node = node.Next {
if node == target {
return true
}
}
return false
}
// if value exist in list, return node, otherwise, return nil
func (l *LinkList) SearchListByValue(value string) *ListNode {
node := l.head.Next
for ; node != l.head; node = node.Next {
if node.value == value {
return node
}
}
return nil
}
// delete node from list
func (l *LinkList) DeleteNode(target *ListNode) bool {
if nil == target {
return false
}
node := l.head.Next
pre := l.head
for ; node != l.head; node = node.Next {
if node == target {
break
}
pre = node
}
if node == l.head {
return false
}
pre.Next = target.Next
target = nil
l.len--
return true
}
// Print return the whole list
func (l *LinkList) Print() string {
head := l.head
next := head.Next
info := ""
for ; next != head; next = next.Next {
info += fmt.Sprintf("%+v", next.value)
if head != next.Next {
info += "->"
}
}
return info
}
| true |
4b02575328600e259793f35cfbe194ae4b25581b
|
Go
|
snikch/aggro
|
/resultset.go
|
UTF-8
| 4,176 | 3.09375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package aggro
import (
"fmt"
"strings"
)
// Resultset represents a complete set of result buckets and any associated errors.
type Resultset struct {
Errors []error `json:"errors"`
Buckets []*ResultBucket `json:"buckets"`
Composition []interface{} `json:"-"`
}
// ResultBucket represents recursively built metrics for our tablular data.
type ResultBucket struct {
Value string `json:"value"`
Metrics map[string]interface{} `json:"metrics"`
Buckets []*ResultBucket `json:"buckets"`
bucketLookup map[string]*ResultBucket
sourceRows []map[string]Cell
}
// ResultTable represents a Resultset split into row / columns at a depth.
type ResultTable struct {
Rows [][]map[string]interface{} `json:"rows"`
RowTitles [][]string `json:"row_titles"`
ColumnTitles [][]string `json:"column_titles"`
}
// Concrete errors.
var (
ErrTargetDepthTooLow = fmt.Errorf("Tabulate: target depth should be 1 or above")
ErrTargetDepthNotReached = fmt.Errorf("Tabulate: reached deepest bucket before hitting target depth")
)
// Tabulate takes a Resultset and converts it to tabular data.
func Tabulate(results *Resultset, depth int) (*ResultTable, error) {
if depth < 1 {
return nil, ErrTargetDepthTooLow
}
// Create our table.
table := &ResultTable{
Rows: [][]map[string]interface{}{},
RowTitles: [][]string{},
ColumnTitles: [][]string{},
}
// And a lookup helper instance.
lookup := &resultLookup{
cells: map[string]map[string]interface{}{},
rowLookup: map[string]bool{},
columnLookup: map[string]bool{},
}
// Recursively build the lookup for each of the root result buckets.
for _, bucket := range results.Buckets {
err := buildLookup([]string{}, 1, depth, table, lookup, bucket)
if err != nil {
return nil, err
}
}
// Now build up the cells for each of the row / column tuples.
for _, row := range table.RowTitles {
tableRow := []map[string]interface{}{}
for _, column := range table.ColumnTitles {
tableRow = append(tableRow, lookup.cells[strings.Join(row, lookupKeyDelimiter)+lookupKeyDelimiter+strings.Join(column, lookupKeyDelimiter)])
}
table.Rows = append(table.Rows, tableRow)
}
// And we're done 👌.
return table, nil
}
// resultLookup stores specific data as the result set is recursively iterated over.
type resultLookup struct {
cells map[string]map[string]interface{}
rowLookup map[string]bool
columnLookup map[string]bool
}
// lookupKeyDelimiter is used to flatten a string array to a single key.
const lookupKeyDelimiter = "😡"
// buildLookup is a recursive function that breaks data into rows and columns
// at a specific depth.
func buildLookup(key []string, depth, targetDepth int, table *ResultTable, lookup *resultLookup, bucket *ResultBucket) error {
// Add the new bucket value to the lookup key.
key = append(key, bucket.Value)
// If we have no buckets, we're at a metric point.
if len(bucket.Buckets) == 0 {
if depth <= targetDepth {
return ErrTargetDepthNotReached
}
// The column key is made up of just the key parts from the target depth.
columnKey := strings.Join(key[targetDepth:], lookupKeyDelimiter)
// If we haven't seen this column tuple before, add it to the lookup.
if _, ok := lookup.columnLookup[columnKey]; !ok {
table.ColumnTitles = append(table.ColumnTitles, key[targetDepth:])
lookup.columnLookup[columnKey] = true
}
m := bucket.Metrics
lookup.cells[strings.Join(key, lookupKeyDelimiter)] = m
return nil
}
// If we've reached target depth, add this key to the rows if it's not there.
if depth == targetDepth {
rowKey := strings.Join(key, lookupKeyDelimiter)
if _, ok := lookup.rowLookup[rowKey]; !ok {
table.RowTitles = append(table.RowTitles, key)
lookup.rowLookup[rowKey] = true
}
}
// Now continue down the 🐇 hole with the next depth of result buckets.
for _, bucket := range bucket.Buckets {
newKey := make([]string, len(key))
copy(newKey, key)
err := buildLookup(newKey, depth+1, targetDepth, table, lookup, bucket)
if err != nil {
return err
}
}
return nil
}
| true |
e190c8fce34db16f6c7322599d6ffe4f84254bfe
|
Go
|
dekoch/gouniversal
|
/shared/hashstor/hashstor.go
|
UTF-8
| 1,537 | 3.390625 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package hashstor
import (
"errors"
"sort"
"sync"
"time"
)
type HashStor struct {
mut sync.RWMutex
Hashes []Hash
}
type Hash struct {
Hash string
Expired time.Time
requested time.Time
}
func (hs *HashStor) Init() {
hs.mut.Lock()
defer hs.mut.Unlock()
t := time.Now()
for i := range hs.Hashes {
hs.Hashes[i].requested = t
}
}
func (hs *HashStor) Add(str string) {
hs.mut.Lock()
defer hs.mut.Unlock()
for i := range hs.Hashes {
if hs.Hashes[i].Hash == str {
return
}
}
var n Hash
n.Hash = str
hs.Hashes = append(hs.Hashes, n)
}
func (hs *HashStor) Remove(str string) {
hs.mut.Lock()
defer hs.mut.Unlock()
var l []Hash
for i := range hs.Hashes {
if str != hs.Hashes[i].Hash {
l = append(l, hs.Hashes[i])
}
}
hs.Hashes = l
}
func (hs *HashStor) RemoveAll() {
hs.mut.Lock()
defer hs.mut.Unlock()
var l []Hash
hs.Hashes = l
}
func (hs *HashStor) SetAsExpired(str string, to time.Duration) {
hs.mut.Lock()
defer hs.mut.Unlock()
for i := range hs.Hashes {
if hs.Hashes[i].Hash == str {
hs.Hashes[i].Expired = time.Now().Add(to)
return
}
}
}
func (hs *HashStor) GetHash() (string, error) {
hs.mut.Lock()
defer hs.mut.Unlock()
sort.Slice(hs.Hashes, func(i, j int) bool { return hs.Hashes[i].requested.Unix() < hs.Hashes[j].requested.Unix() })
for i := range hs.Hashes {
if time.Now().After(hs.Hashes[i].Expired) {
hs.Hashes[i].requested = time.Now()
return hs.Hashes[i].Hash, nil
}
}
return "", errors.New("no hash found")
}
| true |
408cdf560239b40f759b7eebaca7fa4abe8fdf89
|
Go
|
felipefbs/tecnicas-avancadas-programacao
|
/tap/q1018.go
|
UTF-8
| 1,205 | 3.359375 | 3 |
[] |
no_license
|
[] |
no_license
|
package tap
import "fmt"
// Q1018 https://www.urionlinejudge.com.br/judge/pt/problems/view/1018
func Q1018() {
var number int
var cem, cinquenta, vinte, dez, cinco, dois, um int
fmt.Scanf("%d", &number)
centenaMilhar := number / 100000 * 100000
dezenaMilhar := number % 100000 / 10000 * 10000
unidadeMilhar := number % 10000 / 1000 * 1000
centenas := number % 1000 / 100 * 100
dezenas := number % 100 / 10 * 10
unidade := number % 10
for centenaMilhar > 0 {
centenaMilhar -= 100
cem++
}
for dezenaMilhar > 0 {
dezenaMilhar -= 100
cem++
}
for unidadeMilhar > 0 {
unidadeMilhar -= 100
cem++
}
for centenas > 0 {
centenas -= 100
cem++
}
for dezenas >= 50 {
dezenas -= 50
cinquenta++
}
for dezenas >= 20 {
dezenas -= 20
vinte++
}
for dezenas >= 10 {
dezenas -= 10
dez++
}
for unidade >= 5 {
unidade -= 5
cinco++
}
for unidade >= 2 {
unidade -= 2
dois++
}
for unidade >= 1 {
unidade--
um++
}
fmt.Printf("%d\n%d nota(s) de R$ 100,00\n%d nota(s) de R$ 50,00\n%d nota(s) de R$ 20,00\n%d nota(s) de R$ 10,00\n%d nota(s) de R$ 5,00\n%d nota(s) de R$ 2,00\n%d nota(s) de R$ 1,00\n", number, cem, cinquenta, vinte, dez, cinco, dois, um)
}
| true |
0ad1feb7890ab95eb41990014a9c3cba32de0ab2
|
Go
|
FlorianLoch/changeCheck
|
/internal/channelUtils_test.go
|
UTF-8
| 429 | 2.8125 | 3 |
[] |
no_license
|
[] |
no_license
|
package internal
import (
"testing"
"time"
)
func TestMerge(t *testing.T) {
chan1 := make(chan interface{})
chan2 := make(chan interface{})
merged := Merge(chan1, chan2)
go func() {
chan1 <- nil
chan2 <- nil
chan2 <- nil
chan1 <- nil
}()
// Blocks if we cannot get all entries
for range [4]int{} {
<-merged
}
}
func TestTick(t *testing.T) {
tickChan := Tick(time.Duration(1))
<-tickChan
<-tickChan
}
| true |
6f7ce79c8177acc32bc80256c86c1fa47ba09f8a
|
Go
|
mauriciosl/cursogo
|
/keydb/handlers.go
|
UTF-8
| 1,300 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package keydb
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/gorilla/mux"
)
// servehttp START OMIT
func (d *DB) ServeHTTP(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
key := vars["key"]
switch req.Method {
case "GET":
d.HandleGet(key, w, req)
case "POST":
d.HandleSet(key, w, req)
default:
http.Error(w, "Unsupported method", http.StatusBadRequest)
}
}
// servehttp END OMIT
// get START OMIT
func (d *DB) HandleGet(key string, w http.ResponseWriter, req *http.Request) {
result, ok := d.Get(key)
if !ok {
http.Error(w, "Not Found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
enc := json.NewEncoder(w)
enc.Encode(result)
}
// get END OMIT
// set START OMIT
func (d *DB) HandleSet(key string, w http.ResponseWriter, req *http.Request) {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
newValue := map[string]interface{}{}
err = json.Unmarshal(body, &newValue)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
exists := d.Set(key, newValue)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
fmt.Fprintf(w, "%t", exists)
}
// set END OMIT
| true |
1a027949280b45dfe033b48294f9c2ce904e1344
|
Go
|
zhiyi1988/easyss
|
/util/http2frame.go
|
UTF-8
| 1,764 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package util
import (
"encoding/binary"
"math/rand"
"sync"
log "github.com/sirupsen/logrus"
)
var lenPool = sync.Pool{
New: func() interface{} {
buf := make([]byte, 4)
return buf
},
}
func EncodeHTTP2DataFrameHeader(datalen int, dst []byte) (header []byte) {
if len(dst) < 9 {
dst = make([]byte, 9)
} else if len(dst) > 9 {
dst = dst[:9]
}
length := lenPool.Get().([]byte)
defer lenPool.Put(length)
binary.BigEndian.PutUint32(length, uint32(datalen))
// set length field
copy(dst[:3], length[1:])
// set frame type to data
dst[3] = 0x0
// set default flag
dst[4] = 0x0
if datalen < 512 { // data has padding field
log.Debugf("data payload size:%v, less than 512 bytes, we add padding field", datalen)
dst[4] = 0x8
}
// set stream identifier. note: this is temporary, will update in future
binary.BigEndian.PutUint32(dst[5:9], uint32(rand.Int31()))
return dst
}
func EncodeFINRstStreamHeader(dst []byte) (header []byte) {
if len(dst) < 9 {
dst = make([]byte, 9)
} else if len(dst) > 9 {
dst = dst[:9]
}
binary.BigEndian.PutUint16(dst[1:3], uint16(4))
// set frame type to RST_STREAM
dst[3] = 0x7
// set default flag
dst[4] = 0x0
// set stream identifier. note: this is temporary, will update in future
binary.BigEndian.PutUint32(dst[5:9], uint32(rand.Int31()))
return dst
}
func EncodeACKRstStreamHeader(dst []byte) (header []byte) {
if len(dst) < 9 {
dst = make([]byte, 9)
} else if len(dst) > 9 {
dst = dst[:9]
}
binary.BigEndian.PutUint16(dst[1:3], uint16(4))
// set frame type to RST_STREAM
dst[3] = 0x7
// set default flag
dst[4] = 0x1
// set stream identifier. note: this is temporary, will update in future
binary.BigEndian.PutUint32(dst[5:9], uint32(rand.Int31()))
return dst
}
| true |
d7c80b41ff76acfec37592117264a02a8f24715e
|
Go
|
ab22/abcd
|
/services/auth/service.go
|
UTF-8
| 970 | 3.0625 | 3 |
[] |
no_license
|
[] |
no_license
|
package auth
import (
"github.com/ab22/abcd/models"
"github.com/ab22/abcd/services/user"
"github.com/jinzhu/gorm"
)
// Contains all of the logic for the systems authentications.
type authService struct {
db *gorm.DB
userService user.Service
}
// NewService creates a new authentication service.
func NewService(db *gorm.DB, userService user.Service) Service {
return &authService{
db: db,
userService: userService,
}
}
// Basic username/password authentication. BasicAuth checks if the user exists,
// if the passwords match and if the user's state is set as active.
func (s *authService) BasicAuth(username, password string) (*models.User, error) {
u, err := s.userService.FindByUsername(username)
if err != nil {
return nil, err
} else if u == nil || u.Status != int(user.Enabled) {
return nil, nil
}
match := s.userService.ComparePasswords([]byte(u.Password), password)
if !match {
return nil, nil
}
return u, nil
}
| true |
df910a61bdaf1d28ca965aceb57d2c964f91b669
|
Go
|
backwardn/maddy
|
/internal/config/module/interfaces.go
|
UTF-8
| 1,865 | 2.53125 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
package modconfig
import (
"github.com/foxcpp/maddy/internal/config"
"github.com/foxcpp/maddy/internal/module"
)
func MessageCheck(globals map[string]interface{}, args []string, block config.Node) (module.Check, error) {
var check module.Check
if err := ModuleFromNode(args, block, globals, &check); err != nil {
return nil, err
}
return check, nil
}
// deliveryDirective is a callback for use in config.Map.Custom.
//
// It does all work necessary to create a module instance from the config
// directive with the following structure:
// directive_name mod_name [inst_name] [{
// inline_mod_config
// }]
//
// Note that if used configuration structure lacks directive_name before mod_name - this function
// should not be used (call DeliveryTarget directly).
func DeliveryDirective(m *config.Map, node config.Node) (interface{}, error) {
return DeliveryTarget(m.Globals, node.Args, node)
}
func DeliveryTarget(globals map[string]interface{}, args []string, block config.Node) (module.DeliveryTarget, error) {
var target module.DeliveryTarget
if err := ModuleFromNode(args, block, globals, &target); err != nil {
return nil, err
}
return target, nil
}
func MsgModifier(globals map[string]interface{}, args []string, block config.Node) (module.Modifier, error) {
var check module.Modifier
if err := ModuleFromNode(args, block, globals, &check); err != nil {
return nil, err
}
return check, nil
}
func StorageDirective(m *config.Map, node config.Node) (interface{}, error) {
var backend module.Storage
if err := ModuleFromNode(node.Args, node, m.Globals, &backend); err != nil {
return nil, err
}
return backend, nil
}
func TableDirective(m *config.Map, node config.Node) (interface{}, error) {
var tbl module.Table
if err := ModuleFromNode(node.Args, node, m.Globals, &tbl); err != nil {
return nil, err
}
return tbl, nil
}
| true |
48b62645a8c6b267548ecc71b689d6b03b9d5c4f
|
Go
|
CDargis/SecurityAdventures
|
/backend/src/db/db.go
|
UTF-8
| 2,809 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package db
import (
"bufio"
l4g "code.google.com/p/log4go"
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"os"
"strings"
)
type DBConfig struct {
User string
Pass string
DBName string
}
type RowTransformFunc func(*sql.Rows) (interface{}, error)
var dbConfig DBConfig
func Init(path string) {
fullPath := fmt.Sprintf("%s/dbconfig.txt", path)
file, err := os.Open(fullPath)
if err != nil {
l4g.Error("Could not open dbconfig.txt")
return
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
tokens := strings.Split(scanner.Text(), "=")
for index, token := range tokens {
token = strings.Trim(token, " \"")
tokens[index] = token
}
if len(tokens) == 2 {
key := tokens[0]
value := tokens[1]
if key == "User" {
dbConfig.User = value
}
if key == "Pass" {
dbConfig.Pass = value
}
if key == "DBName" {
dbConfig.DBName = value
}
}
}
}
func openDB() (*sql.DB, error) {
openString := fmt.Sprintf("%s:%s@/%s", dbConfig.User, dbConfig.Pass, dbConfig.DBName)
return sql.Open("mysql", openString)
}
func Insert(query string, input []interface{}) (int, error) {
db, err := openDB()
if err != nil {
return -1, err
}
defer db.Close()
stmt, err := db.Prepare(query)
if err != nil {
return -1, err
}
defer stmt.Close()
res, err := stmt.Exec(input...)
if err != nil {
return -1, err
}
id, err := res.LastInsertId()
return int(id), err
}
func QueryRows(query string, input []interface{}, rowTransform RowTransformFunc) ([]interface{}, error) {
var results []interface{}
db, err := openDB()
if err != nil {
return results, err
}
defer db.Close()
stmt, err := db.Prepare(query)
if err != nil {
return results, err
}
defer stmt.Close()
rows, err := stmt.Query(input...)
if err != nil {
return results, err
}
for rows.Next() {
row, err := rowTransform(rows)
if err != nil {
return results, err
}
results = append(results, row)
}
return results, nil
}
func UpdateRow(query string, params []interface{}) error {
db, err := openDB()
if err != nil {
return err
}
defer db.Close()
stmt, err := db.Prepare(query)
if err != nil {
return err
}
defer stmt.Close()
_, err = stmt.Exec(params...)
if err != nil {
return err
}
return nil
}
func Params(value ...interface{}) []interface{} {
return value
}
| true |
7c5fae518eb4091a3ff847ffa1031c847b364bf1
|
Go
|
guilherme-santos/mysql-prepared-conn
|
/main.go
|
UTF-8
| 3,922 | 3 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"database/sql"
"fmt"
"os"
_ "github.com/go-sql-driver/mysql"
)
var mysqlDSQ = "root:root@tcp(127.0.0.1:3306)/mysql-prepared-conn-test"
func main() {
fmt.Println("Connecting to", mysqlDSQ)
db, err := sql.Open("mysql", mysqlDSQ)
if err != nil {
fmt.Println("Unable to connect to mysql:", err)
os.Exit(1)
}
defer db.Close()
printAfter(db, "", nil)
printAfter(db, "do not close stmt", func() error {
stmt, err := db.Prepare("SELECT ?")
if err != nil {
return err
}
var n int
row := stmt.QueryRow("1")
return row.Scan(&n)
})
printAfter(db, "closing stmt", func() error {
stmt, err := db.Prepare("SELECT ?")
if err != nil {
return err
}
defer stmt.Close()
var n int
row := stmt.QueryRow("1")
return row.Scan(&n)
})
printAfter(db, "with transaction: do not close stmt nether commit", func() error {
tx, err := db.Begin()
if err != nil {
return err
}
stmt, err := tx.Prepare("SELECT ?")
if err != nil {
return err
}
var n int
row := stmt.QueryRow("1")
return row.Scan(&n)
})
printAfter(db, "with transaction: closing stmt but not commit", func() error {
tx, err := db.Begin()
if err != nil {
return err
}
stmt, err := tx.Prepare("SELECT ?")
if err != nil {
return err
}
defer stmt.Close()
var n int
row := stmt.QueryRow("1")
return row.Scan(&n)
})
printAfter(db, "with transaction: do not close stmt but commit", func() error {
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Commit()
stmt, err := tx.Prepare("SELECT ?")
if err != nil {
return err
}
var n int
row := stmt.QueryRow("1")
return row.Scan(&n)
})
printAfter(db, "with transaction: do not close stmt but rollback", func() error {
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
stmt, err := tx.Prepare("SELECT ?")
if err != nil {
return err
}
var n int
row := stmt.QueryRow("1")
return row.Scan(&n)
})
printAfter(db, "with transaction: close stmt and commit", func() error {
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Commit()
stmt, err := tx.Prepare("SELECT ?")
if err != nil {
return err
}
defer stmt.Close()
var n int
row := stmt.QueryRow("1")
return row.Scan(&n)
})
printAfter(db, "with transaction: close stmt and rollback", func() error {
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
stmt, err := tx.Prepare("SELECT ?")
if err != nil {
return err
}
defer stmt.Close()
var n int
row := stmt.QueryRow("1")
return row.Scan(&n)
})
}
func printAfter(db *sql.DB, name string, fn func() error) {
if fn != nil {
fmt.Println()
fmt.Println()
fmt.Printf("Executing func %q\n", name)
if err := fn(); err != nil {
fmt.Println("Unable to execute func:", err)
os.Exit(1)
}
}
if err := printNumberPreparedStmt(db); err != nil {
fmt.Println("Unable to print number of prepared statements:", err)
os.Exit(1)
}
}
func printNumberPreparedStmt(db *sql.DB) error {
fmt.Println("Printing number of prepared statements:")
rows, err := db.Query(`SHOW GLOBAL STATUS LIKE 'com_%prepare%'`)
if err != nil {
return err
}
if err := printLines(rows); err != nil {
return err
}
rows.Close()
rows, err = db.Query(`SHOW GLOBAL STATUS LIKE 'prepared_stmt_count'`)
if err != nil {
return err
}
if err := printLines(rows); err != nil {
return err
}
rows.Close()
rows, err = db.Query(`SHOW GLOBAL STATUS LIKE 'com_stmt_close'`)
if err != nil {
return err
}
if err := printLines(rows); err != nil {
return err
}
rows.Close()
return nil
}
func printLines(rows *sql.Rows) error {
for rows.Next() {
var (
varName string
value uint32
)
if err := rows.Scan(&varName, &value); err != nil {
return err
}
fmt.Printf("\t%-20s %d\n", varName+":", value)
}
return rows.Err()
}
| true |
ceb4c2dfcfdef0d7410914f63937fe081dfa26fd
|
Go
|
mr7282/Go
|
/newLine course basik Go/homework-6/task-2/main.go
|
UTF-8
| 1,526 | 3.390625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"os"
)
type Circle struct {
p image.Point
r int
}
type Image interface {
ColorModel() color.Model
Bounds() image.Rectangle
At(x, y int) color.Color
}
func (c *Circle) ColorModel() color.Model {
return color.AlphaModel
}
func (c *Circle) Bounds() image.Rectangle {
return image.Rect(c.p.X-c.r, c.p.Y-c.r, c.p.X+c.r, c.p.Y+c.r)
}
func (c *Circle) At(x, y int) color.Color {
xx, yy, rr := float64(x-c.p.X)+0.5, float64(y-c.p.Y)+0.5, float64(c.r)
if xx*xx+yy*yy < rr*rr {
return color.Alpha{255}
}
return color.Alpha{0}
}
var blue color.Color = color.RGBA{17, 62, 105, 255}
var red color.Color = color.RGBA{250, 5, 5, 255}
func main() {
file, err := os.Create("myImage.png")
if err != nil {
fmt.Errorf("%v", err)
}
img := image.NewRGBA(image.Rect(0, 0, 500, 500))
mask := image.NewRGBA(image.Rect(0, 0, 500, 500))
draw.Draw(mask, mask.Bounds(), &image.Uniform{blue}, image.ZP, draw.Src)
draw.DrawMask(img, img.Bounds(), mask, image.ZP, &Circle{image.Point{20, 21}, 20}, image.ZP, draw.Over)
draw.DrawMask(img, img.Bounds(), mask, image.ZP, &Circle{image.Point{379, 141}, 40}, image.ZP, draw.Over)
draw.DrawMask(img, img.Bounds(), mask, image.ZP, &Circle{image.Point{239, 321}, 70}, image.ZP, draw.Over)
//This code drawing single line
// draw.Draw(img, img.Bounds(), &image.Uniform{blue}, image.ZP, draw.Src)
// for y := 20; y < 380; y++ {
// x := 20
// img.Set(x, y, red)
// }
png.Encode(file, img)
}
| true |
459dfbe8462cd44f9a5bf0aaf056e64fce7f486f
|
Go
|
henriquehorbovyi/learn-golang-by-examples
|
/variadic_functions.go
|
UTF-8
| 374 | 3.96875 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
// It is possible to receive many parameters
// with "Variadic functions", just like varargs in Java
func sumAll(numbers ...int) {
fmt.Print(numbers, " = ")
total := 0
for _, n := range numbers {
total += n
}
fmt.Println(total)
}
func main() {
sumAll(1, 2, 3)
sumAll(1, 1, 1, 2, 2, 2)
numbers := []int{7, 7, 7}
sumAll(numbers...)
}
| true |
ca6a4a050eb3595674553881fa46abeb23e9490b
|
Go
|
jonazero/RPC
|
/Practica8/servidor8.go
|
UTF-8
| 528 | 2.65625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import(
"fmt"
"net"
"net/rpc"
)
type Server struct{}
func (this *Server) AddScore(paso []string, reply *[]string)error{
paso = append(paso, "aaa")
paso = append(paso, "popó")
*reply = paso
return nil
}
func server() {
rpc.Register(new(Server))
ln, err := net.Listen("tcp", ":9999")
if err != nil {
fmt.Println(err)
}
for {
c, err := ln.Accept()
if err != nil {
fmt.Println(err)
continue
}
go rpc.ServeConn(c)
}
}
func main() {
go server()
var input string
fmt.Scanln(&input)
}
| true |
74c130a4465438e054c45887116c792afdee1216
|
Go
|
FlorianBergmann/gosoline
|
/pkg/sqs/naming.go
|
UTF-8
| 1,030 | 2.640625 | 3 |
[] |
no_license
|
[] |
no_license
|
package sqs
import (
"fmt"
"github.com/applike/gosoline/pkg/cfg"
)
const fifoSuffix = ".fifo"
type NamingFactory func(appId cfg.AppId, queueId string) string
var namingStrategy = func(appId cfg.AppId, queueId string) string {
return fmt.Sprintf("%v-%v-%v-%v-%v", appId.Project, appId.Environment, appId.Family, appId.Application, queueId)
}
func WithNamingStrategy(strategy NamingFactory) {
namingStrategy = strategy
}
var deadLetterNamingStrategy = func(appId cfg.AppId, queueId string) string {
return fmt.Sprintf("%v-%v-%v-%v-%v-dead", appId.Project, appId.Environment, appId.Family, appId.Application, queueId)
}
func WithDeadLetterNamingStrategy(strategy NamingFactory) {
deadLetterNamingStrategy = strategy
}
type QueueNameSettings interface {
GetAppid() cfg.AppId
GetQueueId() string
IsFifoEnabled() bool
}
func QueueName(settings QueueNameSettings) string {
name := namingStrategy(settings.GetAppid(), settings.GetQueueId())
if settings.IsFifoEnabled() {
name = name + fifoSuffix
}
return name
}
| true |
a36daff71b835eac1222eb6cbe72d617eb1f7c54
|
Go
|
meet-bariya/golang
|
/06_array/array.go
|
UTF-8
| 101 | 2.6875 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
func main(){
arr := [2][]int{{1,2,7,9},{1,2,9,4}}
fmt.Println(arr)
}
| true |
feac0b92737451c5ec32fc7d99ecea1bc855eed2
|
Go
|
tnir/gitaly
|
/internal/git/catfile/object_info_reader.go
|
UTF-8
| 6,391 | 2.859375 | 3 |
[
"BSD-3-Clause",
"ISC",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-2-Clause",
"GPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-google-patent-license-golang",
"MPL-2.0"
] |
permissive
|
[
"BSD-3-Clause",
"ISC",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-2-Clause",
"GPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-google-patent-license-golang",
"MPL-2.0"
] |
permissive
|
package catfile
import (
"bufio"
"context"
"fmt"
"strconv"
"strings"
"sync/atomic"
"github.com/opentracing/opentracing-go"
"github.com/prometheus/client_golang/prometheus"
"gitlab.com/gitlab-org/gitaly/v14/internal/command"
"gitlab.com/gitlab-org/gitaly/v14/internal/git"
)
// ObjectInfo represents a header returned by `git cat-file --batch`
type ObjectInfo struct {
Oid git.ObjectID
Type string
Size int64
}
// IsBlob returns true if object type is "blob"
func (o *ObjectInfo) IsBlob() bool {
return o.Type == "blob"
}
// ObjectID is the ID of the object.
func (o *ObjectInfo) ObjectID() git.ObjectID {
return o.Oid
}
// ObjectType is the type of the object.
func (o *ObjectInfo) ObjectType() string {
return o.Type
}
// ObjectSize is the size of the object.
func (o *ObjectInfo) ObjectSize() int64 {
return o.Size
}
// NotFoundError is returned when requesting an object that does not exist.
type NotFoundError struct{ error }
// IsNotFound tests whether err has type NotFoundError.
func IsNotFound(err error) bool {
_, ok := err.(NotFoundError)
return ok
}
// ParseObjectInfo reads from a reader and parses the data into an ObjectInfo struct
func ParseObjectInfo(stdout *bufio.Reader) (*ObjectInfo, error) {
restart:
infoLine, err := stdout.ReadString('\n')
if err != nil {
return nil, fmt.Errorf("read info line: %w", err)
}
infoLine = strings.TrimSuffix(infoLine, "\n")
if strings.HasSuffix(infoLine, " missing") {
// We use a hack to flush stdout of git-cat-file(1), which is that we request an
// object that cannot exist. This causes Git to write an error and immediately flush
// stdout. The only downside is that we need to filter this error here, but that's
// acceptable while git-cat-file(1) doesn't yet have any way to natively flush.
if strings.HasPrefix(infoLine, flushCommand) {
goto restart
}
return nil, NotFoundError{fmt.Errorf("object not found")}
}
info := strings.Split(infoLine, " ")
if len(info) != 3 {
return nil, fmt.Errorf("invalid info line: %q", infoLine)
}
oid, err := git.NewObjectIDFromHex(info[0])
if err != nil {
return nil, fmt.Errorf("parse object ID: %w", err)
}
objectSize, err := strconv.ParseInt(info[2], 10, 64)
if err != nil {
return nil, fmt.Errorf("parse object size: %w", err)
}
return &ObjectInfo{
Oid: oid,
Type: info[1],
Size: objectSize,
}, nil
}
// ObjectInfoReader returns information about an object referenced by a given revision.
type ObjectInfoReader interface {
cacheable
// Info requests information about the revision pointed to by the given revision.
Info(context.Context, git.Revision) (*ObjectInfo, error)
// InfoQueue returns an ObjectInfoQueue that can be used to batch multiple object info
// requests. Using the queue is more efficient than using `Info()` when requesting a bunch
// of objects. The returned function must be executed after use of the ObjectInfoQueue has
// finished.
InfoQueue(context.Context) (ObjectInfoQueue, func(), error)
}
// ObjectInfoQueue allows for requesting and reading object info independently of each other. The
// number of RequestInfo and ReadInfo calls must match. ReadObject must be executed after the
// object has been requested already. The order of objects returned by ReadInfo is the same as the
// order in which object info has been requested. Users of this interface must call `Flush()` after
// all requests have been queued up such that all requested objects will be readable.
type ObjectInfoQueue interface {
// RequestRevision requests the given revision from git-cat-file(1).
RequestRevision(git.Revision) error
// ReadInfo reads object info which has previously been requested.
ReadInfo() (*ObjectInfo, error)
// Flush flushes all queued requests and asks git-cat-file(1) to print all objects which
// have been requested up to this point.
Flush() error
}
// objectInfoReader is a reader for Git object information. This reader is implemented via a
// long-lived `git cat-file --batch-check` process such that we do not have to spawn a separate
// process per object info we're about to read.
type objectInfoReader struct {
cmd *command.Command
counter *prometheus.CounterVec
queue requestQueue
queueInUse int32
}
func newObjectInfoReader(
ctx context.Context,
repo git.RepositoryExecutor,
counter *prometheus.CounterVec,
) (*objectInfoReader, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "catfile.ObjectInfoReader")
batchCmd, err := repo.Exec(ctx,
git.SubCmd{
Name: "cat-file",
Flags: []git.Option{
git.Flag{Name: "--batch-check"},
git.Flag{Name: "--buffer"},
},
},
git.WithStdin(command.SetupStdin),
)
if err != nil {
return nil, err
}
objectInfoReader := &objectInfoReader{
cmd: batchCmd,
counter: counter,
queue: requestQueue{
stdout: bufio.NewReader(batchCmd),
stdin: bufio.NewWriter(batchCmd),
},
}
go func() {
<-ctx.Done()
// This is crucial to prevent leaking file descriptors.
objectInfoReader.close()
span.Finish()
}()
return objectInfoReader, nil
}
func (o *objectInfoReader) close() {
o.queue.close()
_ = o.cmd.Wait()
}
func (o *objectInfoReader) isClosed() bool {
return o.queue.isClosed()
}
func (o *objectInfoReader) isDirty() bool {
return o.queue.isDirty()
}
func (o *objectInfoReader) infoQueue(ctx context.Context, tracedMethod string) (*requestQueue, func(), error) {
if !atomic.CompareAndSwapInt32(&o.queueInUse, 0, 1) {
return nil, nil, fmt.Errorf("object info queue already in use")
}
trace := startTrace(ctx, o.counter, tracedMethod)
o.queue.trace = trace
return &o.queue, func() {
atomic.StoreInt32(&o.queueInUse, 0)
trace.finish()
}, nil
}
func (o *objectInfoReader) Info(ctx context.Context, revision git.Revision) (*ObjectInfo, error) {
queue, cleanup, err := o.infoQueue(ctx, "catfile.Info")
if err != nil {
return nil, err
}
defer cleanup()
if err := queue.RequestRevision(revision); err != nil {
return nil, err
}
if err := queue.Flush(); err != nil {
return nil, err
}
objectInfo, err := queue.ReadInfo()
if err != nil {
return nil, err
}
return objectInfo, nil
}
func (o *objectInfoReader) InfoQueue(ctx context.Context) (ObjectInfoQueue, func(), error) {
queue, cleanup, err := o.infoQueue(ctx, "catfile.InfoQueue")
if err != nil {
return nil, nil, err
}
return queue, cleanup, nil
}
| true |
383e690dedbc029e9653a7c3cdcc544138ecbc64
|
Go
|
Kelwing/disgord
|
/internal/httd/header.go
|
UTF-8
| 3,376 | 2.75 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
[
"BSD-3-Clause"
] |
permissive
|
package httd
import (
"encoding/json"
"errors"
"net/http"
"strconv"
"time"
)
// http rate limit identifiers
const (
XAuditLogReason = "X-Audit-Log-Reason"
XRateLimitPrecision = "X-RateLimit-Precision"
XRateLimitBucket = "X-RateLimit-Bucket"
XRateLimitLimit = "X-RateLimit-Limit"
XRateLimitRemaining = "X-RateLimit-Remaining"
XRateLimitReset = "X-RateLimit-Reset"
XRateLimitResetAfter = "X-RateLimit-Reset-After"
XRateLimitGlobal = "X-RateLimit-Global"
RateLimitRetryAfter = "Retry-After"
DisgordNormalizedHeader = "X-Disgord-Normalized-Kufdsfksduhf-S47yf"
)
// HeaderToTime takes the response header from Discord and extracts the
// timestamp. Useful for detecting time desync between discord and client
func HeaderToTime(header http.Header) (t time.Time, err error) {
// date: Fri, 14 Sep 2018 19:04:24 GMT
dateStr := header.Get("date")
if dateStr == "" {
err = errors.New("missing header field 'date'")
return
}
t, err = time.Parse(time.RFC1123, dateStr)
return
}
type RateLimitResponseStructure struct {
Message string `json:"message"` // A message saying you are being rate limited.
RetryAfter int64 `json:"retry_after"` // The number of milliseconds to wait before submitting another request.
Global bool `json:"global"` // A value indicating if you are being globally rate limited or not
}
// NormalizeDiscordHeader overrides header fields with body content and make sure every header field
// uses milliseconds and not seconds. Regards rate limits only.
func NormalizeDiscordHeader(statusCode int, header http.Header, body []byte) (h http.Header, err error) {
// don't care about 2 different time delay estimates for the ltBucket reset.
// So lets take Retry-After and X-RateLimit-Reset-After to set the reset
var delay int64
if retryAfter := header.Get(RateLimitRetryAfter); retryAfter != "" {
delay, _ = strconv.ParseInt(retryAfter, 10, 64)
}
if retry := header.Get(XRateLimitResetAfter); delay == 0 && retry != "" {
delayF, _ := strconv.ParseFloat(retry, 64)
delayF *= 1000 // seconds => milliseconds
delay = int64(delayF)
}
// sometimes the body might be populated too
if statusCode == http.StatusTooManyRequests && body != nil {
var rateLimitBodyInfo *RateLimitResponseStructure
if err = json.Unmarshal(body, &rateLimitBodyInfo); err != nil {
return nil, err
}
if rateLimitBodyInfo.Global {
header.Set(XRateLimitGlobal, "true")
}
if delay == 0 && rateLimitBodyInfo.RetryAfter > 0 {
delay = rateLimitBodyInfo.RetryAfter
}
}
// convert Reset to store milliseconds and not seconds
// if there is no content, we create a Reset unix using the delay
if reset := header.Get(XRateLimitReset); reset != "" {
epoch, _ := strconv.ParseFloat(reset, 64)
epoch *= 1000 // seconds => milliseconds
header.Set(XRateLimitReset, strconv.FormatInt(int64(epoch), 10))
} else if delay > 0 {
timestamp, err := HeaderToTime(header)
if err != nil {
// does add an delay, but there is no reason
// to go insane if timestamp could not be handled
timestamp = time.Now()
}
reset := timestamp.Add(time.Duration(delay) * time.Millisecond)
ms := reset.UnixNano() / int64(time.Millisecond)
header.Set(XRateLimitReset, strconv.FormatInt(ms, 10))
}
header.Set(DisgordNormalizedHeader, "true")
return header, nil
}
| true |
5350e5cc74cdd4ebee086fff2910f64af775bb66
|
Go
|
YJeremy/MyGoCode
|
/src/learningCode/mymath/Goleran_arr.go
|
UTF-8
| 978 | 3.890625 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
func main() {
var arr [10]int
arr[0] = 44
arr[1] = 13
fmt.Printf("The [10]int first element arr[0] is %d\n", arr[0])
fmt.Printf("The [10]int last element arr[9] is %d\n", arr[9])
//slice和声明array一样,只是少了长度;它是一个切片数组,要基于某个数组基础上切片;它是一个空间里引用;
//但当 append 元素,使其长度超出原本引用数组的空间 cap()>len(),那么将分配新的空间给切片,且不再影响原来引用;
var fslice []byte
mm := [4]byte{'a', 'd', 'g', 'k'}
//如此先定义一个基础数组,然后在上面取值,而不是直接当作数组用
fslice = mm[:] // 切片全部数组,不要只写a
fislic2 := []byte{'k', 'b'}
var a, b []byte
a = fslice[1:3]
b = fslice[0:2]
fmt.Printf("mm= %d\n", mm)
fmt.Printf("fslice=%d\n,fislic2=%d\n", fslice, fislic2) //打印出了的是地址
fmt.Printf("cap a = %d\n a=%d", cap(a), a)
fmt.Printf("b = ", b, "\n")
}
| true |
476a9010e2411794a82b305fa7e44493189a0564
|
Go
|
rbozdag/GoCourse
|
/05_ArraySlices/main.go
|
UTF-8
| 458 | 3.65625 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
)
func main() {
var fruitArr [2]string
fruitArr[0] = "Apple"
fruitArr[1] = "Lemon"
fmt.Println("fruitArr>>", fruitArr)
fmt.Println("fruitArr[0]>>", fruitArr[0])
platforms := [2]string{"IOS", "Android"}
fmt.Println("platforms>>", platforms)
fruitSlice := []string{"Grape", "Banana"}
fruitSlice = append(fruitSlice, "Lemon")
fmt.Println("fruitSlice>>", fruitSlice)
fmt.Println("fruitSlice.len>>", len(fruitSlice))
}
| true |
bddfaec918a7e71282e373ad2559d1b15d3d99f9
|
Go
|
ThugUditGurani/gRPC-ProtocolBuffer
|
/greet/greet_server/server.go
|
UTF-8
| 3,024 | 3.09375 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"Github/gRPC-ProtocolBuffer/greet/greetpb"
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"io"
"log"
"net"
"time"
)
type server struct {
}
func (s *server) GreetWithDeadline(ctx context.Context, request *greetpb.GreetWithDeadlineRequest) (*greetpb.GreetWithDeadlineResponse, error) {
fmt.Printf("GreetWithDeadline Funstion is invoked with %v",request)
firstName := request.GetGreeting().GetFirstName()
for i := 0; i < 3; i++ {
if ctx.Err() == context.Canceled {
fmt.Println("The Client canceled the request")
return nil, status.Error(codes.Canceled,"The Client canceled the request")
}
time.Sleep(1 & time.Second)
}
result := "Hello" + firstName
res := &greetpb.GreetWithDeadlineResponse{
Result: result,
}
return res , nil
}
func (s *server) GreetEveryone(everyoneServer greetpb.GreetService_GreetEveryoneServer) error {
fmt.Println("GreetEveryOne function was invoked with a Streaming request")
for {
req,err := everyoneServer.Recv()
if err == io.EOF {
return nil
}
if err != nil {
log.Fatalf("Error while reading client stream: %v",err)
return err
}
firstName := req.GetGreeting().GetFirstName()
result := "hello" + firstName + "!"
errSend := everyoneServer.Send(&greetpb.GreetEveryoneResponse{Result: result})
if errSend != nil {
log.Fatalf("Error while sending data to client : %v",err)
return err
}
}
}
func (s *server) LongGreet(greetServer greetpb.GreetService_LongGreetServer) error {
fmt.Printf("LongGreet Server %v",greetServer)
result := ""
for {
req,err := greetServer.Recv()
if err == io.EOF {
//We have finished reading the client stream
greetServer.SendAndClose(&greetpb.LongGreetResponse{
Result: result,
})
break
}
if err != nil {
log.Fatalf("Error while reading %v",err)
}
firstName := req.GetGreeting().GetFirstName()
result += "Hello" + firstName + "!"
}
return nil
}
func (s *server) GreetManyTimes(request *greetpb.GreetManyTimesRequest, timesServer greetpb.GreetService_GreetManyTimesServer) error {
firstName := request.GetGreeting().GetFirstName()
for i := 0 ; i < 10; i++ {
result := "hello" + firstName + "number" + string(i)
res := &greetpb.GreetManyTimesResponse{Result: result}
timesServer.Send(res)
time.Sleep(1000 * time.Millisecond)
}
return nil
}
func (*server) Greet(ctx context.Context,req *greetpb.GreetRequest) (*greetpb.GreetResponse, error){
fmt.Printf("Greet Funstion is invoked with %v",req)
firstName := req.GetGreeting().GetFirstName()
result := "Hello" + firstName
res := &greetpb.GreetResponse{
Result: result,
}
return res , nil
}
func main() {
fmt.Println("Hello World")
lis , err := net.Listen("tcp","0.0.0.0:50051")
if err != nil {
log.Fatalf("Failed to listen: %v",err)
}
s := grpc.NewServer()
greetpb.RegisterGreetServiceServer(s,&server{})
if err := s.Serve(lis); err != nil {
log.Fatalf("Failed to serve: %v",err)
}
}
| true |
0a2153fb00ad049b576e99b7fbc9d46110144821
|
Go
|
parallelo-ai/go-simple-mgo
|
/mgo_sample.go
|
UTF-8
| 1,159 | 3.609375 | 4 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"fmt"
// mgo package
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
)
func GetDBData() (nItmOne, nItmTwo int) {
// Open MongoDB session
session, err := mgo.Dial("mongodb://localhost/mydb")
if err != nil {
fmt.Println("Error", err)
}
// Connect with the DB
c := session.DB("TheDB").C("ThCollection")
// Count the documents in collection
n, _ := c.Count()
fmt.Println("The amount of elements in collection is", n)
// The document model for this example might be
// doc : { ...
// "item" : {
// "subitem_one" : integer
// "subitem_two" : integer
// }
// ...
// }
// Can implement queries as recommended by MongoDB's documentation
// so, we can count how many documents match our criteria,
nItmOne, _ = c.Find(bson.M{"item.subitem_one": map[string]int{"$gte": 1}}).Count()
nItmTwo, _ = c.Find(bson.M{"item.subitem_two": 1}).Count()
fmt.Println(nItmOne, nItmTwo)
// Close the session
session.Close()
return
}
func main() {
// Get the counts
itemOne, itemTwo := GetDBData()
fmt.Println("The queries gave ", itemOne+itemTwo, "results")
}
| true |
1033c33e16a3c0f45c7d186984a231e060ae5ef3
|
Go
|
zieckey/gohello
|
/std/os/exec/singlecommand/main.go
|
UTF-8
| 384 | 3.03125 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"os/exec"
"fmt"
"os"
)
func main() {
message := "hello, this is the email body"
c := exec.Command("echo", message)
buf, err := c.Output()
if err != nil {
fmt.Fprintf(os.Stderr, "The command failed to perform: %s (Command: %s, Arguments: %s)", err, c.Args)
return
}
fmt.Fprintf(os.Stdout, "Result: %s", buf)
}
| true |
fffdcbcb4cf1236c26cae577c8d41d3fca36b9be
|
Go
|
stts-se/wikispeech-manuscriptor
|
/protocol/payload.go
|
UTF-8
| 2,976 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package protocol
import (
"encoding/json"
)
// type Message struct {
// Level string `json:"level,omitempty"`
// Text string `json:"text,omitempty"`
// }
// type Payload struct {
// Name string `json:"name,omitempty"`
// Message Message `json:"message,omitempty"`
// }
type FilterPayload struct {
//Payload
BatchName string `json:"batch_name"`
TargetSize int `json:"target_size"`
Opts []FilterOpt `json:"opts"`
}
func (f FilterPayload) Empty() bool {
return f.BatchName == "" && f.TargetSize == 0 && len(f.Opts) == 0
}
type BatchMetadata struct {
FilterPayload
OutputSize int `json:"output_size"`
Timestamp string `json:"timestamp"`
}
func (meta BatchMetadata) Empty() bool {
return meta.Timestamp == "" && meta.OutputSize == 0 && meta.BatchName == "" && len(meta.Opts) == 0
}
type FilterOpt struct {
Name string `json:"name"`
Args []string `json:"args"`
}
// Selector
type SelectorFeatOpt struct {
Name string `json:"name"`
TargetAmount int `json:"target_amount"`
}
type SelectorOptions struct {
// Mode: Selection mode (exhaustive or rand)
Mode string `json:"mode"`
FeatureOpts []SelectorFeatOpt `json:"feature_opts"`
AdjustScoreForSentenceLength bool `json:"adjust_score_for_sentence_length"`
TargetSize int `json:"target_size"`
FromBatch string `json:"from_batch"`
ScriptName string `json:"script_name"`
AccumulatedScripts []string `json:"accumulated_scripts"`
//ContinuousPrint bool `json:"continuous_print,omitempty"`
PrintMetaData bool `json:"print_metadata,omitempty"`
// exhaustive search
ChunkSize int `json:"chunk_size"`
ChunkDecrease int `json:"chunk_decrease"`
// random search
MinIterationsRand int `json:"min_iterations"`
CutoffRand int `json:"cutoff"`
Debug bool `json:"debug,omitempty"`
}
func (s SelectorOptions) Empty() bool {
return s.ScriptName == "" && s.TargetSize == 0 && len(s.FeatureOpts) == 0
}
type SelectorPayload struct {
//Payload
Options SelectorOptions `json:"options"`
}
type Config struct {
Description string `json:"description"`
ClearBatches bool `json:"clear_batches"`
ClearScripts bool `json:"clear_scripts"`
Filter FilterPayload `json:"filter"`
Selector SelectorOptions `json:"selector"`
}
func (c Config) String() string {
bts, _ := json.MarshalIndent(c, " ", " ")
return string(bts)
}
type ScriptMetadata struct {
SelectorPayload
InputSize int `json:"input_size"`
OutputSize int `json:"output_size"`
Timestamp string `json:"timestamp"`
}
func (meta ScriptMetadata) Empty() bool {
return meta.Timestamp == "" && meta.InputSize == 0 && meta.OutputSize == 00 &&
meta.Options.FromBatch == "" && len(meta.Options.FeatureOpts) == 0 && meta.Options.Mode == ""
}
| true |
fc1177747e24b8426a1b7e8446274c288be0833e
|
Go
|
Anyarom/Tasks
|
/keeper/map_keeper.go
|
UTF-8
| 1,462 | 3.34375 | 3 |
[] |
no_license
|
[] |
no_license
|
package keeper
import (
"sync"
"sync/atomic"
)
type MapKeeper struct {
currentId uint64
MapTasks sync.Map
}
// функция для инициализации структуры MapKeeper
func InitMapKeeper() *MapKeeper {
var mapTasks sync.Map
mapKeeper := MapKeeper{MapTasks: mapTasks}
return &mapKeeper
}
// метод для сохранения в мапу
func (mk *MapKeeper) SaveTask(task Task) uint64 {
// генерация id инкрементно
reqId := atomic.AddUint64(&mk.currentId, 1)
mk.MapTasks.Store(reqId, task)
return reqId
}
// метод для обновления значений в мапе
func (mk *MapKeeper) UpdateTask(reqId uint64, task Task) {
mk.MapTasks.Store(reqId, task)
}
// метод получения одного запроса
func (mk *MapKeeper) GetById(reqId uint64) (task Task, ok bool) {
t, ok := mk.MapTasks.Load(reqId)
if !ok {
return Task{}, false
}
return t.(Task), true
}
// метод для получения всех запросов из мапы
func (mk *MapKeeper) GetAll() []ReqTaskExtended {
var tasks []ReqTaskExtended
mk.MapTasks.Range(func(id, value interface{}) bool {
reqTaskExtended := ReqTaskExtended{Id: id.(uint64), ReqTask: value.(Task).ReqTask}
tasks = append(tasks, reqTaskExtended)
return true
})
return tasks
}
// метод для удаления из мапы
func (mk *MapKeeper) DeleteById(reqId uint64) {
mk.MapTasks.Delete(reqId)
}
| true |
75e6e9d18921e49be1b4c2d375cd8b650ffaff84
|
Go
|
darkgray1981/kanjiquizbot
|
/quizvalidate_test.go
|
UTF-8
| 3,928 | 2.921875 | 3 |
[
"Unlicense"
] |
permissive
|
[
"Unlicense"
] |
permissive
|
package main
import (
"encoding/json"
"log"
"os"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
)
const TestQuiz = "quizvalidate_test"
func TestStringSet(t *testing.T) {
set := NewStringSet()
// Test Add and AddAll
set.AddAll("a", "a", "b")
set.Add("c")
set.Add("c")
add := NewStringSet()
add.AddAll("a", "b", "c")
if !cmp.Equal(set.Values(), add.Values(), cmpopts.SortSlices(func(x, y string) bool { return x < y })) {
t.Errorf("error:%+v != %+v\n", set.Values(), add.Values())
}
// Test Remove
set.Remove("c")
remove := NewStringSet()
remove.AddAll("a", "b")
if !cmp.Equal(set.Values(), remove.Values(), cmpopts.SortSlices(func(x, y string) bool { return x < y })) {
t.Errorf("error:%+v != %+v\n", set.Values(), remove.Values())
}
// Test IsEmpty
set.Remove("a")
set.Remove("b")
empty := NewStringSet()
if !set.IsEmpty() || !empty.IsEmpty() {
t.Error("IsEmpty() should be true")
}
// Test order preservation
set.Add("a")
set.Add("b")
set.AddOrdered("d", 3)
set.AddOrdered("c", 2)
order := NewStringSet()
order.AddAll("a", "b", "c", "d")
if !cmp.Equal(set.Values(), order.Values()) {
t.Errorf("error:%+v != %+v\n", set.Values(), order.Values())
}
}
func TestValidations(t *testing.T) {
// Weird to initialize a global in a test like this
// Would be better to eventually have another less specific test covering the bot's initialization
loadQuizList()
Quizzes.Map[TestQuiz] = "_" + TestQuiz + ".json"
fixedQuizPath := QUIZ_FOLDER + Quizzes.Map[TestQuiz] + ".fix"
// Raw strings and indentation don't go together
correctQuizRaw := `{
"description": "Test quiz with duplicates",
"type": "text",
"deck": [
{ "question": "q1", "answers": [ "aaa", "bbb" ], "comment": "c1\nc2" },
{ "question": "q2", "answers": [ "ccc", "ddd", "eee" ], "comment": "c3" }
]
}`
correctQuiz := createTestQuiz(correctQuizRaw)
// Actual validation logic is tested below
// This test covers the genereation of fixed quiz copies
ValidateQuizzes(GetQuizlist(), true)
var fixedQuiz Quiz
f, err := os.Open(fixedQuizPath)
if err != nil {
log.Fatal(err)
}
json.NewDecoder(f).Decode(&fixedQuiz)
f.Close()
// Ignoring comment field because supporting field-specific comparison behavior is too annoying
if !quizEqual(correctQuiz, fixedQuiz, cmpopts.IgnoreFields(Card{}, "Comment")) {
t.Errorf("Check duplicates failed! %+v != %+v", correctQuiz, fixedQuiz)
}
// Clean up
os.Remove(fixedQuizPath)
}
func TestDuplicateValidation(t *testing.T) {
// Raw strings and indentation don't go together
dedupQuizRaw := `{
"description": "Test quiz with duplicates",
"type": "text",
"deck": [
{ "question": "q1", "answers": [ "aaa", "bbb" ], "comment": "c1\nc2" },
{ "question": "q2", "answers": [ "ccc", "ddd", "eee" ], "comment": "c3" }
]
}`
var dupQuiz Quiz
f, err := os.Open(QUIZ_FOLDER + "_" + TestQuiz + ".json")
if err != nil {
log.Fatal(err)
}
json.NewDecoder(f).Decode(&dupQuiz)
f.Close()
dedupQuiz := createTestQuiz(dedupQuizRaw)
fixedQuiz, _ := checkDuplicates(dupQuiz)
// Ignoring comment field because supporting field-specific comparison behavior is too annoying
if !quizEqual(dedupQuiz, fixedQuiz, cmpopts.IgnoreFields(Card{}, "Comment")) {
t.Errorf("Check duplicates failed! %+v != %+v", dedupQuiz, fixedQuiz)
}
}
func createTestQuiz(raw string) (quiz Quiz) {
err := json.Unmarshal([]byte(raw), &quiz)
if err != nil {
log.Fatal(err)
}
return
}
// Helper function for comparing quizzes
// Using custom compare because reflect.DeepEqual() cannot correctly equate slices with different order
func quizEqual(qx, qy Quiz, additionalOpts ...cmp.Option) bool {
opts := []cmp.Option{
cmpopts.SortSlices(func(x, y string) bool { return x < y }),
cmpopts.SortSlices(func(x, y Card) bool { return x.Question < y.Question }),
}
opts = append(opts, additionalOpts...)
return cmp.Equal(qx, qy, opts...)
}
| true |
d12f9e629013eab7029efd361a9c5ba0dd07973f
|
Go
|
kilchik/swserver
|
/pkg/store/store.go
|
UTF-8
| 2,165 | 2.78125 | 3 |
[] |
no_license
|
[] |
no_license
|
package store
import (
"context"
"fmt"
_ "github.com/jackc/pgx/stdlib"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
type Storage interface {
GetNewSrvEvents(ctx context.Context, uid int64, revFrom int64) (events []*Event, err error)
AddSrvEvent(ctx context.Context, uid int64, event *Event) error
}
type StorageImpl struct {
db *sqlx.DB
}
func NewStorage(db *sqlx.DB) *StorageImpl {
return &StorageImpl{db}
}
const (
SrvEventTypeAdd = iota
)
type Event struct {
Type int32 `json:"type",db:"type"`
Data []byte `json:"data",db:"data"`
}
func (s *StorageImpl) AddSrvEvent(ctx context.Context, uid int64, event *Event) error {
if err := s.withTransaction(ctx, func(tx *sqlx.Tx) error {
var maxRev int64
if err := tx.GetContext(ctx, &maxRev, `
SELECT MAX(rev) FROM srv_events
WHERE uid=$1`, uid); err != nil {
return errors.Wrapf(err, "get last user revision")
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO srv_events(uid, type, data, rev) VALUES ($1, $2, $3, $4)`, uid, event.Type, event.Data, maxRev+1); err != nil {
return errors.Wrapf(err, "insert new event")
}
return nil
}); err != nil {
return errors.Wrap(err, "add srv event: run transaction")
}
return nil
}
func (s *StorageImpl) GetNewSrvEvents(ctx context.Context, uid int64, revFrom int64) (events []*Event, err error) {
err = s.db.SelectContext(ctx, &events, `
SELECT type, data FROM srv_events
WHERE uid=$1 AND rev>=$2
ORDER BY created_at
LIMIT 10;`, uid, revFrom)
return
}
func (s *StorageImpl) withTransaction(ctx context.Context, f func(tx *sqlx.Tx) error) (err error) {
var trx *sqlx.Tx
trx, err = s.db.BeginTxx(ctx, nil)
if err != nil {
return errors.Wrap(err, "begin transaction")
}
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("recover after panic: %v", r)
}
for {
if err != nil {
if errRollback := trx.Rollback(); errRollback != nil {
err = errors.Wrapf(errRollback, fmt.Sprintf("rollback after error: %v", err))
}
return
}
if err := trx.Commit(); err != nil {
err = errors.Wrapf(err, "commit transaction")
} else {
return
}
}
}()
err = f(trx)
return err
}
| true |
586a2499e2855c10e21fe9df6f28dbafac4334c0
|
Go
|
toothrot/guff
|
/backend/models/division.go
|
UTF-8
| 983 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package models
import (
"bytes"
"regexp"
"github.com/PuerkitoBio/goquery"
"github.com/toothrot/guff/backend/generated"
)
var divisionRex = regexp.MustCompile("leagues/([0-9]+)/schedule")
var titleRex = regexp.MustCompile("leagues/shuffleboard/([0-9]+)-")
type Division struct {
ID string
Name string
}
func (d *Division) ToProto() *guff_proto.Division {
return &guff_proto.Division{
Id: d.ID,
Name: d.Name,
}
}
func ParseDivisions(b []byte) []Division {
var divisions []Division
doc, err := goquery.NewDocumentFromReader(bytes.NewReader(b))
if err != nil {
return divisions
}
doc.Find(".meta-info").Each(func(i int, selection *goquery.Selection) {
var d Division
dLink := selection.Find("h2 a").First()
href, ok := dLink.Attr("href")
if !ok {
return
}
matches := titleRex.FindStringSubmatch(href)
if len(matches) < 2 {
return
}
d.ID = matches[1]
d.Name = dLink.Text()
divisions = append(divisions, d)
})
return divisions
}
| true |
759359f8249bc9c54dcb0f8b4a5dcaeec304e10e
|
Go
|
naoki-urabe/playground
|
/go/sqlx/main.go
|
UTF-8
| 819 | 2.96875 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
"log"
)
var schema = `
CREATE TABLE IF NOT EXISTS person (
first_name text,
last_name text,
email text
);
`
type Person struct {
Id int `db:"id"`
FirstName string `db:"first_name"`
LastName string `db:"last_name"`
Email string `db:"email"`
}
func main() {
db, err := sqlx.Connect("mysql", "root:fg47gh62@tcp(mysql:3306)/go_db")
if err != nil {
log.Fatalln(err)
}
/*if db.MustExec(schema) != nil{
fmt.Println("already exists")
}*/
tx := db.MustBegin()
tx.MustExec("INSERT INTO person (first_name, last_name, email) VALUES (?, ?, ?)", "Jason", "Manson", "[email protected]")
tx.Commit()
people := []Person{}
db.Select(&people, "SELECT * FROM person ORDER BY first_name ASC")
fmt.Println(people)
}
| true |
687ee11e1c5d0b661575ecf6b290987dc9389cdf
|
Go
|
serbe/sites
|
/nntimecom.go
|
UTF-8
| 1,478 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package sites
import (
"bytes"
"fmt"
"regexp"
"strings"
"github.com/PuerkitoBio/goquery"
)
func nnTimeCom() []string {
var ips []string
for _, link := range nnTimeComLinks() {
body, err := crawl(link)
if err != nil {
errmsg("nnTimeCom crawl", err)
continue
}
ips = append(ips, nnTimeComIPS(body)...)
}
return ips
}
func nnTimeComLinks() []string {
var links []string
for page := 1; page < 6; page++ {
links = append(links, fmt.Sprintf("http://nntime.com/proxy-updated-0%d.htm", page))
}
return links
}
func nnTimeComIPS(body []byte) []string {
var ips []string
r := bytes.NewReader(body)
dom, err := goquery.NewDocumentFromReader(r)
if err != nil {
errmsg("nnTimeComIPS NewDocumentFromReader", err)
return ips
}
reS := regexp.MustCompile(`((?:\w=\d;)+)`)
if !reS.Match(body) {
return ips
}
sub := strings.Split(string(reS.FindSubmatch(body)[1]), ";")
hm := make(map[string]string)
for _, s := range sub {
if s != "" {
v := strings.Split(s, "=")
hm[v[0]] = v[1]
}
}
dom.Find("table#proxylist.data tbody tr").Each(func(_ int, s *goquery.Selection) {
ip := s.Find("td").Eq(1).Text()
ip = strings.Replace(ip, `document.write(":"`, ":", -1)
ip = strings.Replace(ip, ")", "", -1)
ip = strings.Replace(ip, "+", "", -1)
for k, v := range hm {
ip = strings.Replace(ip, k, v, -1)
}
ip = strings.Replace(ip, "+", "", -1)
ip = "http://" + ip
if len(ip) > 8 {
ips = append(ips, ip)
}
})
return ips
}
| true |
b609cd5aaeb18f5f5d20ddb844a067ffe2150a9f
|
Go
|
orbs-network/erc721
|
/contract/provenance/list.go
|
UTF-8
| 1,107 | 2.71875 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"github.com/orbs-network/orbs-contract-sdk/go/sdk/v1/state"
"strconv"
)
type List interface {
Append(item interface{}) (length uint64)
Get(index uint64) interface{}
Length() uint64
Iterator() Iterator
}
func NewAppendOnlyList(name string, serializer Serializer, deserializer Deserializer) List {
return &list{
name,
serializer,
deserializer,
}
}
type list struct {
name string
serializer Serializer
deserializer Deserializer
}
func (l *list) Append(item interface{}) (length uint64) {
index := l.Length()
l.serializer(l.itemKeyName(index), item)
length = index + 1
state.WriteUint64(l.lengthKeyName(), length)
return
}
func (l *list) Get(index uint64) interface{} {
key := l.itemKeyName(index)
return l.deserializer(key)
}
func (l *list) Length() uint64 {
return state.ReadUint64(l.lengthKeyName())
}
func (l *list) Iterator() Iterator {
return NewListIterator(l)
}
func (l *list) itemKeyName(index uint64) []byte {
return []byte(l.name+"."+strconv.FormatUint(index, 10))
}
func (l *list) lengthKeyName() []byte {
return []byte(l.name+".length")
}
| true |
e34df9156cfe378e6e6ae568ac8e4a7f13c94ec1
|
Go
|
larjudge/viper-config
|
/main.go
|
UTF-8
| 3,085 | 2.890625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"github.com/mitchellh/mapstructure"
flag "github.com/spf13/pflag"
"github.com/spf13/viper"
"io/ioutil"
)
const (
defaultHealthCheckURL = "/healthz"
)
var (
configFile = flag.StringP("config", "c", "", "specific config file to use")
boolConfig = flag.BoolP("spec.boolConfig", "b", false, "some bool")
intConfig = flag.IntP("spec.intConfig", "i", 0, "some int")
stringConfig = flag.StringP("spec.stringConfig", "s", "DEFAULT", "some string")
healthCheckURL = flag.StringP("opSpec.healthCheckURL", "e", defaultHealthCheckURL, "some string")
defaultConfig = &Config{
AppSpec: AppSpec{
BoolConfig: *boolConfig,
IntConfig: *intConfig,
StringConfig: *stringConfig,
},
OpSpec: OpSpec{HealthCheckURL: *healthCheckURL},
}
)
type OpSpec struct{
HealthCheckURL string `json:"healthCheckURL" yaml:"healthCheckURL" mapstructure:"healthCheckURL"`
}
type Config struct {
AppSpec AppSpec `json:"spec" yaml:"spec" mapstructure:"spec"`
OpSpec OpSpec `json:"opSpech" yaml:"opSpec mapstructure:"opSpec"`
}
type AppSpec struct {
BoolConfig bool `json:"boolConfig" yaml:"boolConfig" mapstructure:"boolConfig"`
IntConfig int `json:"intConfig" yaml:"intConfig" mapstructure:"intConfig"`
StringConfig string `json:"stringConfig" yaml:"stringConfig" mapstructure:"stringConfig"`
}
func loadConfig(srcFile string, fl flag.FlagSet) (*Config, error) {
viper.BindPFlags(&fl)
if srcFile != "" {
viper.SetConfigFile(srcFile)
} else {
viper.SetConfigType("yaml")
viper.SetConfigName("config")
viper.AddConfigPath("/config")
viper.AddConfigPath("/app/config")
}
var config Config
// convert from struct to generic map (required for viper to merge correctly) and set the defaults (will be used if not explicitly set via environment or config file)
viper.SetDefault("spec", config.GetMap(defaultConfig.AppSpec))
viper.SetDefault("opSpec", config.GetMap(defaultConfig.OpSpec))
err := viper.ReadInConfig()
if err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
fmt.Println(viper.ConfigFileUsed())
if err := viper.Unmarshal(&config); err != nil {
fmt.Println(fmt.Errorf("Fatal unmarshal config file: %s \n", err))
return nil, err
}
return &config, nil
} else {
// if no config file found use the default configuration
fmt.Println("error:")
fmt.Println(err)
return defaultConfig, err
}
}
if err := viper.Unmarshal(&config); err != nil {
return nil, err
}
return &config, nil
}
func (c Config) GetMap(config interface{}) map[string]interface{} {
var inInterface map[string]interface{}
mapstructure.Decode(config, &inInterface)
return inInterface
}
func main() {
flag.Parse()
config, _ := loadConfig(*configFile, *flag.CommandLine)
yaml, _ := ioutil.ReadFile(*configFile)
fmt.Printf("YAML \n%+v\n\n", string(yaml))
fmt.Printf("DEFAULT CONFIG IS \n\t%+v\n\n", defaultConfig)
fmt.Printf("\n\nFLAGS are \n\t%+v\n\t%+v\n\t%+v\n\t%+v\n", *stringConfig, *intConfig, *boolConfig, *healthCheckURL)
fmt.Printf("\n\nCONFIG IS \n\t%+v\n\n", config)
}
| true |
2b057c76a4a67fe728ea986ea30768bab5e499c8
|
Go
|
joshprzybyszewski/cribbage
|
/server/interaction/npc_test.go
|
UTF-8
| 12,135 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package interaction
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/joshprzybyszewski/cribbage/model"
)
var _ ActionHandler = (*mockActionHandler)(nil)
type mockActionHandler struct {
handleActionFunc func(a model.PlayerAction) error
}
func (ah *mockActionHandler) Handle(pa model.PlayerAction) error {
return ah.handleActionFunc(pa)
}
func NewNilHandler() ActionHandler {
return &mockActionHandler{
handleActionFunc: func(a model.PlayerAction) error {
return nil
},
}
}
func createPlayer(t *testing.T, pID model.PlayerID) *NPCPlayer {
npc, err := NewNPCPlayer(pID, NewNilHandler())
require.Nil(t, err)
p, ok := npc.(*NPCPlayer)
assert.True(t, ok)
return p
}
func newGame(npcID model.PlayerID, nPlayers int, pegCards []model.Card) model.Game {
players := make([]model.Player, nPlayers)
for i := 0; i < nPlayers-1; i++ {
id := model.PlayerID(fmt.Sprintf(`p%d`, i))
players[i] = model.Player{ID: id}
}
players[len(players)-1] = model.Player{ID: npcID}
hands := make(map[model.PlayerID][]model.Card)
nCards := 6
switch nPlayers {
case 3, 4:
nCards = 5
}
for _, p := range players {
hands[p.ID] = make([]model.Card, nCards)
}
for i := range hands[npcID] {
// create a hand: 2c, 3c, 4c, ...
hands[npcID][i] = model.NewCardFromString(fmt.Sprintf(`%dc`, i+2))
}
pegs := make([]model.PeggedCard, 0)
for i, c := range pegCards {
pegs = append(pegs, model.PeggedCard{
Card: c,
PlayerID: players[i%nPlayers].ID,
})
}
return model.Game{
ID: 5,
Players: players,
Hands: hands,
PeggedCards: pegs,
}
}
func TestDealAction(t *testing.T) {
tests := []struct {
desc string
npc model.PlayerID
}{{
desc: `test dumb npc`,
npc: Dumb,
}, {
desc: `test simple npc`,
npc: Simple,
}, {
desc: `test calculated npc`,
npc: Calc,
}}
for _, tc := range tests {
p := createPlayer(t, tc.npc)
a, err := p.buildAction(model.DealCards, model.Game{})
assert.Nil(t, err)
assert.Equal(t, a.Overcomes, model.DealCards)
da, ok := a.Action.(model.DealAction)
assert.True(t, ok)
assert.LessOrEqual(t, da.NumShuffles, 10)
assert.GreaterOrEqual(t, da.NumShuffles, 1)
}
}
func TestCutAction(t *testing.T) {
tests := []struct {
desc string
npc model.PlayerID
}{{
desc: `test dumb npc`,
npc: Dumb,
}, {
desc: `test simple npc`,
npc: Simple,
}, {
desc: `test calculated npc`,
npc: Calc,
}}
for _, tc := range tests {
p := createPlayer(t, tc.npc)
a, err := p.buildAction(model.CutCard, model.Game{})
assert.Nil(t, err)
assert.Equal(t, a.Overcomes, model.CutCard)
cda, ok := a.Action.(model.CutDeckAction)
assert.True(t, ok)
assert.LessOrEqual(t, cda.Percentage, 1.0)
assert.GreaterOrEqual(t, cda.Percentage, 0.0)
}
}
func TestCountHandAction(t *testing.T) {
g := model.Game{
CutCard: model.NewCardFromString(`10h`),
}
hand := []model.Card{
model.NewCardFromString(`2c`),
model.NewCardFromString(`3c`),
model.NewCardFromString(`4c`),
model.NewCardFromString(`5c`),
}
tests := []struct {
desc string
npc model.PlayerID
g model.Game
exp model.PlayerAction
}{{
desc: `test dumb npc`,
npc: Dumb,
exp: model.PlayerAction{
ID: Dumb,
Overcomes: model.CountHand,
Action: model.CountHandAction{
Pts: 12,
}},
}, {
desc: `test simple npc`,
npc: Simple,
exp: model.PlayerAction{
ID: Simple,
Overcomes: model.CountHand,
Action: model.CountHandAction{
Pts: 12,
}},
}, {
desc: `test calculated npc`,
npc: Calc,
exp: model.PlayerAction{
ID: Calc,
Overcomes: model.CountHand,
Action: model.CountHandAction{
Pts: 12,
}},
}}
for _, tc := range tests {
p := createPlayer(t, tc.npc)
g.Hands = map[model.PlayerID][]model.Card{
tc.npc: hand,
}
a, err := p.buildAction(model.CountHand, g)
assert.Nil(t, err)
assert.Equal(t, a.Overcomes, tc.exp.Overcomes)
cha, ok := a.Action.(model.CountHandAction)
assert.True(t, ok)
exp, ok := tc.exp.Action.(model.CountHandAction)
assert.True(t, ok)
assert.Equal(t, exp.Pts, cha.Pts)
}
}
func TestCountCribAction(t *testing.T) {
g := model.Game{
Crib: []model.Card{
model.NewCardFromString(`2c`),
model.NewCardFromString(`3c`),
model.NewCardFromString(`4c`),
model.NewCardFromString(`5c`),
},
CutCard: model.NewCardFromString(`10h`),
}
tests := []struct {
desc string
npc model.PlayerID
g model.Game
exp model.PlayerAction
}{{
desc: `test dumb npc`,
npc: Dumb,
exp: model.PlayerAction{
ID: Dumb,
Overcomes: model.CountCrib,
Action: model.CountCribAction{
Pts: 8,
}},
}, {
desc: `test simple npc`,
npc: Simple,
exp: model.PlayerAction{
ID: Simple,
Overcomes: model.CountCrib,
Action: model.CountCribAction{
Pts: 8,
}},
}, {
desc: `test calculated npc`,
npc: Calc,
exp: model.PlayerAction{
ID: Calc,
Overcomes: model.CountCrib,
Action: model.CountCribAction{
Pts: 8,
}},
}}
for _, tc := range tests {
p := createPlayer(t, tc.npc)
a, err := p.buildAction(tc.exp.Overcomes, g)
assert.Nil(t, err)
assert.Equal(t, a.Overcomes, tc.exp.Overcomes)
cca, ok := a.Action.(model.CountCribAction)
assert.True(t, ok)
exp, ok := tc.exp.Action.(model.CountCribAction)
assert.True(t, ok)
assert.Equal(t, exp.Pts, cca.Pts)
}
}
func TestPegTwice(t *testing.T) {
tests := []struct {
desc string
npc model.PlayerID
g model.Game
expGo bool
}{{
desc: `test dumb npc`,
npc: Dumb,
g: newGame(Dumb, 2, make([]model.Card, 0)),
expGo: false,
}, {
desc: `test simple npc`,
npc: Simple,
g: newGame(Simple, 2, make([]model.Card, 0)),
expGo: false,
}, {
desc: `test calculated npc`,
npc: Calc,
g: newGame(Calc, 2, make([]model.Card, 0)),
expGo: false,
}}
for _, tc := range tests {
p := createPlayer(t, tc.npc)
a, err := p.buildAction(model.PegCard, tc.g)
assert.NoError(t, err)
assert.Equal(t, a.Overcomes, model.PegCard)
pa, ok := a.Action.(model.PegAction)
assert.True(t, ok)
if !pa.SayGo {
tc.g.PeggedCards = append(tc.g.PeggedCards, model.PeggedCard{
Card: pa.Card,
PlayerID: a.ID,
})
}
a, err = p.buildAction(model.PegCard, tc.g)
assert.NoError(t, err)
assert.Equal(t, a.Overcomes, model.PegCard)
pa, ok = a.Action.(model.PegAction)
assert.True(t, ok)
c := model.PeggedCard{
Card: pa.Card,
PlayerID: a.ID,
}
assert.NotContains(t, tc.g.PeggedCards, c)
}
}
func TestPegAction(t *testing.T) {
tests := []struct {
desc string
npc model.PlayerID
g model.Game
expGo bool
}{{
desc: `test dumb npc`,
npc: Dumb,
g: newGame(Dumb, 2, make([]model.Card, 0)),
expGo: false,
}, {
desc: `test simple npc`,
npc: Simple,
g: newGame(Simple, 2, make([]model.Card, 0)),
expGo: false,
}, {
desc: `test calculated npc`,
npc: Calc,
g: newGame(Calc, 2, make([]model.Card, 0)),
expGo: false,
}, {
desc: `test dumb go`,
npc: Dumb,
g: newGame(Dumb, 2, []model.Card{
model.NewCardFromString(`10c`),
model.NewCardFromString(`10s`),
model.NewCardFromString(`10h`),
}),
expGo: true,
}, {
desc: `test simple go`,
npc: Simple,
g: newGame(Simple, 2, []model.Card{
model.NewCardFromString(`10c`),
model.NewCardFromString(`10s`),
model.NewCardFromString(`10h`),
}),
expGo: true,
}, {
desc: `test calculated go`,
npc: Calc,
g: newGame(Calc, 2, []model.Card{
model.NewCardFromString(`10c`),
model.NewCardFromString(`10s`),
model.NewCardFromString(`10h`),
}),
expGo: true,
}}
for _, tc := range tests {
p := createPlayer(t, tc.npc)
for i := 0; i < 10; i++ {
a, err := p.buildAction(model.PegCard, tc.g)
assert.Nil(t, err)
assert.Equal(t, a.Overcomes, model.PegCard)
pa, ok := a.Action.(model.PegAction)
assert.True(t, ok)
if tc.expGo {
assert.True(t, pa.SayGo)
} else {
assert.False(t, pa.SayGo, tc.desc)
assert.NotEqual(t, model.Card{}, pa.Card)
}
}
}
}
func TestBuildCribAction(t *testing.T) {
tests := []struct {
desc string
npc model.PlayerID
isDealer bool
g model.Game
expNCards int
}{{
desc: `test dumb npc`,
npc: Dumb,
isDealer: false,
g: newGame(Dumb, 2, make([]model.Card, 0)),
expNCards: 2,
}, {
desc: `test simple npc, not dealer`,
npc: Simple,
isDealer: false,
g: newGame(Simple, 2, make([]model.Card, 0)),
expNCards: 2,
}, {
desc: `test simple npc, dealer`,
npc: Simple,
isDealer: true,
g: newGame(Simple, 2, make([]model.Card, 0)),
expNCards: 2,
}, {
desc: `test calculated npc, not dealer`,
npc: Calc,
isDealer: false,
g: newGame(Calc, 2, make([]model.Card, 0)),
expNCards: 2,
}, {
desc: `test calculated npc, dealer`,
npc: Calc,
isDealer: true,
g: newGame(Calc, 2, make([]model.Card, 0)),
expNCards: 2,
}, {
desc: `test 3 player game`,
npc: Dumb,
isDealer: false,
g: newGame(Dumb, 3, make([]model.Card, 0)),
expNCards: 1,
}, {
desc: `test 4 player game`,
npc: Dumb,
isDealer: false,
g: newGame(Dumb, 4, make([]model.Card, 0)),
expNCards: 1,
}}
for _, tc := range tests {
p := createPlayer(t, tc.npc)
if tc.isDealer {
tc.g.CurrentDealer = tc.npc
}
for i := 0; i < 5; i++ {
a, err := p.buildAction(model.CribCard, tc.g)
assert.Nil(t, err)
assert.Equal(t, a.Overcomes, model.CribCard)
bca, ok := a.Action.(model.BuildCribAction)
assert.True(t, ok)
assert.Len(t, bca.Cards, tc.expNCards, tc.desc)
}
}
}
func TestNotifyBlocking(t *testing.T) {
tests := []struct {
desc string
npc model.PlayerID
}{{
desc: `test dumb NPC`,
npc: Dumb,
}, {
desc: `test simple NPC`,
npc: Simple,
}, {
desc: `test calculated NPC`,
npc: Calc,
}}
for _, tc := range tests {
ah := &mockActionHandler{
handleActionFunc: func(a model.PlayerAction) error {
da, ok := a.Action.(model.DealAction)
assert.True(t, ok)
assert.GreaterOrEqual(t, da.NumShuffles, 1)
assert.LessOrEqual(t, da.NumShuffles, 10)
return nil
},
}
p, err := NewNPCPlayer(tc.npc, ah)
require.Nil(t, err)
err = p.NotifyBlocking(model.DealCards, model.Game{}, ``)
assert.Nil(t, err)
}
}
func TestNotifyMessage(t *testing.T) {
tests := []struct {
desc string
npc model.PlayerID
}{{
desc: `test dumb NPC`,
npc: Dumb,
}, {
desc: `test simple NPC`,
npc: Simple,
}, {
desc: `test calculated NPC`,
npc: Calc,
}}
for _, tc := range tests {
p, err := NewNPCPlayer(tc.npc, NewNilHandler())
require.Nil(t, err)
err = p.NotifyMessage(model.Game{}, ``)
assert.Nil(t, err)
}
}
func TestNotifyScoreUpdate(t *testing.T) {
tests := []struct {
desc string
npc model.PlayerID
}{{
desc: `test dumb NPC`,
npc: Dumb,
}, {
desc: `test simple NPC`,
npc: Simple,
}, {
desc: `test calculated NPC`,
npc: Calc,
}}
for _, tc := range tests {
p, err := NewNPCPlayer(tc.npc, NewNilHandler())
require.Nil(t, err)
err = p.NotifyScoreUpdate(model.Game{}, ``)
assert.Nil(t, err)
}
}
func TestNewNPCPlayer(t *testing.T) {
tests := []struct {
desc string
npc model.PlayerID
expErr bool
expPlayer interface{}
}{{
desc: `test dumb NPC`,
npc: Dumb,
expErr: false,
expPlayer: &dumbNPC{},
}, {
desc: `test simple NPC`,
npc: Simple,
expErr: false,
expPlayer: &simpleNPC{},
}, {
desc: `test calculated NPC`,
npc: Calc,
expErr: false,
expPlayer: &calculatedNPC{},
}, {
desc: `test unsupported type`,
npc: `unsupported`,
expErr: true,
expPlayer: nil,
}}
for _, tc := range tests {
p, err := NewNPCPlayer(tc.npc, NewNilHandler())
if tc.expErr {
assert.Error(t, err)
assert.Nil(t, p)
} else {
n, ok := p.(*NPCPlayer)
assert.True(t, ok)
assert.NoError(t, err)
assert.Equal(t, tc.expPlayer, n.player)
}
}
}
| true |
abef6117b4cd52f9f3089e1f1e093220d5c97d9a
|
Go
|
adrianolaselva/solr-client-go
|
/solr/connection.go
|
UTF-8
| 333 | 2.59375 | 3 |
[
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] |
permissive
|
[
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] |
permissive
|
package solr
import (
"net/url"
"sync"
)
type ConnectionPool interface {
Next() (*Connection, error)
URLs() []*url.URL
}
type Connection struct {
sync.Mutex
URL *url.URL
}
type singleConnectionPool struct {
connection *Connection
}
type statusConnectionPool struct {
sync.Mutex
live []*Connection
dead []*Connection
}
| true |
195444f46aa25220838cd76e33eaf004fa15c73a
|
Go
|
sahansera/go-experiments
|
/7-json-unmarshal/main.go
|
UTF-8
| 241 | 2.875 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"encoding/json"
"fmt"
)
type T struct {
HelloWorld string `json:"HelloWorld"`
}
func main() {
foo := `{"HelloWorld": "1", "helloWorld": "2"}`
var dat T
_ = json.Unmarshal([]byte(foo), &dat)
fmt.Println(dat)
}
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.