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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e2cb4f4d048270812323f035838246a8afefa329
|
Go
|
LeeChiChuang/GoExample
|
/interview/q004.go
|
UTF-8
| 1,242 | 3.671875 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"reflect"
"unsafe"
)
/*
翻转字符串
问题描述
请实现一个算法,在不使用【额外数据结构和储存空间】的情况下,翻转一个给定的字符串(可以使用单个过程变量)。
给定一个string,请返回一个string,为翻转后的字符串。保证字符串的长度小于等于5000。
*/
func reverString(s string) (string, bool) {
str := []rune(s)
l := len(str)
if l > 5000 {
return s, false
}
for i := 0; i < l/2; i++ {
str[i], str[l-1-i] = str[l-1-i], str[i]
}
return string(str), true
}
func string2Bytes(s string) []byte {
return *(*[]byte)(unsafe.Pointer(&s))
}
func s2b(s string) (b []byte) {
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
sh := *(*reflect.StringHeader)(unsafe.Pointer(&s))
bh.Data = sh.Data
bh.Len = sh.Len
bh.Cap = sh.Len
return b
}
func StringToBytes(s string) []byte {
return *(*[]byte)(unsafe.Pointer(
&struct {
string
Cap int
}{s, len(s)},
))
}
func main() {
str := "hello"
b1 := s2b(str)
/*
l := len(h)
for i := 0; i < l/2; i++ {
h[i], h[l-1-i] = str[l-1-i], str[i]
}
*/
fmt.Println(b1)
b1[0] = 'a'
b2 := StringToBytes(str)
fmt.Println(b2)
b2[0] = 'a'
//fmt.Println(string(h))
}
| true |
35153d28fb3157b9fe477bae2275dc1e99dcf820
|
Go
|
aliforever/golang-backend-training
|
/chapter14/section14.3/api/httpswitch.go
|
UTF-8
| 311 | 3 | 3 |
[] |
no_license
|
[] |
no_license
|
package api
import (
"fmt"
"net/http"
)
type HTTPSwitch struct {
}
func (hs HTTPSwitch) ServeHTTP(wr http.ResponseWriter, r *http.Request) {
path := r.URL.Path
switch path {
case "/hello":
fmt.Fprintf(wr, "Hello world! method = %q", r.Method)
return
default:
http.NotFound(wr, r)
return
}
}
| true |
e5c60fee00b32692caca008af098502f95bd4e30
|
Go
|
squzy/squzy
|
/apps/squzy_incident/expression/expression.go
|
UTF-8
| 2,447 | 2.515625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
[
"BSD-3-Clause"
] |
permissive
|
package expression
import (
"errors"
"fmt"
"github.com/antonmedv/expr"
"github.com/araddon/dateparse"
apiPb "github.com/squzy/squzy_generated/generated/github.com/squzy/squzy_proto"
timestamp "google.golang.org/protobuf/types/known/timestamppb"
"strconv"
"time"
)
type Expression interface {
ProcessRule(ruleType apiPb.ComponentOwnerType, id string, rule string) (bool, error)
IsValid(ruleType apiPb.ComponentOwnerType, rule string) error
}
type expressionStruct struct {
storageClient apiPb.StorageClient
}
var (
errRuleTypeNotProvided = errors.New("rule type not provided")
)
func NewExpression(storage apiPb.StorageClient) Expression {
return &expressionStruct{
storageClient: storage,
}
}
func (e *expressionStruct) ProcessRule(ruleType apiPb.ComponentOwnerType, id string, rule string) (bool, error) {
env, err := e.getEnv(ruleType, id)
if err != nil {
return false, err
}
program, err := expr.Compile(rule, expr.Env(env))
if err != nil {
return false, err
}
output, err := expr.Run(program, env)
if err != nil {
return false, err
}
value, err := strconv.ParseBool(fmt.Sprintf("%v", output))
if err != nil {
return false, err
}
return value, nil
}
func (e *expressionStruct) IsValid(ruleType apiPb.ComponentOwnerType, rule string) error {
env, err := e.getEnv(ruleType, "id")
if err != nil {
return err
}
_, err = expr.Compile(rule, expr.Env(env))
return err
}
func (e *expressionStruct) getEnv(owner apiPb.ComponentOwnerType, id string) (map[string]interface{}, error) {
switch owner {
case apiPb.ComponentOwnerType_COMPONENT_OWNER_TYPE_SCHEDULER:
return e.getSnapshotEnv(id), nil
case apiPb.ComponentOwnerType_COMPONENT_OWNER_TYPE_AGENT:
return e.getAgentEnv(id), nil
case apiPb.ComponentOwnerType_COMPONENT_OWNER_TYPE_APPLICATION:
return e.getTransactionEnv(id), nil
}
return nil, errRuleTypeNotProvided
}
func convertToTimestamp(strTime string) *timestamp.Timestamp {
t, err := dateparse.ParseAny(strTime)
if err != nil {
panic(err)
}
res := timestamp.New(t)
err = res.CheckValid()
if err != nil {
panic(err)
}
return res
}
func getTimeRange(start, end *timestamp.Timestamp) int64 {
err := start.CheckValid()
if err != nil {
panic("No start time")
}
startTime := start.AsTime()
err = end.CheckValid()
if err != nil {
panic("No end time")
}
endTime := end.AsTime()
return (endTime.UnixNano() - startTime.UnixNano()) / int64(time.Millisecond)
}
| true |
b10cac1e17066ca06904958a67d151d4e7dd0682
|
Go
|
konjoot/benches
|
/kami/contact_query.go
|
UTF-8
| 3,752 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"errors"
"log"
"github.com/jmoiron/sqlx"
)
const (
USERS_QUERY = `
select id,
email,
first_name,
last_name,
middle_name,
date_of_birth,
sex
from users
where deleted_at is null
order by id
limit ?
offset ?;`
PROFILES_QUERY = `
select p.id,
p.type,
p.user_id,
p.school_id,
s.short_name,
s.guid,
p.class_unit_id,
cu.name,
p.enlisted_on,
p.left_on,
c.subject_id,
sb.name
from profiles p
left outer join schools s
on s.id = p.school_id
and s.deleted_at is null
left outer join class_units cu
on cu.id = p.class_unit_id
and cu.deleted_at is null
left outer join competences c
on c.profile_id = p.id
left outer join subjects sb
on c.subject_id = sb.id
where p.deleted_at is null
and p.user_id in (?)
order by p.user_id, p.id;`
)
func NewContactQuery(page int, perPage int) *ContactQuery {
if page < 1 {
page = 1
}
if perPage < 1 {
perPage = 1
}
return &ContactQuery{
limit: perPage,
offset: perPage * (page - 1),
collection: NewContactList(perPage),
}
}
type ContactQuery struct {
limit int
offset int
collection ContactList
}
func (cq *ContactQuery) All() []*Contact {
if !cq.fillUsers() {
return NewContactList(0).Items
}
if err := cq.fillDependentData(); err != nil {
log.Print(err)
}
return cq.collection.Items
}
func (cq *ContactQuery) fillUsers() (ok bool) {
var err error
defer func() {
if err != nil {
log.Print(err)
}
if cq.collection.Any() {
ok = true
}
}()
db, err := DBConn()
if err != nil {
return
}
query := db.Rebind(USERS_QUERY)
rows, err := db.Queryx(query, cq.limit, cq.offset)
if err != nil {
return
}
defer rows.Close()
var contact *Contact
for rows.Next() {
contact = NewContact()
rows.Scan(
&contact.Id,
&contact.Email,
&contact.FirstName,
&contact.LastName,
&contact.MiddleName,
&contact.DateOfBirth,
&contact.Sex,
)
cq.collection.Items = append(cq.collection.Items, contact)
}
return
}
func (cq *ContactQuery) fillDependentData() (err error) {
db, err := DBConn()
if err != nil {
return
}
query, args, err := sqlx.In(PROFILES_QUERY, cq.collection.Ids())
if err != nil {
return
}
query = db.Rebind(query)
rows, err := db.Queryx(query, args...)
if err != nil {
return
}
defer rows.Close()
current := cq.collection.Next()
if current == nil {
return errors.New("Empty collection")
}
var (
profile *Profile
classUnit *ClassUnit
school *School
subject *Subject
)
for rows.Next() {
profile = NewProfile()
classUnit = NewClassUnit()
school = NewSchool()
subject = NewSubject()
rows.Scan(
&profile.Id,
&profile.Type,
&profile.UserId,
&school.Id,
&school.Name,
&school.Guid,
&classUnit.Id,
&classUnit.Name,
&classUnit.EnlistedOn,
&classUnit.LeftOn,
&subject.Id,
&subject.Name,
)
for *current.Id != *profile.UserId {
if next := cq.collection.Next(); next != nil {
current = next
} else {
break
}
}
if *current.Id != *profile.UserId {
continue
}
if classUnit.Id != nil {
profile.ClassUnit = classUnit
}
if school.Id != nil {
profile.School = school
}
if lastPr := current.LastProfile(); lastPr == nil {
current.Profiles = append(current.Profiles, profile)
} else if *lastPr.Id != *profile.Id {
current.Profiles = append(current.Profiles, profile)
}
if subject.Id != nil {
current.LastProfile().Subjects = append(
current.LastProfile().Subjects,
subject,
)
}
}
return
}
| true |
ad4e36803310cbd16965aca635c3dea10fc66bd6
|
Go
|
Bhanditz/wharf
|
/tlc/tlc_test.go
|
UTF-8
| 5,351 | 2.71875 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
package tlc
import (
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"runtime"
"testing"
"github.com/itchio/arkive/zip"
"github.com/itchio/wharf/archiver"
"github.com/itchio/wharf/state"
"github.com/stretchr/testify/assert"
)
func Test_NonDirWalk(t *testing.T) {
tmpPath, err := ioutil.TempDir("", "nondirwalk")
must(t, err)
defer os.RemoveAll(tmpPath)
foobarPath := path.Join(tmpPath, "foobar")
f, err := os.Create(foobarPath)
must(t, err)
must(t, f.Close())
_, err = WalkDir(f.Name(), &WalkOpts{})
assert.NotNil(t, err, "should refuse to walk non-directory")
}
func Test_WalkZip(t *testing.T) {
tmpPath := mktestdir(t, "walkzip")
defer os.RemoveAll(tmpPath)
tmpPath2, err := ioutil.TempDir("", "walkzip2")
must(t, err)
defer os.RemoveAll(tmpPath2)
container, err := WalkDir(tmpPath, &WalkOpts{})
must(t, err)
zipPath := path.Join(tmpPath2, "container.zip")
zipWriter, err := os.Create(zipPath)
must(t, err)
defer zipWriter.Close()
_, err = archiver.CompressZip(zipWriter, tmpPath, &state.Consumer{})
must(t, err)
zipSize, err := zipWriter.Seek(0, io.SeekCurrent)
must(t, err)
zipReader, err := zip.NewReader(zipWriter, zipSize)
must(t, err)
zipContainer, err := WalkZip(zipReader, &WalkOpts{})
must(t, err)
if testSymlinks {
assert.Equal(t, "5 files, 3 dirs, 2 symlinks", container.Stats(), "should report correct stats")
} else {
assert.Equal(t, "5 files, 3 dirs, 0 symlinks", container.Stats(), "should report correct stats")
}
totalSize := int64(0)
for _, regular := range regulars {
totalSize += int64(regular.Size)
}
assert.Equal(t, totalSize, container.Size, "should report correct size")
must(t, container.EnsureEqual(zipContainer))
}
func Test_Walk(t *testing.T) {
tmpPath := mktestdir(t, "walk")
defer os.RemoveAll(tmpPath)
container, err := WalkDir(tmpPath, &WalkOpts{})
must(t, err)
dirs := []string{
"foo",
"foo/dir_a",
"foo/dir_b",
}
for i, dir := range dirs {
assert.Equal(t, dir, container.Dirs[i].Path, "dirs should be all listed")
}
files := []string{
"foo/dir_a/baz",
"foo/dir_a/bazzz",
"foo/dir_b/zoom",
"foo/file_f",
"foo/file_z",
}
for i, file := range files {
assert.Equal(t, file, container.Files[i].Path, "files should be all listed")
}
if testSymlinks {
for i, symlink := range symlinks {
assert.Equal(t, symlink.Newname, container.Symlinks[i].Path, "symlink should be at correct path")
assert.Equal(t, symlink.Oldname, container.Symlinks[i].Dest, "symlink should point to correct path")
}
}
if testSymlinks {
assert.Equal(t, "5 files, 3 dirs, 2 symlinks", container.Stats(), "should report correct stats")
} else {
assert.Equal(t, "5 files, 3 dirs, 0 symlinks", container.Stats(), "should report correct stats")
}
totalSize := int64(0)
for _, regular := range regulars {
totalSize += int64(regular.Size)
}
assert.Equal(t, totalSize, container.Size, "should report correct size")
if testSymlinks {
container, err := WalkDir(tmpPath, &WalkOpts{Dereference: true})
must(t, err)
assert.EqualValues(t, 0, len(container.Symlinks), "when dereferencing, no symlinks should be listed")
files := []string{
"foo/dir_a/baz",
"foo/dir_a/bazzz",
"foo/dir_b/zoom",
"foo/file_f",
"foo/file_m",
"foo/file_o",
"foo/file_z",
}
for i, file := range files {
assert.Equal(t, file, container.Files[i].Path, "when dereferencing, symlinks should appear as files")
}
// add both dereferenced symlinks to total size
totalSize += int64(regulars[3].Size) // foo/file_z
totalSize += int64(regulars[1].Size) // foo/dir_a/baz
assert.Equal(t, totalSize, container.Size, "when dereferencing, should report correct size")
}
}
func Test_Prepare(t *testing.T) {
tmpPath := mktestdir(t, "prepare")
defer os.RemoveAll(tmpPath)
container, err := WalkDir(tmpPath, &WalkOpts{})
must(t, err)
tmpPath2, err := ioutil.TempDir("", "prepare")
defer os.RemoveAll(tmpPath2)
must(t, err)
err = container.Prepare(tmpPath2)
must(t, err)
container2, err := WalkDir(tmpPath2, &WalkOpts{})
must(t, err)
must(t, container.EnsureEqual(container2))
}
// Support code
func must(t *testing.T, err error) {
if err != nil {
t.Error("must failed: ", err.Error())
t.FailNow()
}
}
type regEntry struct {
Path string
Size int
Byte byte
}
type symlinkEntry struct {
Oldname string
Newname string
}
var regulars = []regEntry{
{"foo/file_f", 50, 0xd},
{"foo/dir_a/baz", 10, 0xa},
{"foo/dir_b/zoom", 30, 0xc},
{"foo/file_z", 40, 0xe},
{"foo/dir_a/bazzz", 20, 0xb},
}
var symlinks = []symlinkEntry{
{"file_z", "foo/file_m"},
{"dir_a/baz", "foo/file_o"},
}
var testSymlinks = runtime.GOOS != "windows"
func mktestdir(t *testing.T, name string) string {
tmpPath, err := ioutil.TempDir("", "tmp_"+name)
must(t, err)
must(t, os.RemoveAll(tmpPath))
for _, entry := range regulars {
fullPath := filepath.Join(tmpPath, entry.Path)
must(t, os.MkdirAll(filepath.Dir(fullPath), os.FileMode(0777)))
file, err := os.Create(fullPath)
must(t, err)
filler := []byte{entry.Byte}
for i := 0; i < entry.Size; i++ {
_, err := file.Write(filler)
must(t, err)
}
must(t, file.Close())
}
if testSymlinks {
for _, entry := range symlinks {
new := filepath.Join(tmpPath, entry.Newname)
must(t, os.Symlink(entry.Oldname, new))
}
}
return tmpPath
}
| true |
f9c40c3b01d771f87065d58833c538f294727741
|
Go
|
conalryan/go-notes
|
/lang/controlflow/main.go
|
UTF-8
| 4,389 | 3.890625 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
// Looping
// for
// break keyword
// continue keyword
fmt.Println("\nfor loop:")
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// Multiple variables
// Scoped to for loop
for i, j := 0, 0; i < 5; i, j = i+1, j+1 {
fmt.Println(i)
fmt.Println(j)
}
// Split declaration
i := 0 // i now scoped to main function
for ; i < 5; i++ {
fmt.Println(i)
}
// While loop ~ sort of
fmt.Println("\npseudo while loop:")
j := 0
for j < 5 {
fmt.Println(j)
j++
}
b := true
for b {
fmt.Println(b)
b = false
}
for true {
fmt.Println(b)
if true {
break
}
}
// Range keyword
// Use to loop over collections (arrays, slices, maps)
fmt.Println("\nRange:")
s := []int{1, 2, 3}
for k, v := range s {
fmt.Println(k, v)
// 0 1
// 1 2
// 2 3
}
ar := [...]int{1, 2, 3}
for k, v := range ar {
fmt.Println(k, v)
// 0 1
// 1 2
// 2 3
}
m := map[string]int{
"key1": 1,
"key2": 2,
}
for k, v := range m {
fmt.Println(k, v)
// key1 1
// key2 2
}
str := "hello"
for k, v := range str {
// v will be ASCII number, covert to string
fmt.Println(k, v, string(v))
// 0 104 h
// 1 101 e
// 2 108 l
// 3 108 l
// 4 111 o
}
// Only keys
for k := range m {
fmt.Println(k)
// key1
// key2
}
// Only values
for _, v := range m {
fmt.Println(v)
// 1
// 2
}
// Channels
// used for concurrency
// can range over them...
// Defer
// Envoke function but delay execution
// Executes any defered functions that were passed into it after the outer function exits, but before any values are returned
// Runs in LIFO order
// Commonly used to close resources
// Takes a function all as input, can be an anoymous function, but anonymous function must be called.
fmt.Println("\nDefer:")
defered := deferFn()
fmt.Println(defered) // 22
closure()
// Panic
// Go returns errors rather than exceptions for common exceptions in other languages,
// like trying to open a file that doesn't exist
// Only use when the program is in a state the can't be recovered from e.g. web server can't start
// Panic happens after deferred statements,
// which makes sense since you want to close resource before exiting program
fmt.Println("\nPanic:")
// If you uncomment the code below the program will exit after the panic
// panicEx()
// Recover
// When you run into panic, how to recover
// Only usefule in deferred functions
// Current function will not attempt to continue, but higher functions in call stack will
fmt.Println("\nRecover:")
// pre panicker
// about to panic
// this anonymous function will immediately envoke
// 2020/02/07 18:54:04 Error: uh oh
// post panicker
fmt.Println("pre panicker")
panicker()
fmt.Println("post panicker")
}
// Will print:
// deferFn...
// start
// end
// <deferFn has finished at this point>
// Now runtime sees it has a defered function to call
// runtime calls that function then returns value
// middle
func deferFn() int {
fmt.Println("deferFn...")
fmt.Println("start")
defer fmt.Println("middle")
fmt.Println("end")
return 22
}
func closure() {
a := "Start"
defer fmt.Println(a)
a = "end"
}
func httpWithDefer() {
res, err := http.Get("http://www.google.com/robots.txt")
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
robots, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", robots)
}
func panicEx() {
n1, n2 := 1, 0
if n1 == 0 || n2 == 0 {
panic("I can't divide by zero!") // apparently, automatically prints stack trace too
} else {
ans := n1 / n2 // 1 / 0 error
fmt.Println(ans)
}
}
// Automatically envoke anonymous function with braces after declaration
// Will print
// start
// Error: uh oh
func panicker() {
fmt.Println("about to panic")
func() {
fmt.Println("this anonymous function will immediately envoke")
}()
defer func() {
if err := recover(); err != nil {
log.Println("Error: ", err)
// If you can't handle the error then rethrow the panic
// panic(err)
}
}()
panic("uh oh")
fmt.Println("done panicking") // this will never print
}
| true |
2086f2d647868afb43fcbb34db2f0bbbbb749ae8
|
Go
|
oasangqi/proxy
|
/internal/conn/conn_tcp.go
|
UTF-8
| 1,511 | 2.90625 | 3 |
[] |
no_license
|
[] |
no_license
|
package conn
import (
"encoding/binary"
"errors"
"github.com/oasangqi/proxy/pkg/bufio"
"github.com/oasangqi/proxy/pkg/bytes"
"net"
)
type TCPConn struct {
conn net.Conn
r *bufio.Reader
w *bufio.Writer
rb *bytes.Buffer
wb *bytes.Buffer
rp *bytes.Pool
wp *bytes.Pool
}
func NewTcpConn(conn net.Conn, rp, wp *bytes.Pool) *TCPConn {
tc := &TCPConn{
conn: conn,
r: new(bufio.Reader),
w: new(bufio.Writer),
rp: rp,
wp: wp,
rb: rp.Get(),
wb: wp.Get(),
}
tc.r.ResetBuffer(conn, tc.rb.Bytes())
tc.w.ResetBuffer(conn, tc.wb.Bytes())
return tc
}
func (c *TCPConn) ReadMessage() (payload []byte, err error) {
var (
packLen uint32
buf []byte
)
if buf, err = c.r.Pop(4); err != nil {
return
}
packLen = binary.LittleEndian.Uint32(buf[0:4])
if packLen > 16*1024 {
return nil, errors.New("invalid pack size")
}
if packLen > 0 {
payload, err = c.r.Pop(int(packLen))
}
xorfunc(payload)
return
}
func (c *TCPConn) WriteMessage(payload []byte) (err error) {
var (
buf []byte
packLen uint32
)
packLen = uint32(len(payload))
if buf, err = c.w.Peek(4); err != nil {
return
}
binary.LittleEndian.PutUint32(buf[0:4], packLen)
if packLen > 0 {
xorfunc(payload)
_, err = c.w.Write(payload)
c.w.Flush()
}
return
}
func (c *TCPConn) RemoteAddr() string {
return c.conn.RemoteAddr().String()
}
func (c *TCPConn) Close() {
c.conn.Close()
c.rp.Put(c.rb)
c.wp.Put(c.wb)
}
func (c *TCPConn) DisConnect() {
c.conn.Close()
}
| true |
99f1fb379fd97b1d32f3fd2a43eaabec456b25dd
|
Go
|
muyunil/strbot
|
/txqq/backup/rollBack.go
|
UTF-8
| 1,709 | 2.828125 | 3 |
[] |
no_license
|
[] |
no_license
|
package backup
import (
"os"
"fmt"
"strings"
"github.com/otiai10/copy"
)
const (
RdDirErr = "回滚存档路径错误!\n检查参数路径是否存在及格式正确!\n格式参考:\n<rd worlds-2020-12-10_16-44-44>\n使用lsbd查看可回滚存档列表"
RdOk = "回滚完成!"
RdErr = "回滚copy错误!请管理员查看日志!"
)
/*func main(){
// fmt.Println(Rd("rb worlds-2020-10-08_20-14-45"))
fmt.Println(Rd("rb worlds-2020-10-98_20-14-45"))
}*/
func Rd(dir string,rdChat chan <- string) {
var rDir string
tmp := strings.Split(dir, " ")
if len(tmp[1]) < 21 {
rdChat <- RdDirErr + "1"
return
}
// if i := strings.Index(test[1],"-") != -1 {
if strings.HasPrefix(tmp[1],"worlds-") {
tmp2 := strings.Split(tmp[1],"_")
if len(tmp2) < 2 {
rdChat <- RdDirErr + "2"
return
}
tmp3 := strings.Split(tmp2[0],"-")
if len(tmp3) < 4 {
rdChat <- RdDirErr + "3"
return
}
if tmp3[3][0] == '0' {
rDir += fmt.Sprintf("./backup/%s/%s/%s/",tmp3[2],string(tmp3[3][1]),tmp[1])
}else{
rDir += fmt.Sprintf("./backup/%s/%s/%s/",tmp3[2],tmp3[3],tmp[1])
}
fmt.Println(rDir)
}else{
rdChat <- RdDirErr + "4"
return
}
if Exist(rDir) == true {
err := copy.Copy(rDir,"./worlds/")
if err != nil {
rdChat <-RdErr
fmt.Println(err)
}
}else{
rdChat <- RdDirErr + "5"
return
}
rdChat <- RdOk
}
func Exist(filename string) bool {
_, err := os.Stat(filename)
return err == nil || os.IsExist(err)
}
| true |
627d8d981fba8289fe9b03fcc4d07fbebbdcfadd
|
Go
|
robhurring/cmd
|
/cmd.go
|
UTF-8
| 3,740 | 3.140625 | 3 |
[] |
no_license
|
[] |
no_license
|
package cmd
import (
"bytes"
"fmt"
"os"
"os/exec"
"runtime"
"strings"
"syscall"
"github.com/kballard/go-shellquote"
)
var (
// isWindows determines if running on Windows or *nix
isWindows = runtime.GOOS == "windows"
)
// Cmd represents an OS command
type Cmd struct {
// Name is the name of the command
Name string
// Args are any args to pass to the command
Args []string
}
// Copy copies a string to the OS clipboard
func Copy(data string) error {
var cpCmd string
if isWindows {
cpCmd = "clip"
} else {
cpCmd = "pbcopy"
}
echo := New("echo").WithArgs(data)
copy := New(cpCmd)
_, _, err := Pipeline(echo, copy)
return err
}
// Open opens a location
// OSX only
func Open(location string) error {
return New("open").WithArgs(location).Run()
}
// String prints the command as a string
func (cmd *Cmd) String() string {
return fmt.Sprintf("%s %s", cmd.Name, strings.Join(cmd.Args, " "))
}
// WithArgs adds arguments to the current command
func (cmd *Cmd) WithArgs(args ...string) *Cmd {
for _, arg := range args {
cmd.Args = append(cmd.Args, arg)
}
return cmd
}
// CombinedOutput runs the command and returns its combined standard output and standard error.
func (cmd *Cmd) CombinedOutput() (string, error) {
output, err := exec.Command(cmd.Name, cmd.Args...).CombinedOutput()
return string(output), err
}
// Run runs command with `Exec` on platforms except Windows
// which only supports `Spawn`
func (cmd *Cmd) Run() error {
if isWindows {
return cmd.Spawn()
}
return cmd.Exec()
}
// Spawn runs command with spawn(3)
func (cmd *Cmd) Spawn() error {
c := exec.Command(cmd.Name, cmd.Args...)
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr
return c.Run()
}
// Exec runs command with exec(3)
// Note that Windows doesn't support exec(3): http://golang.org/src/pkg/syscall/exec_windows.go#L339
func (cmd *Cmd) Exec() error {
binary, err := exec.LookPath(cmd.Name)
if err != nil {
return fmt.Errorf("command not found: %s", cmd.Name)
}
args := []string{binary}
args = append(args, cmd.Args...)
return syscall.Exec(binary, args, os.Environ())
}
// Pipeline runs a series of commands, passing the output of one command to the
// input of the next
func Pipeline(list ...*Cmd) (string, string, error) {
var output bytes.Buffer
var stderr bytes.Buffer
var err error
// Require at least one command
if len(list) < 1 {
return "", "", nil
}
var newCmd *exec.Cmd
cmds := make([]*exec.Cmd, 0, 4)
// Convert into an exec.Cmd
for _, cmd := range list {
newCmd = exec.Command(cmd.Name, cmd.Args...)
cmds = append(cmds, newCmd)
}
// Collect the output from the command(s)
last := len(cmds) - 1
for i, cmd := range cmds[:last] {
// Connect each command's stdin to the previous command's stdout
if cmds[i+1].Stdin, err = cmd.StdoutPipe(); err != nil {
return "", "", err
}
// Connect each command's stderr to a buffer
cmd.Stderr = &stderr
}
// Connect the output and error for the last command
cmds[last].Stdout, cmds[last].Stderr = &output, &stderr
// Start each command
for _, cmd := range cmds {
if err = cmd.Start(); err != nil {
return output.String(), stderr.String(), err
}
}
// Wait for each command to complete
for _, cmd := range cmds {
if err := cmd.Wait(); err != nil {
return output.String(), stderr.String(), err
}
}
// Return the pipeline output and the collected standard error
return output.String(), stderr.String(), nil
}
// New creates a new Cmd instance
func New(cmd string) *Cmd {
var args []string
cmds, err := shellquote.Split(cmd)
if err != nil {
panic(err)
}
name := cmds[0]
for _, arg := range cmds[1:] {
args = append(args, arg)
}
return &Cmd{Name: name, Args: args}
}
| true |
c632377ee165c6477d895e3f5678cb925a3996b7
|
Go
|
arvi3411301/init-templates
|
/cli/migrate/database/migration.go
|
UTF-8
| 1,716 | 3.5 | 4 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
package database
import "sort"
// Migrations wraps Migration and has an internal index
// to keep track of Migration order in database.
type Migrations struct {
index uint64Slice
}
func NewMigrations() *Migrations {
return &Migrations{
index: make(uint64Slice, 0),
}
}
func (i *Migrations) Append(version uint64) {
if i.findPos(version) > 0 {
return
}
i.index = append(i.index, version)
sort.Sort(i.index)
}
func (i *Migrations) First() (version uint64, ok bool) {
if len(i.index) == 0 {
return 0, false
}
return i.index[0], true
}
func (i *Migrations) Last() (uint64, bool) {
if len(i.index) == 0 {
return 0, false
}
return i.index[len(i.index)-1], true
}
func (i *Migrations) Prev(version uint64) (prevVersion uint64, ok bool) {
pos := i.findPos(version)
if pos >= 1 && len(i.index) > pos-1 {
return i.index[pos-1], true
}
return 0, false
}
func (i *Migrations) Next(version uint64) (nextVersion uint64, ok bool) {
pos := i.findPos(version)
if pos >= 0 && len(i.index) > pos+1 {
return i.index[pos+1], true
}
return 0, false
}
func (i *Migrations) Read(version uint64) (ok bool) {
pos := i.findPos(version)
if pos >= 0 {
return true
}
return false
}
func (i *Migrations) findPos(version uint64) int {
if len(i.index) > 0 {
ix := i.index.Search(version)
if ix < len(i.index) && i.index[ix] == version {
return ix
}
}
return -1
}
type uint64Slice []uint64
func (s uint64Slice) Len() int {
return len(s)
}
func (s uint64Slice) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s uint64Slice) Less(i, j int) bool {
return s[i] < s[j]
}
func (s uint64Slice) Search(x uint64) int {
return sort.Search(len(s), func(i int) bool { return s[i] >= x })
}
| true |
85dc84e35caeca30ab5dd9fdfb77dc75cede75e8
|
Go
|
shoenig/marathonctl
|
/config/configuration.go
|
UTF-8
| 697 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package config
import (
"bufio"
"fmt"
"os"
"strings"
)
type Properties map[string]string
func (p Properties) GetStringOr(s, alt string) string {
v, exists := p[s]
if !exists {
return alt
}
return v
}
func ReadProperties(filename string) (Properties, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
m := make(map[string]string)
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
tokens := strings.SplitN(line, ":", 2)
if len(tokens) != 2 {
return nil, fmt.Errorf("unable to parse line: %q", line)
}
m[tokens[0]] = tokens[1]
}
if scErr := scanner.Err(); scErr != nil {
return nil, scErr
}
return m, nil
}
| true |
a270105e696583a5e54c7d52734f307c97e958e9
|
Go
|
onlineconf/onlineconf
|
/admin/go/common/database.go
|
UTF-8
| 1,148 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package common
import (
"database/sql"
"net"
"time"
"github.com/go-sql-driver/mysql"
"github.com/rs/zerolog/log"
)
var DB *sql.DB
func MysqlInitConfig(config DatabaseConfig) *mysql.Config {
mysqlConfig := mysql.NewConfig()
mysqlConfig.User = config.User
mysqlConfig.Passwd = config.Password
mysqlConfig.Net = "tcp"
mysqlConfig.Addr = net.JoinHostPort(config.Host, "3306")
mysqlConfig.DBName = config.Base
mysqlConfig.Params = map[string]string{
"charset": "utf8mb4",
"collation": "utf8mb4_general_ci",
}
return mysqlConfig
}
func OpenDatabase(config DatabaseConfig) *sql.DB {
mysqlConfig := MysqlInitConfig(config)
db, err := sql.Open("mysql", mysqlConfig.FormatDSN())
if err != nil {
log.Fatal().Err(err).Msg("failed to open database")
}
db.SetConnMaxLifetime(time.Duration(config.MaxLifetime) * time.Second)
db.SetMaxOpenConns(config.MaxConn)
return db
}
func ReadStrings(rows *sql.Rows) ([]string, error) {
list := make([]string, 0)
defer rows.Close()
for rows.Next() {
var str string
err := rows.Scan(&str)
if err != nil {
return nil, err
}
list = append(list, str)
}
return list, nil
}
| true |
b18bfa028599e5cf3cad6aec11d4cf8364b9c754
|
Go
|
gabrielperezs/CARBOnic
|
/lib/aws_session_pool.go
|
UTF-8
| 1,649 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package lib
import (
"fmt"
"log"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
)
const (
SESSION_INTERVAL time.Duration = 24 * time.Hour
SESSION_RETRY time.Duration = 30 * time.Second
)
var (
sessMutex sync.RWMutex
Sessions = make(map[string]*Session)
)
type Session struct {
Profile string
Region string
Svc *sqs.SQS
lastConnection time.Time
tick *time.Ticker
done chan bool
}
func NewSession(profile string, region string) *Session {
sessMutex.RLock()
defer sessMutex.RUnlock()
key := fmt.Sprintf("%s:%s", profile, region)
if sqs, ok := Sessions[key]; ok {
return sqs
}
s := &Session{
Profile: profile,
Region: region,
lastConnection: time.Now(),
tick: time.NewTicker(SESSION_INTERVAL),
done: make(chan bool, 0),
}
Sessions[key] = s
go s.loopSession()
s.connect()
return s
}
func (s *Session) loopSession() {
defer s.tick.Stop()
for {
select {
case <-s.tick.C:
log.Printf("Renew session with AWS %s", s.lastConnection)
s.connect()
case <-s.done:
return
}
}
}
func (s *Session) connect() {
opt := session.Options{}
if s.Profile != "" {
opt = session.Options{
Profile: s.Profile,
SharedConfigState: session.SharedConfigEnable,
}
}
sess, err := session.NewSessionWithOptions(opt)
if err != nil {
log.Printf("AWS Session ERROR: failed to create session: %s", err)
return
}
s.Svc = sqs.New(sess, &aws.Config{Region: aws.String(s.Region)})
s.lastConnection = time.Now()
}
| true |
79701165e65473faf5ddba8141791cadf703cb7a
|
Go
|
mehrdad-shokri/drone
|
/handler/api/user/update_test.go
|
UTF-8
| 3,194 | 2.59375 | 3 |
[
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
[
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
// Copyright 2019 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by the Drone Non-Commercial License
// that can be found in the LICENSE file.
package user
import (
"bytes"
"encoding/json"
"net/http/httptest"
"testing"
"github.com/drone/drone/handler/api/errors"
"github.com/drone/drone/handler/api/request"
"github.com/drone/drone/mock"
"github.com/drone/drone/core"
"github.com/golang/mock/gomock"
"github.com/google/go-cmp/cmp"
)
func TestUpdate(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
userInput := &core.User{
Login: "octocat",
Email: "[email protected]",
}
user := &core.User{
Login: "octocat",
Email: "",
}
users := mock.NewMockUserStore(controller)
users.EXPECT().Update(gomock.Any(), user)
in := new(bytes.Buffer)
json.NewEncoder(in).Encode(userInput)
w := httptest.NewRecorder()
r := httptest.NewRequest("PATCH", "/api/user", in)
r = r.WithContext(
request.WithUser(r.Context(), user),
)
HandleUpdate(users)(w, r)
if got, want := w.Code, 200; want != got {
t.Errorf("Want response code %d, got %d", want, got)
}
if got, want := user.Email, "[email protected]"; got != want {
t.Errorf("Want user email %v, got %v", want, got)
}
got, want := new(core.User), user
json.NewDecoder(w.Body).Decode(got)
if diff := cmp.Diff(got, want); len(diff) != 0 {
t.Errorf(diff)
}
}
// the purpose of this unit test is to verify that an invalid
// (in this case missing) request body will result in a bad
// request error returned to the client.
func TestUpdate_BadRequest(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
mockUser := &core.User{
ID: 1,
Login: "octocat",
}
in := new(bytes.Buffer)
w := httptest.NewRecorder()
r := httptest.NewRequest("PATCH", "/api/user", in)
r = r.WithContext(
request.WithUser(r.Context(), mockUser),
)
HandleUpdate(nil)(w, r)
if got, want := w.Code, 400; want != got {
t.Errorf("Want response code %d, got %d", want, got)
}
got, want := new(errors.Error), &errors.Error{Message: "EOF"}
json.NewDecoder(w.Body).Decode(got)
if diff := cmp.Diff(got, want); len(diff) != 0 {
t.Errorf(diff)
}
}
// the purpose of this unit test is to verify that an error
// updating the database will result in an internal server
// error returned to the client.
func TestUpdate_ServerError(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
userInput := &core.User{
Login: "octocat",
Email: "[email protected]",
}
user := &core.User{
Login: "octocat",
Email: "",
}
users := mock.NewMockUserStore(controller)
users.EXPECT().Update(gomock.Any(), user).Return(errors.ErrNotFound)
in := new(bytes.Buffer)
json.NewEncoder(in).Encode(userInput)
w := httptest.NewRecorder()
r := httptest.NewRequest("PATCH", "/api/user", in)
r = r.WithContext(
request.WithUser(r.Context(), user),
)
HandleUpdate(users)(w, r)
if got, want := w.Code, 500; want != got {
t.Errorf("Want response code %d, got %d", want, got)
}
got, want := new(errors.Error), errors.ErrNotFound
json.NewDecoder(w.Body).Decode(got)
if diff := cmp.Diff(got, want); len(diff) != 0 {
t.Errorf(diff)
}
}
| true |
0936c25c5c9c421ec9f02881669658b41ef7441f
|
Go
|
fengyfei/nuts
|
/examples/udp/server/server.go
|
UTF-8
| 2,091 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
/*
* MIT License
*
* Copyright (c) 2017 SmartestEE Co., Ltd..
*
* 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.
*/
/*
* Revision History:
* Initial: 2017/08/13 Feng Yifei
*/
package main
import (
"fmt"
"github.com/fengyfei/nuts/udp/packet"
"github.com/fengyfei/nuts/udp/server"
)
var (
udpServer *server.Server
)
func main() {
newServer()
close := make(chan struct{})
select {
case <-close:
return
}
}
func newServer() {
var err error
conf := server.Conf{
Address: "",
Port: "9527",
PacketSize: 32,
CacheCount: 12,
}
udpServer, err = server.NewServer(&conf, &handler{})
if err != nil {
panic(err)
}
}
type handler struct {
}
func (h *handler) OnPacket(p *packet.Packet) error {
fmt.Println(string(p.Payload), " from ", p.Remote)
resp := make([]byte, p.Size)
copy(resp, p.Payload[:p.Size])
udpServer.Send(resp, p.Remote)
return nil
}
func (h *handler) OnError(err error) error {
fmt.Println(err)
return nil
}
func (h *handler) OnClose() error {
fmt.Println("OnClose triggered")
return nil
}
| true |
e20f0dda8dddd3f7138c21158d5a0daef071302e
|
Go
|
Odzen/GoLang
|
/Learning/functions/basics/basics.go
|
UTF-8
| 356 | 3.859375 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
)
func main() {
for i := 0; i < 5; i++ {
sayMessage("Hello go", i)
}
}
func sayMessage(msg string, idx int) {
fmt.Println(msg)
fmt.Println("The value of the message is", idx)
}
/* We can add the type at the end to show that all the arguments are of the same type
func sayMessage(msg1 , msg2, msg3 string) {
...
}
*/
| true |
159b2e0e50e7a057732241c39f968e9f8f65bf30
|
Go
|
ao-concepts/websockets
|
/connection_test.go
|
UTF-8
| 1,318 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package websockets_test
import (
"context"
"github.com/ao-concepts/websockets"
"github.com/ao-concepts/websockets/mock"
"github.com/stretchr/testify/assert"
"testing"
)
func TestNewConnection(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
socket := websockets.New(mock.NewServiceContainer())
assert.NotNil(t, websockets.NewConnection(socket, nil, ctx, cancel))
}
func TestConnection_Set(t *testing.T) {
conn := mock.WsConnection(nil)
conn.Set("test-key", "test-value")
assert.Equal(t, "test-value", conn.Get("test-key"))
assert.Nil(t, conn.Get("nil-key"))
}
func TestConnection_Get(t *testing.T) {
conn := mock.WsConnection(nil)
assert.Nil(t, conn.Get("test-key"))
conn.Set("test-key", "test-value")
assert.Equal(t, "test-value", conn.Get("test-key"))
}
func TestConnection_Publish(t *testing.T) {
conn := mock.WsConnection(nil)
assert.NotPanics(t, func() {
conn.Publish(&websockets.Message{
Event: "test",
Payload: websockets.Payload{
"value": "test-data",
},
}, nil)
})
}
func TestConnection_Locals(t *testing.T) {
wsConn := websockets.NewWebsocketConnMock()
wsConn.LocalData["test-key"] = "test-value"
conn := mock.WsConnection(wsConn)
assert.Equal(t, "test-value", conn.Locals("test-key"))
assert.Nil(t, conn.Locals("not-available"))
}
| true |
a004c00d416d53a5f8f8302d43ffc0a634e04d07
|
Go
|
lybobob1/CatTails
|
/cmd/c2/server.go
|
UTF-8
| 5,195 | 2.9375 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"os"
"strconv"
"strings"
"github.com/google/gopacket"
"github.com/oneNutW0nder/CatTails/cattails"
"golang.org/x/sys/unix"
)
// Global to store staged command
var stagedCmd string
// Glabal to store target info
var targetIP string
var targetcommand string
// Host defines values for a callback from a bot
type Host struct {
Hostname string
Mac net.HardwareAddr
IP net.IP
RespIP net.IP
SrcPort int
DstPort int
}
// PwnBoard is used for updating pwnboard
type PwnBoard struct {
IPs string `json:"ip"`
Type string `json:"type"`
}
// sendCommand takes
func sendCommand(iface *net.Interface, myIP net.IP, dstMAC net.HardwareAddr, listen chan Host) {
// Forever loop to respond to bots
for {
// Block on reading from channel
bot := <-listen
// Check if there is a command to run
// Make a socket for sending
fd := cattails.NewSocket()
// Create packet
// fmt.Println("SRC MAC:", iface.HardwareAddr)
// fmt.Println("DST MAC:", dstMAC)
// fmt.Println("SRC IP:", myIP)
// fmt.Println("DST IP:", bot.RespIP)
if targetcommand != "" {
fmt.Println("[+] Sending target cmd", targetIP, targetcommand)
packet := cattails.CreatePacket(iface, myIP, bot.RespIP, bot.DstPort, bot.SrcPort, dstMAC, cattails.CreateTargetCommand(targetcommand, targetIP))
cattails.SendPacket(fd, iface, cattails.CreateAddrStruct(iface), packet)
} else {
packet := cattails.CreatePacket(iface, myIP, bot.RespIP, bot.DstPort, bot.SrcPort, dstMAC, cattails.CreateCommand(stagedCmd))
cattails.SendPacket(fd, iface, cattails.CreateAddrStruct(iface), packet)
}
// YEET
if stagedCmd != "" {
fmt.Println("[+] Sent reponse to:", bot.Hostname, "(", bot.IP, ")")
// Close the socket
unix.Close(fd)
updatepwnBoard(bot)
} else {
unix.Close(fd)
updatepwnBoard(bot)
}
}
}
// ProcessPacket TODO:
func serverProcessPacket(packet gopacket.Packet, listen chan Host) {
// Get data from packet
data := string(packet.ApplicationLayer().Payload())
payload := strings.Split(data, " ")
// fmt.Println("PACKET SRC IP", packet.NetworkLayer().NetworkFlow().Src().String())
// Parse the values from the data
mac, err := net.ParseMAC(payload[2])
if err != nil {
fmt.Println("[-] ERROR PARSING MAC:", err)
return
}
srcport, _ := strconv.Atoi(packet.TransportLayer().TransportFlow().Src().String())
dstport, _ := strconv.Atoi(packet.TransportLayer().TransportFlow().Dst().String())
// New Host struct for shipping info to sendCommand()
newHost := Host{
Hostname: payload[1],
Mac: mac,
IP: net.ParseIP(payload[3]),
RespIP: net.ParseIP(packet.NetworkLayer().NetworkFlow().Src().String()),
SrcPort: srcport,
DstPort: dstport,
}
// fmt.Println("[+] Recieved From:", newHost.Hostname, "(", newHost.IP, ")")
// Write host to channel
listen <- newHost
}
// Simple CLI to update the "stagedCmd" value
func cli() {
for {
// reader type
reader := bufio.NewReader(os.Stdin)
fmt.Print("CatTails> ")
stagedCmd, _ = reader.ReadString('\n')
// Trim the bullshit newlines
stagedCmd = strings.Trim(stagedCmd, "\n")
if stagedCmd == "TARGET" {
stagedCmd = ""
// Get the target IP
fmt.Print("Enter IP to target> ")
targetIP, _ = reader.ReadString('\n')
targetIP = strings.Trim(targetIP, "\n")
// Get TARGET command
fmt.Print("TARGET COMMAND> ")
targetcommand, _ = reader.ReadString('\n')
targetcommand = strings.Trim(targetcommand, "\n")
}
fmt.Println("[+] Staged CMD:", stagedCmd)
if targetcommand != "" {
fmt.Println("[+] Target CMD:", targetcommand, "on box", targetIP)
}
}
}
// Update pwnboard
func updatepwnBoard(bot Host) {
url := "http://pwnboard.win/generic"
// Create the struct
data := PwnBoard{
IPs: bot.IP.String(),
Type: "CatTails",
}
// Marshal the data
sendit, err := json.Marshal(data)
if err != nil {
fmt.Println("\n[-] ERROR SENDING POST:", err)
return
}
// Send the post to pwnboard
resp, err := http.Post(url, "application/json", bytes.NewBuffer(sendit))
if err != nil {
fmt.Println("[-] ERROR SENDING POST:", err)
return
}
defer resp.Body.Close()
}
func main() {
// Create a BPF vm for filtering
vm := cattails.CreateBPFVM(cattails.FilterRaw)
// Create a socket for reading
readfd := cattails.NewSocket()
defer unix.Close(readfd)
fmt.Println("[+] Created sockets")
// Make channel buffer by 5
listen := make(chan Host, 5)
// Iface and myip for the sendcommand func to use
iface, myIP := cattails.GetOutwardIface("192.168.1.10:80")
fmt.Println("[+] Interface:", iface.Name)
dstMAC, err := cattails.GetRouterMAC()
if err != nil {
log.Fatal(err)
}
fmt.Println("[+] DST MAC:", dstMAC.String())
// Spawn routine to listen for responses
fmt.Println("[+] Starting go routine...")
go sendCommand(iface, myIP, dstMAC, listen)
// Start CLI
go cli()
// This needs to be on main thread
for {
// packet := cattails.ServerReadPacket(readfd, vm)
packet := cattails.ServerReadPacket(readfd, vm)
// Yeet over to processing function
if packet != nil {
go serverProcessPacket(packet, listen)
}
}
}
| true |
24e4abc8cca9a49fa25d10a0e4215db34d815776
|
Go
|
squ1dd13/scm
|
/value.go
|
UTF-8
| 2,793 | 3.171875 | 3 |
[] |
no_license
|
[] |
no_license
|
package scm
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"strings"
)
type ElementType byte
const (
ElementTypeInt ElementType = iota
ElementTypeFloat ElementType = iota
ElementTypeString8 ElementType = iota
ElementTypeString16 ElementType = iota
)
type ArrayAccess struct {
Element ElementType
FirstVariableOffset uint16
IndexVariableOffset uint16
InfoMask byte
}
type Value struct {
Type DataType
Integer *int64
Float *float32
String *string
Array *ArrayAccess
}
func intFromBytes(bites []byte) int64 {
reader := bytes.NewReader(bites)
switch len(bites) {
case 1:
{
var value int8
binary.Read(reader, binary.LittleEndian, &value)
return int64(value)
}
case 2:
{
var value int16
binary.Read(reader, binary.LittleEndian, &value)
return int64(value)
}
case 4:
{
var value int32
binary.Read(reader, binary.LittleEndian, &value)
return int64(value)
}
}
panic(errors.New("invalid count"))
}
func ReadValue(reader *bytes.Reader) Value {
typeByte, _ := reader.ReadByte()
dataType := ConcreteType(typeByte).Lift()
length := dataType.Concrete.ValueLength()
if dataType.IsConcrete(ConcreteVariableString) {
lengthByte, _ := reader.ReadByte()
length = int(lengthByte)
}
buffer := make([]byte, length)
reader.Read(buffer)
bufferReader := bytes.NewBuffer(buffer)
if dataType.IsAbstract(AbstractInteger) || dataType.IsVariable() {
fromBytes := intFromBytes(buffer)
return Value{Type: dataType, Integer: &fromBytes}
}
if dataType.IsAbstract(AbstractFloat) {
var floating float32
err := binary.Read(bufferReader, binary.LittleEndian, &floating)
if err != nil {
panic(err)
}
return Value{Type: dataType, Float: &floating}
}
if dataType.IsAbstract(AbstractString) {
str := string(buffer)
if nullIndex := strings.IndexByte(str, 0); -1 < nullIndex {
str = str[0:nullIndex]
}
return Value{Type: dataType, String: &str}
}
if dataType.IsArrayElement() {
var arrayAccess ArrayAccess
err := binary.Read(bufferReader, binary.LittleEndian, &arrayAccess)
if err != nil {
panic(err)
}
return Value{Type: dataType, Array: &arrayAccess}
}
return Value{}
}
func (value Value) CodeString() string {
if value.Array != nil {
return fmt.Sprintf("0x%x[*0x%x]", value.Array.FirstVariableOffset, value.Array.IndexVariableOffset)
}
if value.Float != nil {
return fmt.Sprint(*value.Float)
}
if value.Integer != nil {
prefix := ""
if value.Type.IsLocal() {
prefix = "local_"
} else if value.Type.IsGlobal() {
prefix = "global_"
}
return prefix + fmt.Sprint(*value.Integer)
}
if value.String != nil {
return fmt.Sprintf("\"%s\"", *value.String)
}
panic(errors.New("unable to produce code string"))
}
| true |
80a83084a729bc227bc9b1fa42cd30e6e60ba81d
|
Go
|
pombredanne/salsaflow
|
/version/version.go
|
UTF-8
| 3,373 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package version
import (
// Stdlib
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strconv"
// Internal
"github.com/tchap/git-trunk/git"
)
const (
PackageFileName = "package.json"
GroupMatcherString = "([0-9]+)[.]([0-9]+)[.]([0-9]+)"
MatcherString = "[0-9]+[.][0-9]+[.][0-9]+"
)
type packageFile struct {
Version string
}
type Version struct {
Major uint
Minor uint
Patch uint
}
func ReadFromBranch(branch string) (ver *Version, stderr *bytes.Buffer, err error) {
content, stderr, err := git.ShowByBranch(branch, PackageFileName)
if err != nil {
return
}
var pkg packageFile
err = json.Unmarshal(content.Bytes(), &pkg)
if err != nil {
return
}
if pkg.Version == "" {
err = fmt.Errorf("version key not found in %v", PackageFileName)
return
}
ver, err = parseVersion(pkg.Version)
return
}
func (ver *Version) Zero() bool {
return ver.Major == 0 && ver.Minor == 0 && ver.Patch == 0
}
func (ver *Version) IncrementPatch() *Version {
return &Version{ver.Major, ver.Minor, ver.Patch + 1}
}
func (ver *Version) Set(versionString string) error {
newVer, err := parseVersion(versionString)
if err != nil {
return err
}
ver.Major = newVer.Major
ver.Minor = newVer.Minor
ver.Patch = newVer.Patch
return nil
}
func (ver *Version) String() string {
return fmt.Sprintf("%v.%v.%v", ver.Major, ver.Minor, ver.Patch)
}
func (ver *Version) ReleaseTagString() string {
return "v" + ver.String()
}
func (ver *Version) CommitToBranch(branch string) (stderr *bytes.Buffer, err error) {
// Checkout the branch.
stderr, err = git.Checkout(branch)
if err != nil {
return
}
// Get the absolute path of package.json
root, stderr, err := git.RepositoryRootAbsolutePath()
if err != nil {
return
}
path := filepath.Join(root, PackageFileName)
// Read package.json
file, err := os.OpenFile(path, os.O_RDWR, 0)
if err != nil {
return
}
defer file.Close()
content, err := ioutil.ReadAll(file)
if err != nil {
return
}
// Parse and replace stuff in package.json
pattern := regexp.MustCompile(fmt.Sprintf("\"version\": \"%v\"", MatcherString))
newContent := pattern.ReplaceAllLiteral(content,
[]byte(fmt.Sprintf("\"version\": \"%v\"", ver)))
if bytes.Equal(content, newContent) {
err = fmt.Errorf("%v: failed to replace version string", PackageFileName)
return
}
// Write package.json
_, err = file.Seek(0, os.SEEK_SET)
if err != nil {
return
}
err = file.Truncate(0)
if err != nil {
return
}
_, err = io.Copy(file, bytes.NewReader(newContent))
if err != nil {
return
}
// Commit package.json
_, stderr, err = git.Git("add", path)
if err != nil {
return
}
// XXX: Somehow unstage package.json?
_, stderr, err = git.Git("commit", "-m", fmt.Sprintf("Bump version to %v", ver))
return
}
func parseVersion(versionString string) (ver *Version, err error) {
pattern := regexp.MustCompile("^" + GroupMatcherString + "$")
parts := pattern.FindStringSubmatch(versionString)
if len(parts) != 4 {
return nil, fmt.Errorf("invalid version string: %v", versionString)
}
// regexp passed, we know that we are not going to fail here.
major, _ := strconv.ParseUint(parts[1], 10, 32)
minor, _ := strconv.ParseUint(parts[2], 10, 32)
patch, _ := strconv.ParseUint(parts[3], 10, 32)
return &Version{uint(major), uint(minor), uint(patch)}, nil
}
| true |
6fe0d1a6af113a9a0fb783e9b67b1b8c3b5c59a5
|
Go
|
ZBMO/algorithms
|
/count/count.go
|
UTF-8
| 530 | 3.78125 | 4 |
[] |
no_license
|
[] |
no_license
|
package count
import (
"fmt"
"time"
)
func Count(array []int) []int {
start := time.Now()
count(array)
elapsed := time.Since(start)
fmt.Println("Count sort elapsed time: ", elapsed)
return array
}
func count(array []int) {
max := getMax(array)
c := make([]int, max+1)
for _, i := range array {
c[i]++
}
i, j := 0, 0
for i <= max {
if c[i] > 0 {
array[j] = i
j++
c[i]--
} else {
i++
}
}
}
func getMax(array []int) int {
x := 0
for _, n := range array {
if n > x {x = n}
}
return x
}
| true |
c551a50eba459670bf879dca175095e5996753fe
|
Go
|
BOXFoundation/boxd
|
/storage/memdb/storage.go
|
UTF-8
| 4,877 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
// Copyright (c) 2018 ContentBox Authors.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package memdb
import (
"bytes"
"context"
"fmt"
"sync"
"time"
storage "github.com/BOXFoundation/boxd/storage"
)
type memorydb struct {
sm sync.RWMutex
writeLock chan struct{}
db map[string][]byte
enableBatch bool
batch storage.Batch
}
var _ storage.Storage = (*memorydb)(nil)
// Create or Get the table associated with the name
func (db *memorydb) Table(name string) (storage.Table, error) {
return &mtable{
memorydb: db,
prefix: fmt.Sprintf("%s.", name),
}, nil
}
// Drop the table associated with the name
func (db *memorydb) DropTable(name string) error {
db.writeLock <- struct{}{}
defer func() {
<-db.writeLock
}()
db.sm.Lock()
defer db.sm.Unlock()
var keys [][]byte
for key := range db.db {
keys = append(keys, []byte(key))
}
var prefix = fmt.Sprintf("%s.", name)
for _, key := range keys {
if bytes.HasPrefix(key, []byte(prefix)) {
delete(db.db, string(key))
}
}
return nil
}
func (db *memorydb) EnableBatch() {
db.enableBatch = true
db.batch = db.NewBatch()
}
// DisableBatch disable batch write.
func (db *memorydb) DisableBatch() {
db.sm.Lock()
defer db.sm.Unlock()
db.enableBatch = false
db.batch = nil
}
// IsInBatch indicates whether db is in batch
func (db *memorydb) IsInBatch() bool {
db.sm.Lock()
defer db.sm.Unlock()
return db.enableBatch
}
// create a new write batch
func (db *memorydb) NewBatch() storage.Batch {
return &mbatch{
memorydb: db,
}
}
func (db *memorydb) NewTransaction() (storage.Transaction, error) {
timer := time.NewTimer(time.Millisecond * 100)
select {
case <-timer.C:
return nil, storage.ErrTransactionExists
case db.writeLock <- struct{}{}:
}
return &mtx{
db: db,
closed: false,
batch: &mbatch{memorydb: db},
writeLock: db.writeLock,
}, nil
}
func (db *memorydb) Close() error {
db.writeLock <- struct{}{}
defer func() {
<-db.writeLock
}()
db.sm.Lock()
defer db.sm.Unlock()
db.db = make(map[string][]byte)
return nil
}
// put the value to entry associate with the key
func (db *memorydb) Put(key, value []byte) error {
if db.enableBatch {
db.batch.Put(key, value)
} else {
db.writeLock <- struct{}{}
defer func() {
<-db.writeLock
}()
db.sm.Lock()
defer db.sm.Unlock()
db.db[string(key)] = value
}
return nil
}
// delete the entry associate with the key in the Storage
func (db *memorydb) Del(key []byte) error {
if db.enableBatch {
db.batch.Del(key)
} else {
db.writeLock <- struct{}{}
defer func() {
<-db.writeLock
}()
db.sm.Lock()
defer db.sm.Unlock()
delete(db.db, string(key))
}
return nil
}
// Flush atomic writes all enqueued put/delete
func (db *memorydb) Flush() error {
var err error
if db.enableBatch {
err = db.batch.Write()
} else {
err = storage.ErrOnlySupportBatchOpt
}
return err
}
// return value associate with the key in the Storage
func (db *memorydb) Get(key []byte) ([]byte, error) {
db.sm.RLock()
defer db.sm.RUnlock()
if value, ok := db.db[string(key)]; ok {
return value, nil
}
return nil, nil
}
// return values associate with the keys in the Storage
func (db *memorydb) MultiGet(key ...[]byte) ([][]byte, error) {
db.sm.RLock()
defer db.sm.RUnlock()
values := [][]byte{}
for _, k := range key {
if value, ok := db.db[string(k)]; ok {
values = append(values, value)
} else {
return nil, nil
}
}
return values, nil
}
// check if the entry associate with key exists
func (db *memorydb) Has(key []byte) (bool, error) {
db.sm.RLock()
defer db.sm.RUnlock()
_, ok := db.db[string(key)]
return ok, nil
}
// return a set of keys in the Storage
func (db *memorydb) Keys() [][]byte {
db.sm.RLock()
defer db.sm.RUnlock()
var keys [][]byte
for key := range db.db {
keys = append(keys, []byte(key))
}
return keys
}
func (db *memorydb) KeysWithPrefix(prefix []byte) [][]byte {
db.sm.RLock()
defer db.sm.RUnlock()
var keys [][]byte
for key := range db.db {
k := []byte(key)
if bytes.HasPrefix(k, prefix) {
keys = append(keys, k)
}
}
return keys
}
// return a chan to iter all keys
func (db *memorydb) IterKeys(ctx context.Context) <-chan []byte {
keys := db.Keys()
out := make(chan []byte)
go func() {
defer close(out)
for _, k := range keys {
select {
case <-ctx.Done():
return
case out <- k:
}
}
}()
return out
}
// return a set of keys with specified prefix in the Storage
func (db *memorydb) IterKeysWithPrefix(ctx context.Context, prefix []byte) <-chan []byte {
keys := db.KeysWithPrefix(prefix)
out := make(chan []byte)
go func() {
defer close(out)
for _, k := range keys {
select {
case out <- k:
case <-ctx.Done():
return
}
}
}()
return out
}
| true |
e08fe3f98aaadaf664ac3aaf0668c72757f00c7a
|
Go
|
LCY2013/learing-go
|
/src/module1/ch17/share_mem/share_mem_test.go
|
UTF-8
| 834 | 3.015625 | 3 |
[] |
no_license
|
[] |
no_license
|
package share_mem
import (
"sync"
"testing"
"time"
)
//协程不安全
func TestShareMemory(t *testing.T) {
counter := 0
for i := 0; i < 5000; i++ {
go func() {
counter++
}()
}
time.Sleep(time.Millisecond * 500)
t.Log("counter = ", counter)
}
//协程安全
func TestShareMemorySafe(t *testing.T) {
var mut sync.Mutex
counter := 0
for i := 0; i < 5000; i++ {
go func() {
defer func() {
mut.Unlock()
}()
mut.Lock()
counter++
}()
}
time.Sleep(time.Millisecond * 500)
t.Log("counter = ", counter)
}
func TestShareMemoryWaitGroup(t *testing.T) {
var mut sync.Mutex
var wg sync.WaitGroup
counter := 0
for i := 0; i < 5000; i++ {
wg.Add(1)
go func() {
defer func() {
mut.Unlock()
wg.Done()
}()
mut.Lock()
counter++
}()
}
wg.Wait()
t.Log("counter = ", counter)
}
| true |
0f45ed6152161b58348990dfce87e9d19e6f31c9
|
Go
|
liuqitoday/go-file-backup
|
/service/upload_service.go
|
UTF-8
| 919 | 2.515625 | 3 |
[] |
no_license
|
[] |
no_license
|
package service
import (
"github.com/cheggaaa/pb/v3"
"github.com/studio-b12/gowebdav"
"go-file-buckup/config"
"io/ioutil"
"sync"
)
func UploadAllFiles(allFilePaths *[]string) {
if len(*allFilePaths) <= 0 {
return
}
// init webdav client
root := config.WebdavUrl
user := config.WebdavUsername
password := config.WebdavPassword
client := gowebdav.NewClient(root, user, password)
// upload files
group := sync.WaitGroup{}
group.Add(len(*allFilePaths))
processBar := pb.StartNew(len(*allFilePaths)).SetWidth(80)
for _, filePath := range *allFilePaths {
filePath := filePath
go func() {
uploadFile(filePath, client)
group.Done()
processBar.Increment()
}()
}
group.Wait()
processBar.Finish()
}
func uploadFile(filePath string, client *gowebdav.Client) error {
bytes, _ := ioutil.ReadFile(filePath)
err := client.Write(config.WebdavParentFilePath+filePath, bytes, 0644)
return err
}
| true |
026c19ec34af990eb65c418f7b5e4f9210c7c591
|
Go
|
bakku/minimalisp
|
/collection.go
|
UTF-8
| 4,302 | 3.25 | 3 |
[] |
no_license
|
[] |
no_license
|
package minimalisp
// First returns the first element of a list.
type First struct{}
// Arity returns 1.
func (f *First) Arity() int {
return 1
}
// Call implements the extraction of the first element.
func (f *First) Call(line int, i *Interpreter, arguments []interface{}) (interface{}, error) {
list, ok := arguments[0].(List)
if !ok {
return nil, &executionError{line, "'first' is only defined for lists"}
}
if list.Len() == 0 {
return nil, nil
}
return list.First(), nil
}
func (f *First) String() string {
return "<first>"
}
// Rest returns all except the first element of a list.
type Rest struct{}
// Arity returns 1.
func (f *Rest) Arity() int {
return 1
}
// Call implements returning all except the first element of a list.
func (f *Rest) Call(line int, i *Interpreter, arguments []interface{}) (interface{}, error) {
list, ok := arguments[0].(List)
if !ok {
return nil, &executionError{line, "'rest' is only defined for lists"}
}
if list.Len() == 0 {
return nil, nil
}
return list.Rest(), nil
}
func (f *Rest) String() string {
return "<rest>"
}
// Add adds an element to a list and returns a new list.
type Add struct{}
// Arity returns 2.
func (f *Add) Arity() int {
return 2
}
// Call implements the addition of an element to a list.
func (f *Add) Call(line int, i *Interpreter, arguments []interface{}) (interface{}, error) {
list, ok := arguments[0].(List)
if !ok {
return nil, &executionError{line, "'len' is only defined for lists"}
}
return list.Add(arguments[1]), nil
}
func (f *Add) String() string {
return "<add>"
}
// Len returns the amount of elements in a list.
type Len struct{}
// Arity returns 1.
func (f *Len) Arity() int {
return 1
}
// Call implements the counting of the elements in a list.
func (f *Len) Call(line int, i *Interpreter, arguments []interface{}) (interface{}, error) {
list, ok := arguments[0].(List)
if !ok {
return nil, &executionError{line, "'len' is only defined for lists"}
}
return list.Len(), nil
}
func (f *Len) String() string {
return "<len>"
}
// Map applies a function to each element of a list.
type Map struct{}
// Arity returns 2.
func (f *Map) Arity() int {
return 2
}
// Call implements map for a list.
func (f *Map) Call(line int, i *Interpreter, arguments []interface{}) (interface{}, error) {
fun, ok := arguments[0].(Function)
if !ok {
return nil, &executionError{line, "<map> expects a function as first parameter"}
}
if fun.Arity() != 1 {
return nil, &executionError{line, "<map> expects a function which accepts one argument"}
}
list, ok := arguments[1].(List)
if !ok {
return nil, &executionError{line, "<map> expects a list as second parameter"}
}
var mappedElements []interface{}
restOfList := list
for restOfList.Len() > 0 {
var args []interface{}
args = append(args, restOfList.First())
newEl, err := fun.Call(line, i, args)
if err != nil {
return nil, err
}
mappedElements = append(mappedElements, newEl)
restOfList = restOfList.Rest()
}
return NewArrayList(mappedElements), nil
}
func (f *Map) String() string {
return "<map>"
}
// Filter returns a new list with only the elements for which the given function returned true.
type Filter struct{}
// Arity returns 2.
func (f *Filter) Arity() int {
return 2
}
// Call implements filter for a list.
func (f *Filter) Call(line int, i *Interpreter, arguments []interface{}) (interface{}, error) {
fun, ok := arguments[0].(Function)
if !ok {
return nil, &executionError{line, "<filter> expects a function as first parameter"}
}
if fun.Arity() != 1 {
return nil, &executionError{line, "<filter> expects a function which accepts one argument"}
}
list, ok := arguments[1].(List)
if !ok {
return nil, &executionError{line, "<filter> expects a list as second parameter"}
}
var filteredElements []interface{}
restOfList := list
for restOfList.Len() > 0 {
var args []interface{}
args = append(args, restOfList.First())
response, err := fun.Call(line, i, args)
if err != nil {
return nil, err
}
if isTruthy(response) {
filteredElements = append(filteredElements, restOfList.First())
}
restOfList = restOfList.Rest()
}
return NewArrayList(filteredElements), nil
}
func (f *Filter) String() string {
return "<filter>"
}
| true |
1d98e08afa91a8d99db11a2720ded6cbf7753ff8
|
Go
|
jstrachan/jx-gitops
|
/pkg/kyamls/helpers.go
|
UTF-8
| 2,062 | 2.859375 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package kyamls
import (
"strings"
"github.com/jenkins-x/jx-logging/pkg/log"
"sigs.k8s.io/kustomize/kyaml/yaml"
)
var quotes = []string{"'", "\""}
// GetKind finds the Kind of the node at the given path
func GetKind(node *yaml.RNode, path string) string {
return GetStringField(node, path, "kind")
}
// GetAPIVersion finds the API Version of the node at the given path
func GetAPIVersion(node *yaml.RNode, path string) string {
return GetStringField(node, path, "apiVersion")
}
// GetName returns the name from the metadata
func GetName(node *yaml.RNode, path string) string {
return GetStringField(node, path, "metadata", "name")
}
// GetNamespace returns the namespace from the metadata
func GetNamespace(node *yaml.RNode, path string) string {
return GetStringField(node, path, "metadata", "namespace")
}
/// GetStringField returns the given field from the node or returns a blank string if the field cannot be found
func GetStringField(node *yaml.RNode, path string, fields ...string) string {
answer := ""
valueNode, err := node.Pipe(yaml.Lookup(fields...))
if err != nil {
log.Logger().Warnf("failed to read field %s for path %s", JSONPath(fields...), path)
}
if valueNode != nil {
var err error
answer, err = valueNode.String()
if err != nil {
log.Logger().Warnf("failed to get string value of field %s for path %s", JSONPath(fields...), path)
}
}
return TrimSpaceAndQuotes(answer)
}
// TrimSpaceAndQuotes trims any whitespace and quotes around a value
func TrimSpaceAndQuotes(answer string) string {
text := strings.TrimSpace(answer)
for _, q := range quotes {
if strings.HasPrefix(text, q) && strings.HasSuffix(text, q) {
return strings.TrimPrefix(strings.TrimSuffix(text, q), q)
}
}
return text
}
// IsClusterKind returns true if the kind is a cluster kind
func IsClusterKind(kind string) bool {
return kind == "" || kind == "Namespace" || strings.HasPrefix(kind, "Cluster")
}
// JSONPath returns the fields separated by dots
func JSONPath(fields ...string) string {
return strings.Join(fields, ".")
}
| true |
8cdc4fb07c1623aa62022eda1114c4888f93ef7d
|
Go
|
zhaoxin-BF/Ucloud_Work
|
/normal_gowork/12_22_study_goroutine/04_more_db_goroutine.go
|
UTF-8
| 2,909 | 2.9375 | 3 |
[] |
no_license
|
[] |
no_license
|
/*
1、根据地址的需要,无限制创建协程的个数
2、主协程打印汇总的数据
*/
package main
import (
"fmt"
"sync"
"gopkg.in/mgo.v2"
)
type Person struct {
Name string
Age string
}
func main() {
var wg sync.WaitGroup
wg.Add(50)
ch := make(chan Person, 1000000) //总文档数预测
ipt := make([]string, 50)
ipt[0] = "172.18.183.132:27017"
ipt[1] = "172.18.183.132:27020"
ipt[2] = "172.18.183.132:27017"
ipt[3] = "172.18.183.132:27020"
ipt[4] = "172.18.183.132:27017"
ipt[5] = "172.18.183.132:27020"
ipt[6] = "172.18.183.132:27017"
ipt[7] = "172.18.183.132:27020"
ipt[8] = "172.18.183.132:27017"
ipt[9] = "172.18.183.132:27020"
ipt[10] = "172.18.183.132:27017"
ipt[11] = "172.18.183.132:27020"
ipt[12] = "172.18.183.132:27017"
ipt[13] = "172.18.183.132:27020"
ipt[14] = "172.18.183.132:27017"
ipt[15] = "172.18.183.132:27020"
ipt[16] = "172.18.183.132:27017"
ipt[17] = "172.18.183.132:27020"
ipt[18] = "172.18.183.132:27017"
ipt[19] = "172.18.183.132:27020"
ipt[20] = "172.18.183.132:27017"
ipt[21] = "172.18.183.132:27020"
ipt[22] = "172.18.183.132:27017"
ipt[23] = "172.18.183.132:27020"
ipt[24] = "172.18.183.132:27017"
ipt[25] = "172.18.183.132:27020"
ipt[26] = "172.18.183.132:27017"
ipt[27] = "172.18.183.132:27020"
ipt[28] = "172.18.183.132:27017"
ipt[29] = "172.18.183.132:27020"
ipt[30] = "172.18.183.132:27017"
ipt[31] = "172.18.183.132:27020"
ipt[32] = "172.18.183.132:27017"
ipt[33] = "172.18.183.132:27020"
ipt[34] = "172.18.183.132:27017"
ipt[35] = "172.18.183.132:27020"
ipt[36] = "172.18.183.132:27017"
ipt[37] = "172.18.183.132:27020"
ipt[38] = "172.18.183.132:27017"
ipt[39] = "172.18.183.132:27020"
ipt[40] = "172.18.183.132:27017"
ipt[41] = "172.18.183.132:27020"
ipt[42] = "172.18.183.132:27017"
ipt[43] = "172.18.183.132:27020"
ipt[44] = "172.18.183.132:27017"
ipt[45] = "172.18.183.132:27020"
ipt[46] = "172.18.183.132:27017"
ipt[47] = "172.18.183.132:27020"
ipt[48] = "172.18.183.132:27017"
ipt[49] = "172.18.183.132:27020"
for i := 0; i < len(ipt); i++ { //循环开辟协程
go func(ipstr string) {
fmt.Println("一个协程创建完毕")
// str := "172.18.183.132:27017"
session, err := mgo.Dial(ipstr)
if err != nil {
panic(err)
}
defer session.Clone()
session.SetMode(mgo.Monotonic, true)
c := session.DB("test").C("student")
stus := make([]Person, 1000) //大于文档数
err = c.Find(nil).All(&stus)
fmt.Println("一共查到数据", len(stus))
for i := 0; i < len(stus); i++ {
ch <- stus[i]
}
wg.Done()
}(ipt[i])
}
wg.Wait() //等待子协程运行完毕后退出主协程
//i := 0
//n := len(ch)
//for ; i < n; i++ {
// per := <-ch
// fmt.Println(per.Name + ":" + per.Age)
//}
//
//fmt.Printf("一共%d条数据", i)
//fmt.Println("查找完毕!")
fmt.Println("主协程退出")
defer func() {
close(ch)
}()
}
| true |
dc32c78d36589e7a61c42fc6e0c2da29bb5a2d4e
|
Go
|
maximus-next/repo.nefrosovet.ru
|
/maximus-platform/profile/cmd/root.go
|
UTF-8
| 2,058 | 2.703125 | 3 |
[] |
no_license
|
[] |
no_license
|
package cmd
import (
"fmt"
"strings"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var (
CFGFile string
next func()
rootCmd = &cobra.Command{
Use: "profile",
Short: "profile service",
Long: `Just use it`,
PreRun: func(cmd *cobra.Command, args []string) {
},
Run: func(cmd *cobra.Command, args []string) {
if next != nil {
next()
}
},
}
)
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVarP(&CFGFile, "config", "c", "", "Config file path")
rootCmd.PersistentFlags().String("http.host", "", "API host")
rootCmd.PersistentFlags().Int("http.port", 8585, "API port")
rootCmd.PersistentFlags().String("db.host", "127.0.0.1", "Database host")
rootCmd.PersistentFlags().Int("db.port", 27017, "Database port")
rootCmd.PersistentFlags().String("db.database", "profile", "Database name")
rootCmd.PersistentFlags().String("db.login", "", "Database login")
rootCmd.PersistentFlags().String("db.password", "", "Database password")
rootCmd.PersistentFlags().String("logging.output", "STDOUT", "Logging output")
rootCmd.PersistentFlags().String("logging.level", "INFO", "Logging level")
rootCmd.PersistentFlags().String("logging.format", "TEXT", "Logging format: TEXT or JSON")
rootCmd.PersistentFlags().String("sentryDSN", "", "Sentry DSN")
// Bind command flags to config variables
viper.BindPFlags(rootCmd.PersistentFlags())
}
func initConfig() {
// Use config file from the flag if provided.
if CFGFile != "" {
viper.SetConfigFile(CFGFile)
if err := viper.ReadInConfig(); err != nil {
log.Fatal("Can't read config:", err)
}
}
viper.SetEnvPrefix("PROFILE")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AutomaticEnv()
}
func SetVersion(version string) {
rootCmd.Version = version
rootCmd.SetVersionTemplate(fmt.Sprintf("Version: %s\n", rootCmd.Version))
}
func Execute(nextFn func()) {
next = nextFn
if err := rootCmd.Execute(); err != nil {
log.WithError(err).
Fatal("Execute error")
}
}
| true |
a9ea99b23e4e69a35002d37b61ad684c6665476c
|
Go
|
jjGonBas31/Go-awesome
|
/src/awesomeProject/32-panic-recover/panic-recover.go
|
UTF-8
| 349 | 3.015625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
// panic se utiliza para detener errores en tiempo de ejecucion
func imprimir() {
fmt.Println("Hola Alex!")
//panic("Error")
//
//cadena := recover()
//}
defer func() {
someString := recover()
fmt.Println(someString)
} ()
panic("Error")
}
func main() {
imprimir()
fmt.Println("Hola main")
}
| true |
aab435f8ef069a45b1165c1da2f8ecec198895d9
|
Go
|
MrHide06/OddEvenPrime-go
|
/main.go
|
UTF-8
| 1,311 | 3.96875 | 4 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"fmt"
)
func main() {
array := [30]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
fmt.Printf("Bilangan awal : %+v, Jumlah = %d\n", array, len(array))
fmt.Println("-----------------------------------------------------------------------------------")
fmt.Printf("Bilangan ganjil : %+v, jumlah = %d\n", ganjil(array), len(ganjil(array)))
fmt.Println("-----------------------------------------------------------------------------------")
fmt.Printf("Bilangan genap : %+v, jumlah = %d\n", genap(array), len(genap(array)))
fmt.Println("-----------------------------------------------------------------------------------")
fmt.Printf("Bilangan Prima : %+v, jumlah = %d\n", prime(array), len(prime(array)))
}
func genap(array [30]int) []int {
var odd []int
for _, i := range array {
if i != 0 {
if i%2 == 0 {
odd = append(odd, i)
}
}
}
return odd
}
func ganjil(array [30]int) []int {
var even []int
for _, i := range array {
if i%2 != 0 {
even = append(even, i)
}
}
return even
}
func prime(array [30]int) []int {
var prima []int
for x := 1; x < len(array); x++ {
i := 0
for y := 1; y < len(array); y++ {
if x%y == 0 {
i++
}
}
if (i == 2) && (x != 1) {
prima = append(prima, x)
}
}
return prima
}
| true |
d6785b4e30760dae41dedb2075b35dcc8c18ea0e
|
Go
|
ramdunzo/schedular
|
/schedule.go
|
UTF-8
| 834 | 2.65625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"database/sql"
"encoding/json"
"fmt"
"net/http"
"github.com/gorilla/mux"
)
type scheduler struct {
TaskID int `json:"taskId"`
TimeStamp int64 `json:"timestamp"`
Flag bool `json:"flag"`
}
var db *sql.DB
func schedule(w http.ResponseWriter, r *http.Request) {
var q scheduler
_ = json.NewDecoder(r.Body).Decode(&q)
fmt.Println(q)
stmtIns, er := db.Prepare("insert into scheduler values(?,?,?)")
if er != nil {
panic(er.Error())
} else {
fmt.Println("entity add")
}
_, err := stmtIns.Exec(q.TaskID, q.TimeStamp, q.Flag)
if err != nil {
panic(err.Error())
}
}
func main() {
r := mux.NewRouter()
db, _ = sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/todo")
defer db.Close()
r.HandleFunc("/schedule/{id:[0-9]+}", schedule).Methods("GET")
http.ListenAndServe(":8000", r)
}
| true |
b32a3e216c08cefd978a8a272881de75378f6383
|
Go
|
mcspring/codex
|
/managers/create_manager.go
|
UTF-8
| 3,320 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
// Package managers provides AST managers for the codex package.
package managers
import (
"github.com/chuckpreslar/codex/nodes"
"github.com/chuckpreslar/codex/sql"
)
type CreateManager struct {
Tree *nodes.CreateStatementNode
adapter interface{} // The SQL adapter.
}
// AddColumn adds a UnexistingColumn from the nodes package to the AST for creation.
func (self *CreateManager) AddColumn(name interface{}, typ sql.Type) *CreateManager {
if _, ok := name.(string); ok {
name = nodes.UnqualifiedColumn(name)
}
self.Tree.UnexistingColumns = append(self.Tree.UnexistingColumns, nodes.UnexistingColumn(name, typ))
return self
}
// AddColumn adds a ConstraintNode from the nodes package to the AST to apply to a column.
func (self *CreateManager) AddConstraint(columns []interface{}, kind sql.Constraint, options ...interface{}) *CreateManager {
for index, column := range columns {
if _, ok := column.(string); ok {
columns[index] = nodes.UnqualifiedColumn(column)
}
}
var node interface{}
switch kind {
case sql.NotNull:
node = nodes.NotNull(columns, options...)
case sql.Unique:
node = nodes.Unique(columns, options...)
case sql.PrimaryKey:
node = nodes.PrimaryKey(columns, options...)
case sql.ForeignKey:
node = nodes.ForeignKey(columns, options...)
case sql.Check:
node = nodes.Check(columns, options...)
case sql.Default:
node = nodes.Default(columns, options...)
default:
node = nodes.Constraint(columns, options...)
}
self.Tree.Constraints = append(self.Tree.Constraints, node)
return self
}
func (self *CreateManager) AddUniqueConstraint(columns []interface{},
name ...interface{}) *CreateManager {
return self.AddConstraint(columns, sql.Unique, name...)
}
func (self *CreateManager) AddForiegnKeyConstraint(columns []interface{},
reference interface{}, name ...interface{}) *CreateManager {
return self.AddConstraint(columns, sql.ForeignKey, append([]interface{}{
reference,
}, name...)...)
}
func (self *CreateManager) AddDefaultContraint(columns []interface{},
value interface{}) *CreateManager {
return self.AddConstraint(columns, sql.Default, value)
}
func (self *CreateManager) AddNotNullConstraint(columns []interface{}) *CreateManager {
return self.AddConstraint(columns, sql.NotNull)
}
func (self *CreateManager) AddPrimaryKeyConstraint(columns []interface{},
name ...interface{}) *CreateManager {
return self.AddConstraint(columns, sql.PrimaryKey, name...)
}
// SetEngine sets the AST's Engine field, used for table creation.
func (self *CreateManager) SetEngine(engine interface{}) *CreateManager {
if _, ok := engine.(*nodes.EngineNode); !ok {
engine = nodes.Engine(engine)
}
self.Tree.Engine = engine.(*nodes.EngineNode)
return self
}
// Sets the SQL Adapter.
func (self *CreateManager) SetAdapter(adapter interface{}) *CreateManager {
self.adapter = adapter
return self
}
// ToSql calls a visitor's Accept method based on the manager's SQL adapter.
func (self *CreateManager) ToSql() (string, error) {
if nil == self.adapter {
self.adapter = "to_sql"
}
return VisitorFor(self.adapter).Accept(self.Tree)
}
// SelectManager factory method.
func Creation(relation *nodes.RelationNode) (statement *CreateManager) {
statement = new(CreateManager)
statement.Tree = nodes.CreateStatement(relation)
return
}
| true |
4d01b2af34dc8f314ed7527866e901d8e38ef6a1
|
Go
|
Covertness/ally
|
/pkg/coinbase/coinbase.go
|
UTF-8
| 609 | 2.84375 | 3 |
[] |
no_license
|
[] |
no_license
|
package coinbase
import (
"fmt"
"github.com/imroc/req"
)
var ins *CoinBase
// Init create the CoinBase connection
func Init() *CoinBase {
ins = New()
return ins
}
// GetInstance get the CoinBase instance
func GetInstance() *CoinBase {
return ins
}
// New create a new instance
func New() *CoinBase {
return &CoinBase{
Endpoint: "https://api.coinbase.com",
}
}
func (c *CoinBase) get(path string) (*req.Resp, error) {
url := fmt.Sprintf("%s%s",
c.Endpoint, path,
)
return req.Get(url)
}
// CoinBase instance connect to https://www.coinbase.com/
type CoinBase struct {
Endpoint string
}
| true |
b054b15148c7ac6948874d3911b0390fa547d316
|
Go
|
Esseh/Misc
|
/WebDev/WebDevProjectAttempt2/Step4/handleCookie.go
|
UTF-8
| 540 | 3.03125 | 3 |
[] |
no_license
|
[] |
no_license
|
/*
This file is responsible for determining what to do with a cookie.
*/
package main
import "net/http" //web server
func handleCookie(res http.ResponseWriter,req *http.Request) User {
cookie, err := req.Cookie("session-info") //Ensure that the cookie exists...
if err != nil {
cookie = makeDefaultCookie()
http.SetCookie(res,cookie)
}
if req.Method == "POST" { //If in POST
cookie.Value = updateCookie(cookie,req) //update the cookie
}
return outputUser(cookie.Value) //Return the constructed User.
}
| true |
ed2165baac3a52c77f828bcfbad51232d8f63978
|
Go
|
niltrix/gotutorial
|
/errGroup.go
|
UTF-8
| 955 | 3.390625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"context"
"errors"
"fmt"
"time"
"golang.org/x/sync/errgroup"
)
func counterWork5(ctx context.Context) error {
timer := time.NewTimer(time.Second * 5)
select {
case <-timer.C:
fmt.Println("5sec timer")
return nil
case <-ctx.Done():
fmt.Println("ctx.Done in 5sec timer")
return ctx.Err()
}
}
func counterWork2(ctx context.Context) error {
timer := time.NewTimer(time.Second * 2)
select {
case <-timer.C:
fmt.Println("2sec timer")
fmt.Println("Occur error 2sec timer")
return errors.New("error 2sec timer")
case <-ctx.Done():
fmt.Println("ctx.Done in 2sec timer ")
return ctx.Err()
}
}
func main() {
ctx, _ := context.WithCancel(context.Background())
errGrp, errCtx := errgroup.WithContext(ctx)
errGrp.Go(func() error { return counterWork5(errCtx) })
errGrp.Go(func() error { return counterWork2(errCtx) })
//cancel()
if err := errGrp.Wait(); err != nil {
fmt.Println(err.Error())
}
}
| true |
df0c3aa3cd256de5ea06c3d0f47e47db924ac12a
|
Go
|
moyuanhui/go-dev
|
/day2/example2/main.go
|
UTF-8
| 176 | 2.859375 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"os"
)
func main() {
goos := os.Getenv("GOOS")
fmt.Println("The operating is:",goos)
path := os.Getenv("PATH")
fmt.Println("Path: ",path)
}
| true |
2bd557686c430428b0faf2dfd8c02eff2da6004a
|
Go
|
geenasmith/Distributed-Go-Fish
|
/src/server/server.go
|
UTF-8
| 8,251 | 2.828125 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"net/rpc"
"os"
"sort"
"sync"
"time"
)
import . "../helpers"
import "../raft"
type Player struct {
ID int
Hand []Card
Pairs []Pairs
Opponents []Player
}
type GameServer struct {
Mu sync.Mutex
Ready bool
GameOver bool
Winner int // index of the winning player
Players []Player // holds ID, hand, pairs, and opponents
Deck []Card // hold the cards that are still in the deck
CurrentTurnPlayer int // what's the difference between this and currentTurn???
CurrentTurn int
PlayerCount int // number of players in the game
GameInitialized bool
ServerId int64
}
type GameStatusReply struct {
Complete bool
Turn int
CurrentPlayer int
Winner int
Scores []int
Players []Player
}
// RPC for clients (players) to join the game
func (gs *GameServer) JoinGame(args *JoinGameArgs, reply *JoinGameReply) error {
gs.Mu.Lock()
defer gs.Mu.Unlock()
// game can have no more than 7 players
if gs.PlayerCount == 7 {
reply.Success = false
return nil
}
reply.Success = true
// if game doesn't exist, start one
if !gs.GameInitialized {
gs.GameInitialized = true
}
reply.ID = gs.PlayerCount
// append player to game state
gs.Players = append(gs.Players, Player{ID: gs.PlayerCount})
gs.PlayerCount = len(gs.Players)
return nil
}
// Load card objects from a JSON file and populate the deck
func (gs *GameServer) loadCards() {
gs.Mu.Lock()
defer gs.Mu.Unlock()
fmt.Printf("SERVER: loading cards\n")
var values []Card
file, err := os.Open("standard52.json")
if err != nil {
log.Fatalf("Cant open card file\n")
}
dec := json.NewDecoder(file)
if err := dec.Decode(&values); err != nil {
if err != io.EOF {
fmt.Printf("%v\n", err)
}
}
_ = file.Close()
gs.Deck = values
}
// Assign each player 7 cards from the deck
func (gs *GameServer) dealCards() {
gs.Mu.Lock()
defer gs.Mu.Unlock()
Shuffle(gs.Deck)
for i := 0; i < gs.PlayerCount; i++ {
gs.Players[i].Hand = gs.Deck[0:7]
gs.Deck = gs.Deck[7:]
}
fmt.Println("SERVER: Dealing Cards")
}
// RPC for clients (players) to ask the status of the game
func (gs *GameServer) AskGameStatus(ask *GameStatusRequest, gameStatus *GameStatusReply) error {
gs.Mu.Lock()
defer gs.Mu.Unlock()
// information returned to the player includes:
// - if game is over
// - current player whose turn it is
// - the current turn
// - all players still in the game
// - all player's scores
// - winner of the game (if there is one)
gameStatus.Complete = gs.GameOver
gameStatus.CurrentPlayer = gs.CurrentTurnPlayer
gameStatus.Turn = gs.CurrentTurn
gameStatus.Players = gs.Players
var scores []int
for _, v := range gs.Players {
scores = append(scores, len(v.Pairs))
}
gameStatus.Scores = scores
if gs.GameOver {
gameStatus.Winner = gs.Winner
_ = os.Remove("server-id")
} else {
gameStatus.Winner = -1
}
return nil
}
// RPC for clients (players) to ask for specific cards from a specific player
func (gs *GameServer) AskForCards(ask *CardRequest, reply *CardRequestReply) error {
gs.Mu.Lock()
reply.GoFish = true
// Loop through target player's hand and find matching cards
var toRemove []int
var cardPool = gs.Players[ask.Target].Hand
for k, v := range cardPool {
if v.Value == ask.Value {
reply.GoFish = false
reply.Cards = append(reply.Cards, v)
toRemove = append(toRemove, k)
}
}
if reply.GoFish { // No card found
reply.Cards = append(reply.Cards, gs.goFish())
} else { // Target player has 1 or more matching cards
sort.Ints(toRemove)
for i, v := range toRemove {
gs.Players[ask.Target].Hand = append(gs.Players[ask.Target].Hand[:v-i], gs.Players[ask.Target].Hand[v+1-i:]...)
}
}
gs.Mu.Unlock()
gs.checkGameOver()
return nil
}
// RPC for clients (players) to end their turn by playing their pairs and updating the game state
func (gs *GameServer) EndTurn(ask *PlayPairRequest, reply *PlayPairReply) error {
gs.Mu.Lock()
defer gs.Mu.Unlock()
// Update the player's matching pairs
if ask.Pair != nil && len(ask.Pair) != 0 {
gs.Players[ask.Owner].Pairs = append(gs.Players[ask.Owner].Pairs, ask.Pair...)
}
// Update the player's hand
gs.Players[ask.Owner].Hand = ask.Hand
// Determine next player
gs.saveGameState()
gs.CurrentTurnPlayer++
if gs.CurrentTurnPlayer >= gs.PlayerCount {
gs.CurrentTurnPlayer = 0
}
ask.Pair = nil
return nil
}
// Go-fish action which draws 1 card
func (gs *GameServer) goFish() Card {
// Deck empty
if len(gs.Deck) == 0 {
return Card{Value: "-1"}
}
var fish = gs.Deck[0]
gs.Deck = gs.Deck[1:]
return fish
}
// Check if the game is finished, indicated by an empty deck and all players having an empty hand
func (gs *GameServer) checkGameOver() {
gs.Mu.Lock()
defer gs.Mu.Unlock()
var deckEmpty = false
var playerEmpty = true
if len(gs.Deck) == 0 {
deckEmpty = true
}
for _, v := range gs.Players {
if len(v.Hand) != 0 {
playerEmpty = false
break
}
}
gs.GameOver = playerEmpty && deckEmpty
// find the winner, indicated by the greatest number of pairs
gs.Winner = 0
for _, k := range gs.Players {
if len(gs.Players[gs.Winner].Pairs) < len(k.Pairs) {
gs.Winner = k.ID
}
}
}
func (gs *GameServer) server() {
rpc.Register(gs)
rpc.HandleHTTP()
sockname := GameServerSock()
os.Remove(sockname)
l, e := net.Listen("unix", sockname)
if e != nil {
log.Fatal("listen error:", e)
}
go http.Serve(l, nil)
}
// Create a GameServer
func MakeGameServer() *GameServer {
gs := GameServer{}
if _, err := os.Stat("server-id"); err == nil {
return gs.loadStartup()
} else {
return gs.createNewGs()
}
}
func (gs *GameServer) createNewGs() *GameServer {
gs.Mu.Lock()
gs.CurrentTurn = 0
gs.CurrentTurnPlayer = -1
gs.GameOver = false
gs.GameInitialized = false
gs.Ready = false
gs.ServerId = raft.Nrand()
fp, _ := os.Create("server-id")
_, _ = fp.WriteString(fmt.Sprintf("%d", gs.ServerId))
_ = fp.Close()
gs.server()
gs.Mu.Unlock()
time.Sleep(30 * time.Second)
fmt.Printf("\nSERVER: total %d players\n", gs.PlayerCount)
// not enough players or no one joined
if gs.PlayerCount < 2 {
fmt.Println("SERVER: Game error not enough players")
return gs
}
gs.loadCards()
gs.dealCards()
gs.CurrentTurnPlayer = 0
return gs
}
func main() {
gs := MakeGameServer()
fmt.Printf("%v", gs)
fmt.Printf("%v", gs.CurrentTurn)
for !gs.GameOver {
time.Sleep(3 * time.Second)
}
fmt.Printf("SERVER: Game Over\n")
fmt.Printf("SERVER: Player %d won with %d pairs\n", gs.Winner, len(gs.Players[gs.Winner].Pairs))
time.Sleep(1 * time.Second)
}
func (gs *GameServer) saveGameState() {
args := GameStateArgs{}
reply := GameStateReply{}
args.Key = string(gs.ServerId)
js, _ := json.Marshal(gs)
args.Payload = string(js)
ok := CallRB("RaftBroker.PutGameState", &args, &reply)
if !ok || !reply.Ok {
fmt.Printf("Put Game state failed\n")
}
}
func (gs *GameServer) getGameState() {
gs.Mu.Lock()
defer gs.Mu.Unlock()
args := GameStateArgs{}
reply := GameStateReply{}
args.Key = string(gs.ServerId)
ok := CallRB("RaftBroker.GetGameState", &args, &reply)
if !ok || !reply.Ok {
fmt.Printf("Get Game state failed\n")
}
gs.reconcileState(reply.Payload)
}
func (gs *GameServer) reconcileState(payload string) {
var gsSaved GameServer
err := json.Unmarshal([]byte(payload), &gsSaved)
if err != nil {
fmt.Printf("Unmarshall of game state failed")
}
if gsSaved.ServerId != gs.ServerId {
fmt.Printf("Wrong game state retreived")
} else {
gs.Winner = gsSaved.Winner
gs.Players = gsSaved.Players
gs.GameOver = gsSaved.GameOver
gs.CurrentTurnPlayer = gsSaved.CurrentTurnPlayer
gs.CurrentTurn = gsSaved.CurrentTurn
gs.Deck = gsSaved.Deck
gs.Ready = gsSaved.Ready
gs.GameInitialized = gsSaved.GameInitialized
}
}
func (gs *GameServer) loadStartup() *GameServer {
fp, err := os.Open("server-id")
if err != nil {
fmt.Printf("Could not open id file\n")
}
_, err = fmt.Fscanf(fp, "%d", &gs.ServerId)
if err != nil {
fmt.Printf("Failed to read id file")
}
gs.getGameState()
gs.server()
return gs
}
| true |
1af549467e27f7defebacdf584d7d4cc1b6d47f5
|
Go
|
cloudfoundry/bbs
|
/models/routes.go
|
UTF-8
| 1,251 | 3.0625 | 3 |
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
package models
import (
"bytes"
"encoding/json"
)
type Routes map[string]*json.RawMessage
func (r *Routes) protoRoutes() *ProtoRoutes {
pr := &ProtoRoutes{
Routes: map[string][]byte{},
}
for k, v := range *r {
pr.Routes[k] = *v
}
return pr
}
func (r *Routes) Marshal() ([]byte, error) {
return r.protoRoutes().Marshal()
}
func (r *Routes) MarshalTo(data []byte) (n int, err error) {
return r.protoRoutes().MarshalTo(data)
}
func (r *Routes) Unmarshal(data []byte) error {
pr := &ProtoRoutes{}
err := pr.Unmarshal(data)
if err != nil {
return err
}
if pr.Routes == nil {
return nil
}
routes := map[string]*json.RawMessage{}
for k, v := range pr.Routes {
raw := json.RawMessage(v)
routes[k] = &raw
}
*r = routes
return nil
}
func (r *Routes) Size() int {
if r == nil {
return 0
}
return r.protoRoutes().Size()
}
func (r *Routes) Equal(other Routes) bool {
for k, v := range *r {
if !bytes.Equal(*v, *other[k]) {
return false
}
}
return true
}
func (r Routes) Validate() error {
totalRoutesLength := 0
if r != nil {
for _, value := range r {
totalRoutesLength += len(*value)
if totalRoutesLength > maximumRouteLength {
return ErrInvalidField{"routes"}
}
}
}
return nil
}
| true |
8b0b5419d275e3b725608444f0e42a0b97091011
|
Go
|
TropicalPenguinn/BlockChain
|
/Goblock/blockchain/main.go
|
UTF-8
| 3,734 | 2.734375 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"bytes"
"crypto/sha256"
"strconv"
"time"
"math/big"
"encoding/gob"
"github.com/boltdb/bolt"
"log"
"math"
)
const targetBits=24
func IntToHex(n int64) []byte{
return []byte(strconv.FormatInt(n,16))
}
func (b *Block) Serialize() []byte {
var result bytes.Buffer
encoder := gob.NewEncoder(&result)
err := encoder.Encode(b)
return result.Bytes()
}
func DeserializeBlock(d []byte) *Block {
var block Block
decoder := gob.NewDecoder(bytes.NewReader(d))
err := decoder.Decode(&block)
return &block
}
type Block struct {
Timestamp int64
Data []byte
PrevBlockHash []byte
Hash []byte
Nonce int64
}
type Blockchain struct {
tip []byte
db *bolt.DB
}
type ProofOfWork struct {
block *Block
target *big.Int
}
type BlockchainIterator struct {
currentHash []byte
db *bolt.DB
}
func (bc *Blockchain) Iterator() *BlockchainIterator {
bci := &BlockchainIterator{bc.tip, bc.db}
return bci
}
func (i *BlockchainIterator) Next() *Block {
var block *Block
err := i.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(blocksBucket))
encodedBlock := b.Get(i.currentHash)
block = DeserializeBlock(encodedBlock)
return nil
})
i.currentHash = block.PrevBlockHash
return block
}
func NewProofOfWork(b *Block) *ProofOfWork {
target := big.NewInt(1)
target.Lsh(target, uint(256-targetBits))
pow := &ProofOfWork{b, target}
return pow
}
func (pow *ProofOfWork) prepareData(nonce int64) []byte {
data := bytes.Join(
[][]byte{
pow.block.PrevBlockHash,
pow.block.Data,
IntToHex(pow.block.Timestamp),
IntToHex(int64(targetBits)),
IntToHex(int64(nonce)),
},
[]byte{},
)
return data
}
func (pow *ProofOfWork) Run() (int64, []byte) {
var hashInt big.Int
var hash [32]byte
var nonce int64
nonce=0
fmt.Printf("Mining the block containing \"%s\"\n", pow.block.Data)
for nonce < math.MaxInt64 {
data := pow.prepareData(nonce)
hash = sha256.Sum256(data)
fmt.Printf("\r%x", hash)
hashInt.SetBytes(hash[:])
if hashInt.Cmp(pow.target) == -1 {
break
} else {
nonce++
}
}
fmt.Print("\n\n")
return nonce, hash[:]
}
func NewBlock(data string, prevBlockHash []byte) *Block {
block := &Block{time.Now().Unix(), []byte(data), prevBlockHash, []byte{}, 0}
pow := NewProofOfWork(block)
nonce, hash := pow.Run()
block.Hash = hash[:]
block.Nonce = nonce
return block
}
func (bc *Blockchain) AddBlock(data string) {
var lastHash []byte
err := bc.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(blocksBucket))
lastHash = b.Get([]byte("l"))
return nil
})
newBlock := NewBlock(data, lastHash)
err = bc.db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(blocksBucket))
err := b.Put(newBlock.Hash, newBlock.Serialize())
err = b.Put([]byte("l"), newBlock.Hash)
bc.tip = newBlock.Hash
return nil
})
}
func NewracoonBlock() *Block {
return NewBlock("Racoon coin", []byte{})
}
const (
blocksBucket="blocks"
dbFile="chain.db"
)
func NewBlockchain() *Blockchain {
var tip []byte
db, err := bolt.Open(dbFile, 0600, nil)
err = db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(blocksBucket))
if b == nil {
genesis := NewracoonBlock()
b, err := tx.CreateBucket([]byte(blocksBucket))
err = b.Put(genesis.Hash, genesis.Serialize())
err = b.Put([]byte("l"), genesis.Hash)
tip = genesis.Hash
} else {
tip = b.Get([]byte("l"))
}
return nil
})
bc := Blockchain{tip, db}
return &bc
}
| true |
226c7723b8b50ba1b8e66850d45e89b4e682e353
|
Go
|
xsh884826402/InvoiceVerification
|
/util.go
|
UTF-8
| 6,107 | 2.59375 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"bufio"
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"math/rand"
"mime/multipart"
"net/http"
"os"
"os/exec"
"strings"
"time"
)
func CreateRandomNumber() string {
return fmt.Sprintf("%015v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))
}
func CreateRandomDataExchangeId() string{
current_time := time.Now().Format("20060102150405")
ms :=time.Now().UnixNano()/1e6
ms_str :=fmt.Sprintf("%d", ms)
tail :=ms_str[len(ms_str)-3:]
fmt.Println("here", tail)
random_str := CreateRandomNumber()
return current_time+tail+random_str
}
func CreateRandomDataExchangeId_1() string{
current_time := time.Now().Format("20060102150405000")
random_str := CreateRandomNumber()
return current_time+random_str
}
func Base64Encode(input string) string{
return base64.StdEncoding.EncodeToString([]byte(input))
}
func Base64Decode(input string) (string, error){
data, err :=base64.StdEncoding.DecodeString(input)
if err != nil {
return "", err
}
return string(data),err
}
//func ConvertInvoiceTypeToFpdam( invoiceType string) string{
// //to do
//
//}
func ConvertPdfTojpg(pdfFile string, jpgFile string) string{
log.Print("ConvertPdfTojpg ",pdfFile,"\n", "ConvertPdfTojpg ",jpgFile)
command:= exec.Command("magick","convert","-density","300",pdfFile,jpgFile)
err := command.Run()
if err != nil{
log.Fatal(err)
}
return jpgFile
}
func CheckInputFileType(filename string) string{
if filename[len(filename)-4:]==".jpg"{
return filename
}
if filename[len(filename)-4:]==".png"{
return filename
}
if filename[len(filename)-4:]=="jpeg"{
return filename
}
if filename[len(filename)-4:]==".pdf"{
jpgfile :=filename[:len(filename)-4]+".jpg"
ConvertPdfTojpg(filename, jpgfile)
return jpgfile
}
return ""
}
func ConvertFileToInvoiceJson(filename string) SingleInvoiceCheckPostData{
InvoiceInfoJson := GetInvoiceInfoByBaiduai(filename)
//fmt.Println("Invoice Info Json\n", string(InvoiceInfoJson))
//
var invoiceInfoBaiduai InvociceInfoBaiduai
err :=json.Unmarshal(InvoiceInfoJson, &invoiceInfoBaiduai)
if err != nil{
log.Fatal(err)
}
singleInvoiceCheckPostData := SingleInvoiceCheckPostData{
}
singleInvoiceCheckPostData.Fpje = invoiceInfoBaiduai.Words_result.TotalAmount
singleInvoiceCheckPostData.Fpdm = invoiceInfoBaiduai.Words_result.InvoiceCode
st := invoiceInfoBaiduai.Words_result.InvoiceDate
st = strings.Replace(st, "年", "", -1)
st = strings.Replace(st,"月","",-1)
st = strings.Replace(st,"日","",-1)
//singleInvoiceCheckPostData.Kprq = st+"haha"
singleInvoiceCheckPostData.Kprq = st
singleInvoiceCheckPostData.Fphm = invoiceInfoBaiduai.Words_result.InvoiceNum
if invoiceInfoBaiduai.Words_result.InvoiceType=="电子普通发票" {
singleInvoiceCheckPostData.Fpzl = "10"
} else{
if invoiceInfoBaiduai.Words_result.InvoiceType=="专用发票"{
singleInvoiceCheckPostData.Fpzl = "01"
}
}
if singleInvoiceCheckPostData.Fpzl =="10"{
singleInvoiceCheckPostData.Jym = invoiceInfoBaiduai.Words_result.CheckCode[len(invoiceInfoBaiduai.Words_result.CheckCode)-6:]
}
return singleInvoiceCheckPostData
}
func PrepareJsonForHttpRequest(jsonData []byte) []byte{
jsonDataEncoded :=Base64Encode(string(jsonData))
dataExchangeId := CreateRandomDataExchangeId_1()
commonPostData := CommonPostData{
ZipCode: "0",
EncryptCode: "0",
DataExchangeId: dataExchangeId,
EntCode: "",
Content: jsonDataEncoded,
}
commonPostDataJson,_ :=json.Marshal(commonPostData)
return commonPostDataJson
}
func GetUrlFromFactory(RequestType string) string{
token:= GetTokenData()
//fmt.Println("debug 1", token,RequestType)
var Url string
switch RequestType{
case "MultiInvoiceCheck":
Url = "https://sandbox.ele-cloud.com/api/open-recipt/V1/MultilCheckInvoice"
v, ok := token["access_token"].(string)
if ok {
Url += "?" + "access_token=" + v
} else{
log.Println("access_token is not string")
}
case "MultiInvoiceResultQuery":
Url = "https://sandbox.ele-cloud.com/api/open-recipt/V1/BatchGetInvoice"
v, ok := token["access_token"].(string)
if ok {
Url += "?" + "access_token=" + v
} else{
log.Println("access_token is not string")
}
case "SingleInvoiceCheck":
Url = "https://sandbox.ele-cloud.com/api/open-recipt/V1/CheckInvoiceSingle"
v, ok := token["access_token"].(string)
if ok {
Url += "?" + "access_token=" + v
} else{
log.Println("access_token is not string")
}
default:
fmt.Println("default")
}
return Url
}
func SentHttpequestByPost(url string,commonPostDataJson [] byte) string{
fmt.Println("Json data", string(commonPostDataJson))
client := &http.Client{}
request,_ := http.NewRequest("POST", url, bytes.NewBuffer(commonPostDataJson))
request.Header.Set("Content-Type", "application/json")
resp, _ :=client.Do(request)
//fmt.Println("resp", resp)
body,_ := ioutil.ReadAll(resp.Body)
fmt.Println("In Sent Http body", string(body))
resp_result := CommonPostData{}
err := json.Unmarshal(body, &resp_result)
if err != nil{
log.Fatal(err)
}
result,_ := Base64Decode(resp_result.Content)
fmt.Println("result", result)
return result
}
func CopyHttpfilesToLocalFiles(files []*multipart.FileHeader) []string{
var InvoiceFilenames []string
for i :=0; i<len(files);i++{
file, err := files[i].Open()
defer file.Close()
if err != nil{
log.Fatal(err)
}
temp_str :="./cache/"+files[i].Filename
cur, _ := os.Create(temp_str)
InvoiceFilenames = append(InvoiceFilenames,temp_str)
defer cur.Close()
io.Copy(cur, file)
}
return InvoiceFilenames
}
func GeneratePchNumber() string{
current_time := time.Now().Format("20060102150405")
var head0 string
for i:=0;i<(32-len(current_time));i++{
head0 +="0"
}
current_time =head0+current_time
return current_time
}
func AppendContentToFile(filePath string, Content string){
file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
fmt.Println("文件打开失败", err)
}
defer file.Close()
write:= bufio.NewWriter(file)
write.WriteString(Content+"\n")
write.Flush()
}
| true |
f6fb72ec44d30f055fd91d14262e9f023abd3cc8
|
Go
|
sosedoff/dotfiles
|
/tools/scan_pano_photos.go
|
UTF-8
| 1,195 | 3.015625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"github.com/gosexy/exif"
)
func expandPath(path string) string {
home := os.Getenv("HOME")
return strings.Replace(path, "~", home, 1)
}
func scanImageFiles(path string) ([]string, error) {
results := make([]string, 0)
basePath := expandPath(path)
files, err := ioutil.ReadDir(basePath)
if err != nil {
return results, err
}
for _, file := range files {
if !file.IsDir() {
ext := filepath.Ext(file.Name())
if ext == ".JPG" {
results = append(results, basePath+"/"+file.Name())
}
}
}
return results, nil
}
func main() {
if len(os.Args) != 2 {
fmt.Println("Provide a path")
os.Exit(1)
}
path := expandPath(os.Args[1])
out, err := exec.Command("find", path, "-name", "*.JPG").Output()
if err != nil {
fmt.Println("Cant find any images")
return
}
files := strings.Split(strings.TrimSpace(string(out)), "\n")
exifr := exif.New()
for _, path := range files {
err = exifr.Open(path)
x, _ := strconv.Atoi(exifr.Tags["Pixel X Dimension"])
y, _ := strconv.Atoi(exifr.Tags["Pixel Y Dimension"])
if x/y > 2.0 {
fmt.Println(path)
}
}
}
| true |
08781dafbe0aa6a0891d0cfbeefe83fd8e230616
|
Go
|
AFloresc/atutorgobknd
|
/tapi/rbac/jwtmiddleware.go
|
UTF-8
| 755 | 2.53125 | 3 |
[] |
no_license
|
[] |
no_license
|
package rbac
import (
jwtmiddleware "github.com/auth0/go-jwt-middleware"
jwt "github.com/dgrijalva/jwt-go"
"github.com/gorilla/mux"
"github.com/urfave/negroni"
)
type JWTMiddleware struct {
jwtMW *jwtmiddleware.JWTMiddleware
}
func NewJWTMiddlware(authnValidationKey string) *JWTMiddleware {
return &JWTMiddleware{
jwtMW: jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return []byte(authnValidationKey), nil
},
SigningMethod: jwt.SigningMethodHS256,
CredentialsOptional: false,
}),
}
}
func (j JWTMiddleware) AuthenticateRouter(router *mux.Router) *negroni.Negroni {
return negroni.New(negroni.HandlerFunc(j.jwtMW.HandlerWithNext), negroni.Wrap(router))
}
| true |
4d14638c40056484af84d353e0fe9781561cbac3
|
Go
|
krlv/ctci-go
|
/ch02/05_sum_lists_test.go
|
UTF-8
| 3,129 | 3.375 | 3 |
[] |
no_license
|
[] |
no_license
|
package ch02
import "testing"
func TestSumLists(t *testing.T) {
n1 := New(7)
n1.AppendToTail(1)
n1.AppendToTail(6)
n2 := New(5)
n2.AppendToTail(9)
n2.AppendToTail(2)
expected := []int{2, 1, 9}
actual := SumLists(n1, n2)
for i := 0; actual != nil; i++ {
if actual.data != expected[i] {
t.Errorf("%dth node expected to have data %v, got %v", i+1, expected[i], actual.data)
}
actual = actual.next
}
n1 = New(1)
n1.AppendToTail(1)
n2 = New(9)
n2.AppendToTail(9)
expected = []int{0, 1, 1}
actual = SumLists(n1, n2)
for i := 0; actual != nil; i++ {
if actual.data != expected[i] {
t.Errorf("%dth node expected to have data %v, got %v", i+1, expected[i], actual.data)
}
actual = actual.next
}
n1 = New(1)
n1.AppendToTail(1)
n2 = New(2)
n2.AppendToTail(2)
expected = []int{3, 3}
actual = SumLists(n1, n2)
for i := 0; actual != nil; i++ {
if actual.data != expected[i] {
t.Errorf("%dth node expected to have data %v, got %v", i+1, expected[i], actual.data)
}
actual = actual.next
}
n1 = New(1)
n1.AppendToTail(1)
n1.AppendToTail(1)
n2 = New(2)
n2.AppendToTail(2)
expected = []int{3, 3, 1}
actual = SumLists(n1, n2)
for i := 0; actual != nil; i++ {
if actual.data != expected[i] {
t.Errorf("%dth node expected to have data %v, got %v", i+1, expected[i], actual.data)
}
actual = actual.next
}
}
func TestSumListsReverse(t *testing.T) {
n1 := New(6)
n1.AppendToTail(1)
n1.AppendToTail(7)
n2 := New(2)
n2.AppendToTail(9)
n2.AppendToTail(5)
expected := []int{9, 1, 2}
actual := SumListsReverse(n1, n2)
for i := 0; actual != nil; i++ {
if actual.data != expected[i] {
t.Errorf("%dth node expected to have data %v, got %v", i+1, expected[i], actual.data)
}
actual = actual.next
}
n1 = New(1)
n1.AppendToTail(1)
n2 = New(9)
n2.AppendToTail(9)
expected = []int{1, 1, 0}
actual = SumListsReverse(n1, n2)
for i := 0; actual != nil; i++ {
if actual.data != expected[i] {
t.Errorf("%dth node expected to have data %v, got %v", i+1, expected[i], actual.data)
}
actual = actual.next
}
n1 = New(1)
n1.AppendToTail(1)
n2 = New(2)
n2.AppendToTail(2)
expected = []int{3, 3}
actual = SumListsReverse(n1, n2)
for i := 0; actual != nil; i++ {
if actual.data != expected[i] {
t.Errorf("%dth node expected to have data %v, got %v", i+1, expected[i], actual.data)
}
actual = actual.next
}
n1 = New(1)
n1.AppendToTail(1)
n1.AppendToTail(1)
n2 = New(2)
n2.AppendToTail(2)
expected = []int{1, 3, 3}
actual = SumListsReverse(n1, n2)
for i := 0; actual != nil; i++ {
if actual.data != expected[i] {
t.Errorf("%dth node expected to have data %v, got %v", i+1, expected[i], actual.data)
}
actual = actual.next
}
n1 = New(1)
n1.AppendToTail(1)
n1.AppendToTail(1)
n2 = New(2)
n2.AppendToTail(2)
n2.AppendToTail(2)
n2.AppendToTail(2)
expected = []int{2, 3, 3, 3}
actual = SumListsReverse(n1, n2)
for i := 0; actual != nil; i++ {
if actual.data != expected[i] {
t.Errorf("%dth node expected to have data %v, got %v", i+1, expected[i], actual.data)
}
actual = actual.next
}
}
| true |
5675534e77779bdb7703bd4bf191f1c47ff0aec5
|
Go
|
zachmu/dolt
|
/go/libraries/doltcore/str_to_noms_test.go
|
UTF-8
| 2,370 | 2.6875 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
// Copyright 2019 Liquidata, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package doltcore
import (
"testing"
"github.com/liquidata-inc/dolt/go/store/types"
)
type strToNomsTypeTests struct {
s string
k types.NomsKind
expVal types.Value
expErr bool
}
var tests = []strToNomsTypeTests{
{"test string", types.StringKind, types.String("test string"), false},
{"1.3294398", types.FloatKind, types.Float(1.3294398), false},
{"-3294398", types.FloatKind, types.Float(-3294398), false},
{"TRuE", types.BoolKind, types.Bool(true), false},
{"False", types.BoolKind, types.Bool(false), false},
{"-123456", types.IntKind, types.Int(-123456), false},
{"123456", types.IntKind, types.Int(123456), false},
{"100000000000", types.UintKind, types.Uint(100000000000), false},
{"0", types.UintKind, types.Uint(0), false},
{
"01234567-89ab-cdef-FEDC-BA9876543210",
types.UUIDKind,
types.UUID([16]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10}),
false},
{"0", types.UintKind, types.Uint(0), false},
{"", types.NullKind, types.NullValue, false},
{"test failure", types.FloatKind, nil, true},
{"test failure", types.BoolKind, nil, true},
{"test failure", types.IntKind, nil, true},
{"0xdeadbeef", types.IntKind, nil, true},
{"test failure", types.UintKind, nil, true},
{"-1", types.UintKind, nil, true},
{"0123456789abcdeffedcba9876543210abc", types.UUIDKind, nil, true},
{"0", types.UUIDKind, nil, true},
}
func TestStrConversion(t *testing.T) {
for _, test := range tests {
val, err := StringToValue(test.s, test.k)
if (err != nil) != test.expErr {
t.Errorf("Conversion of \"%s\" returned unexpected error: %v", test.s, err)
}
if err == nil && val != test.expVal {
t.Errorf("Conversion of \"%s\" returned unexpected error: %v", test.s, err)
}
}
}
| true |
2b989a2b13937b277e36153126ef693eacfca840
|
Go
|
tresnaadin/Into-the-Golang-Verse
|
/code/palindrome.go
|
UTF-8
| 1,214 | 3.84375 | 4 |
[] |
no_license
|
[] |
no_license
|
package code
import (
"fmt"
"strconv"
"strings"
)
// The parameter of "func utama" could be inputted on "start.go"
func Utama(x string) int {
inputNum := strings.Split(x, " ") // The string input value will be convert to Array
arrayInput := make([]int, len(inputNum))
for i := range arrayInput {
arrayInput[i], _ = strconv.Atoi(inputNum[i]) // The conversion from String to Integer will be done here
}
count := 0
for i := arrayInput[0]; i <= arrayInput[1]; i++ {
startingPoint := i
result := reverse(i) // This line refers to "func reverse" on bellow
if startingPoint == result {
count += 1 // Everytime startingPoint value matched with the Result, it will increase the Count value by 1
}
}
return count // The result of Counted Palindrome
}
// The reverse version of Parameter value will be done in this function
func reverse(n int) int {
reverseInt := strconv.Itoa(n) // The conversion from Integer to String will be done here
endPoint := ""
for x := len(reverseInt); x > 0; x-- {
endPoint += string(reverseInt[x-1])
}
newInt, err := strconv.Atoi(endPoint) // The conversion from String to Integer will be done here
if err != nil {
fmt.Println(err)
}
return newInt
}
| true |
1802e8d1a8b49b4e33d6b580759d49a566fdddf7
|
Go
|
cia-rana/go-telnet-echo-client
|
/main.go
|
UTF-8
| 1,310 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"flag"
"fmt"
oi "github.com/reiver/go-oi"
telnet "github.com/reiver/go-telnet"
termbox "github.com/nsf/termbox-go"
)
func main() {
host := flag.String("host", "localhost", "host")
port := flag.String("port", "23", "port")
flag.Parse()
// Init termbox to use the getchar
if err := termbox.Init(); err != nil {
panic(err)
}
defer termbox.Close()
termbox.SetCursor(0, 0)
termbox.HideCursor()
if err := telnet.DialToAndCall(*host+":"+*port, caller{}); err != nil {
fmt.Println(err)
}
}
type caller struct{}
func (c caller) CallTELNET(ctx telnet.Context, w telnet.Writer, r telnet.Reader) {
quit := make(chan struct{}, 1)
defer close(quit)
// Write to telnet server
readBlocker := make(chan struct{}, 1)
defer close(readBlocker)
go func() {
for {
switch ev := termbox.PollEvent(); ev.Type {
case termbox.EventKey:
if ev.Key == termbox.KeyCtrlC {
quit <- struct{}{}
return
}
if isASCII(ev.Ch) {
fmt.Printf("%c", ev.Ch)
oi.LongWrite(w, []byte{byte(ev.Ch)})
readBlocker <- struct{}{}
}
}
}
}()
// Read from telnet server
go func() {
var buffer [1]byte
p := buffer[:]
for {
<-readBlocker
r.Read(p)
fmt.Printf("%c", p[0])
}
}()
<-quit
}
func isASCII(r rune) bool {
return r <= '~'
}
| true |
39207932f4f6f9058d6ba5e058c35454e216bb93
|
Go
|
ihard/carbonapi
|
/expr/functions/timeShiftByMetric/function.go
|
UTF-8
| 7,070 | 2.609375 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
[
"BSD-2-Clause"
] |
permissive
|
package timeShiftByMetric
import (
"context"
"math"
"regexp"
"strings"
"github.com/ansel1/merry"
"github.com/go-graphite/carbonapi/expr/helper"
"github.com/go-graphite/carbonapi/expr/interfaces"
"github.com/go-graphite/carbonapi/expr/types"
"github.com/go-graphite/carbonapi/pkg/parser"
)
type offsetByVersion map[string]int64
type timeShiftByMetric struct {
interfaces.FunctionBase
}
func GetOrder() interfaces.Order {
return interfaces.Any
}
func New(configFile string) []interfaces.FunctionMetadata {
return []interfaces.FunctionMetadata{{
F: &timeShiftByMetric{},
Name: "timeShiftByMetric",
}}
}
// timeShiftByMetric(seriesList, markSource, versionRankIndex)
func (f *timeShiftByMetric) Do(ctx context.Context, e parser.Expr, from, until int64, values map[parser.MetricRequest][]*types.MetricData) (resultData []*types.MetricData, resultError error) {
params, err := f.extractCallParams(ctx, e, from, until, values)
if err != nil {
return nil, err
}
latestMarks, err := f.locateLatestMarks(params)
if err != nil {
return nil, err
}
offsets := f.calculateOffsets(params, latestMarks)
result := f.applyShift(params, offsets)
return result, nil
}
// applyShift shifts timeline of those metrics which major version is less than top major version
func (f *timeShiftByMetric) applyShift(params *callParams, offsets offsetByVersion) []*types.MetricData {
result := make([]*types.MetricData, 0, len(params.metrics))
for _, metric := range params.metrics {
offsetIsSet := false
offset := int64(0)
var possibleVersion string
name := metric.Tags["name"]
nameSplit := strings.Split(name, ".")
// make sure that there is desired rank at all
if params.versionRank >= len(nameSplit) {
continue
}
possibleVersion = nameSplit[params.versionRank]
if possibleOffset, ok := offsets[possibleVersion]; !ok {
for key, value := range offsets {
if strings.HasPrefix(key, possibleVersion) {
offset = value
offsetIsSet = true
offsets[possibleVersion] = value
}
}
} else {
offset = possibleOffset
offsetIsSet = true
}
// checking if it is some version after all, otherwise this series will be omitted
if offsetIsSet {
r := metric.CopyLinkTags()
r.Name = "timeShiftByMetric(" + r.Name + ")"
r.StopTime += offset
r.StartTime += offset
result = append(result, r)
}
}
return result
}
func (f *timeShiftByMetric) calculateOffsets(params *callParams, versions versionInfos) offsetByVersion {
result := make(offsetByVersion)
topPosition := versions[0].position
for _, version := range versions {
result[version.mark] = int64(topPosition-version.position) * params.stepTime
}
return result
}
// extractCallParams (preliminarily) validates and extracts parameters of timeShiftByMetric's call as structure
func (f *timeShiftByMetric) extractCallParams(ctx context.Context, e parser.Expr, from, until int64, values map[parser.MetricRequest][]*types.MetricData) (*callParams, error) {
metrics, err := helper.GetSeriesArg(ctx, e.Arg(0), from, until, values)
if err != nil {
return nil, err
}
marks, err := helper.GetSeriesArg(ctx, e.Arg(1), from, until, values)
if err != nil {
return nil, err
}
versionRank, err := e.GetIntArg(2)
if err != nil {
return nil, err
}
// validating data sets: both metrics and marks must have at least 2 series each
// also, all IsAbsent and Values lengths must be equal to each other
pointsQty := -1
stepTime := int64(-1)
var dataSets map[string][]*types.MetricData = map[string][]*types.MetricData{
"marks": marks,
"metrics": metrics,
}
for name, dataSet := range dataSets {
if len(dataSet) < 2 {
return nil, merry.WithMessagef(errTooFewDatasets, "bad data: need at least 2 %s data sets to process, got %d", name, len(dataSet))
}
for _, series := range dataSet {
if pointsQty == -1 {
pointsQty = len(series.Values)
if pointsQty == 0 {
return nil, merry.WithMessagef(errEmptySeries, "bad data: empty series %s", series.Name)
}
} else if pointsQty != len(series.Values) {
return nil, merry.WithMessagef(errSeriesLengthMismatch, "bad data: length of Values for series %s differs from others", series.Name)
}
if stepTime == -1 {
stepTime = series.StepTime
}
}
}
result := &callParams{
metrics: metrics,
marks: marks,
versionRank: versionRank,
pointsQty: pointsQty,
stepTime: stepTime,
}
return result, nil
}
var reLocateMark *regexp.Regexp = regexp.MustCompile(`(\d+)_(\d+)`)
// locateLatestMarks gets the series with marks those look like "65_4"
// and looks for the latest ones by _major_ versions
// e.g. among set [63_0, 64_0, 64_1, 64_2, 65_0, 65_1] it locates 63_0, 64_4 and 65_1
// returns located elements
func (f *timeShiftByMetric) locateLatestMarks(params *callParams) (versionInfos, error) {
versions := make(versionInfos, 0, len(params.marks))
// noinspection SpellCheckingInspection
for _, mark := range params.marks {
markSplit := strings.Split(mark.Tags["name"], ".")
markVersion := markSplit[len(markSplit)-1]
// for mark that matches pattern (\d+)_(\d+), this should return slice of 3 strings exactly
submatch := reLocateMark.FindStringSubmatch(markVersion)
if len(submatch) != 3 {
continue
}
position := -1
for i := params.pointsQty - 1; i >= 0; i-- {
if !math.IsNaN(mark.Values[i]) {
position = i
break
}
}
if position == -1 {
// weird, but mark series has no data in it - skipping
continue
}
// collecting all marks found
versions = append(versions, versionInfo{
mark: markVersion,
position: position,
versionMajor: mustAtoi(submatch[1]),
versionMinor: mustAtoi(submatch[2]),
})
}
// obtain top versions for each major version
result := versions.HighestVersions()
if len(result) < 2 {
return nil, merry.WithMessagef(errLessThan2Marks, "bad data: could not find 2 marks, only %d found", len(result))
} else {
return result, nil
}
}
func (f *timeShiftByMetric) Description() map[string]types.FunctionDescription {
return map[string]types.FunctionDescription{
"timeShiftByMetric": types.FunctionDescription{
Description: "Takes a seriesList with wildcard in versionRankIndex rank and applies shift to the closest version from markSource\n\n.. code-block:: none\n\n &target=timeShiftByMetric(carbon.agents.graphite.creates)",
Function: "timeShiftByMetric(seriesList, markSource, versionRankIndex)",
Group: "Transform",
Module: "graphite.render.functions",
Name: "timeShiftByMetric",
Params: []types.FunctionParam{
types.FunctionParam{
Name: "seriesList",
Required: true,
Type: types.SeriesList,
},
types.FunctionParam{
Name: "markSource",
Required: true,
Type: types.SeriesList,
},
types.FunctionParam{
Name: "versionRankIndex",
Required: true,
Type: types.Integer,
},
},
NameChange: true, // name changed
ValuesChange: true, // values changed
},
}
}
| true |
9cc20fcdb10ff85735f2c54e18d73ed898627644
|
Go
|
nqd/cs-bc-w3
|
/artifacts/src/github.com/nqd/salmon_transfer/main.go
|
UTF-8
| 5,013 | 2.890625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"encoding/json"
"fmt"
"log"
"strconv"
"time"
"github.com/hyperledger/fabric/core/chaincode/shim"
sc "github.com/hyperledger/fabric/protos/peer"
)
// Define the Smart Contract structure
type SmartContract struct {
}
type salmon struct {
ObjectType string `json:"docType"`
ID string `json:"id"`
Vessel string `json:"vessel"`
Datetime string `json:"datetime"`
Location string `json:"localtion"`
Holder string `json:"holder"`
}
type deal struct {
ObjectType string `json:"docType"`
Buyer string `json:"buyer"`
Seller string `json:"seller"`
Price int32 `json:"price"`
}
/*
* The Init method is called when the Smart Contract "fabcar" is instantiated by the blockchain network
* Best practice is to have any Ledger initialization in separate function -- see initLedger()
*/
func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {
log.Println(">> salmon transfer: init")
salmons := []salmon{
salmon{
Vessel: "vessel no1",
Datetime: time.Now().Format(time.UnixDate),
Location: "somewhere",
Holder: "someone",
},
}
log.Printf("salmons %v\n", salmons)
i := 0
for i < len(salmons) {
salmonAsBytes, _ := json.Marshal(salmons[i])
APIstub.PutState("SALMON"+strconv.Itoa(i), salmonAsBytes)
fmt.Println("Added", salmons[i])
i = i + 1
}
return shim.Success(nil)
}
/*
* The Invoke method is called as a result of an application request to run the Smart Contract "fabcar"
* The calling application program has also specified the particular smart contract function to be called, with arguments
*/
func (s *SmartContract) Invoke(APIstub shim.ChaincodeStubInterface) sc.Response {
// Retrieve the requested Smart Contract function and arguments
function, args := APIstub.GetFunctionAndParameters()
// Route to the appropriate handler function to interact with the ledger appropriately
if function == "recordSalmon" {
return s.recordSalmon(APIstub, args)
}
if function == "changeSalmonHolder" {
return s.changeSalmonHolder(APIstub, args)
}
if function == "querySalmon" {
return s.querySalmon(APIstub, args)
}
if function == "queryAllSalmon" {
return s.queryAllSalmon(APIstub)
}
return shim.Error("Invalid Smart Contract function name.")
}
func (s *SmartContract) initLedger(APIstub shim.ChaincodeStubInterface) sc.Response {
salmons := []salmon{
salmon{
Vessel: "vessel no1",
Datetime: time.Now().Format(time.UnixDate),
Location: "somewhere",
Holder: "someone",
},
}
i := 0
for i < len(salmons) {
salmonAsBytes, _ := json.Marshal(salmons[i])
APIstub.PutState("SALMON"+strconv.Itoa(i), salmonAsBytes)
fmt.Println("Added", salmons[i])
i = i + 1
}
return shim.Success(nil)
}
func (s *SmartContract) recordSalmon(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {
if len(args) != 5 {
return shim.Error("Incorrect number of arguments. Expecting 5")
}
var salmon = salmon{
Vessel: args[1],
Datetime: args[2],
Location: args[3],
Holder: args[4],
}
salmonAsBytes, _ := json.Marshal(salmon)
APIstub.PutState(args[0], salmonAsBytes)
return shim.Success(nil)
}
func (s *SmartContract) changeSalmonHolder(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {
// 0 1
// id owner
if len(args) != 2 {
return shim.Error("Incorrect number of arguments. Expecting 2")
}
id := args[0]
newHolder := args[1]
salmonAsBytes, err := APIstub.GetState(id)
if err != nil {
return shim.Error("Failed to get salmon:" + err.Error())
}
if salmonAsBytes == nil {
return shim.Error("Salmon does not exist")
}
salmonToTransfer := salmon{}
err = json.Unmarshal(salmonAsBytes, &salmonToTransfer) // unmarshal it aka JSON.parse()
if err != nil {
return shim.Error(err.Error())
}
salmonToTransfer.Holder = newHolder //change the owner
newSalmonAsByte, _ := json.Marshal(salmonToTransfer)
err = APIstub.PutState(id, newSalmonAsByte) //rewrite the marble
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
}
func (s *SmartContract) querySalmon(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {
// 0
// id
if len(args) != 1 {
return shim.Error("Incorrect number of arguments. Expecting 1")
}
id := args[0]
salmonAsBytes, err := APIstub.GetState(id)
if err != nil {
return shim.Error("Failed to get salmon:" + err.Error())
}
if salmonAsBytes == nil {
return shim.Error("Salmon does not exist")
}
return shim.Success(salmonAsBytes)
}
func (s *SmartContract) queryAllSalmon(APIstub shim.ChaincodeStubInterface) sc.Response {
return shim.Success([]byte{})
}
// queryAllSalmon -- used by regulator to check sustainability of supply chain
// todo
// The main function is only relevant in unit test mode. Only included here for completeness.
func main() {
// Create a new Smart Contract
err := shim.Start(new(SmartContract))
if err != nil {
fmt.Printf("Error creating new Smart Contract: %s", err)
}
}
| true |
a7d34735833339a261630c249f19ad9addf8eb6a
|
Go
|
ronniegane/hackerrank-solutions
|
/interviews/greedy/abs/abs.go
|
UTF-8
| 572 | 3.734375 | 4 |
[] |
no_license
|
[] |
no_license
|
package abs
import (
"sort"
)
func minAbsDiff(arr []int32) int32 {
// Find the minimum absolute difference between any two numbers
// in the array
// First approach: sort, then compare consecutive pairs
sort.Slice(arr, func(a, b int) bool {
return arr[a] < arr[b]
})
// Iterate comparing pairs
min := arr[1] - arr[0] // With array sorted ascending, this will be >= 0
for i := 0; i < len(arr)-1; i++ {
next := arr[i+1] - arr[i]
if next < min {
min = next
}
if min == 0 {
// If we find zero diff we can stop early
break
}
}
return min
}
| true |
90956b0ab00a5e1a3ba575850fa066baf5867da5
|
Go
|
belousandrey/new-episodes
|
/new_episodes.go
|
UTF-8
| 1,614 | 3.03125 | 3 |
[] |
no_license
|
[] |
no_license
|
package new_episodes
import "io"
const (
// DateFormat - default date format that used at most of podcasts
DateFormat = "2006-01-02"
)
// Episoder - interface for engines
type Episoder interface {
GetNewEpisodes(resp io.Reader) (episodes []Episode, last string, err error)
}
// Podcast - config file representation for podcast
type Podcast struct {
// Last - string with last episode date
Last string
// Link - link to RSS or HTML page with episodes list
Link string
// Title - human readable name
Title string
// Engine - way of podcast processing
Engine string
}
// Episode - one episode of podcast
type Episode struct {
// Link - URL to the episode file
Link string
// Title - name of the episode
Title string
// Date - string with episode date
Date string
}
// PodcastWithEpisodes - data structure for email template
type PodcastWithEpisodes struct {
// Position - position in config file
Position int
Podcast
// Episodes - list with new episodes
Episodes []Episode
// LastEpisodeDate - string with last episode date
LastEpisodeDate string
}
// NewPodcastWithEpisodes - create new data structure
func NewPodcastWithEpisodes(podcast Podcast, pos int, led string) *PodcastWithEpisodes {
return &PodcastWithEpisodes{
pos,
podcast,
make([]Episode, 0),
led,
}
}
// EmailContent - structured data for email
type EmailContent struct {
Success []PodcastWithEpisodes
Problem []Podcast
}
// NewEmailContent - create new email content structure
func NewEmailContent(s []PodcastWithEpisodes, p []Podcast) *EmailContent {
return &EmailContent{
Success: s,
Problem: p,
}
}
| true |
4b045f558cdfd5a4047b3ff457af4d6c6b6b3100
|
Go
|
temporalio/ringpop-go
|
/hashring/rbtree_test.go
|
UTF-8
| 27,383 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
// Copyright (c) 2015 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 hashring
import (
"errors"
"fmt"
"math/rand"
"strconv"
"testing"
"github.com/stretchr/testify/assert"
)
type treeTestInt int
func (t treeTestInt) Compare(other interface{}) int {
return int(t) - int(other.(treeTestInt))
}
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
//
// TESTS
//
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
func makeTree() redBlackTree {
tree := redBlackTree{}
tree.Insert(treeTestInt(1), "one")
tree.Insert(treeTestInt(2), "two")
tree.Insert(treeTestInt(3), "three")
tree.Insert(treeTestInt(4), "four")
tree.Insert(treeTestInt(5), "five")
tree.Insert(treeTestInt(6), "six")
tree.Insert(treeTestInt(7), "seven")
tree.Insert(treeTestInt(8), "eight")
// 4,B
// / \
// 2,R 6,R
// / \ / \
// 1,B 3,B 5,B 7,B
// \
// 8,R
return tree
}
func TestEmptyTree(t *testing.T) {
tree := redBlackTree{}
assert.Nil(t, tree.root, "tree root is nil")
assert.Equal(t, 0, tree.Size(), "tree has 0 nodes")
}
// counts the black height of the tree and validates it along the way
func validateRedBlackTree(n *redBlackNode) (int, error) {
if n == nil {
return 1, nil
}
var err error
if isRed(n) && (isRed(n.left) || isRed(n.right)) {
err = errors.New(fmt.Sprint("red violation at node key ", n.key))
return 0, err
}
leftHeight, err := validateRedBlackTree(n.left)
if err != nil {
return 0, err
}
rightHeight, err := validateRedBlackTree(n.right)
if err != nil {
return 0, err
}
if n.left != nil && n.left.key.Compare(n.key) >= 0 ||
n.right != nil && n.right.key.Compare(n.key) <= 0 {
err = errors.New(fmt.Sprint("binary tree violation at node key ", n.key))
return 0, err
}
if leftHeight != 0 && rightHeight != 0 {
if leftHeight != rightHeight {
err = errors.New(fmt.Sprint("black height violation at node key ", n.key))
return 0, err
}
if isRed(n) {
return leftHeight, nil
}
return leftHeight + 1, nil
}
return 0, nil
}
func TestInsert(t *testing.T) {
tree := makeTree()
height, err := validateRedBlackTree(tree.root)
assert.NoError(t, err, "expected tree to be a valid red black tree")
assert.Equal(t, 3, height, "expected tree to have black height of 3")
assert.Equal(t, 8, tree.Size(), "expected tree to have 8 nodes")
// 4, B
node := tree.root
assert.Equal(t, treeTestInt(4), node.key, "expected tree root key to be 4")
assert.Equal(t, "four", node.value, "expected tree root value to be 'four'")
assert.Equal(t, false, node.red, "expected tree root to be black")
assert.NotNil(t, node.left, "expected tree root to have left child")
assert.NotNil(t, node.right, "expected tree root to have right child")
// 2,R
node = tree.root.left
assert.Equal(t, treeTestInt(2), node.key, "got unexpected node key")
assert.Equal(t, "two", node.value, "got unexpected node value")
assert.Equal(t, true, node.red, "got unexpected node colour")
assert.NotNil(t, node.left, "expected node to have left child")
assert.NotNil(t, node.right, "expected node to have right child")
// 1,B
node = tree.root.left.left
assert.Equal(t, treeTestInt(1), node.key, "got unexpected node key")
assert.Equal(t, "one", node.value, "got unexpected node value")
assert.Equal(t, false, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.Nil(t, node.right, "expected node to have no right child")
// 3, B
node = tree.root.left.right
assert.Equal(t, treeTestInt(3), node.key, "got unexpected node key")
assert.Equal(t, "three", node.value, "got unexpected node value")
assert.Equal(t, false, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.Nil(t, node.right, "expected node to have no right child")
// 6, R
node = tree.root.right
assert.Equal(t, treeTestInt(6), node.key, "got unexpected node key")
assert.Equal(t, "six", node.value, "got unexpected node value")
assert.Equal(t, true, node.red, "got unexpected node colour")
assert.NotNil(t, node.left, "expected node to have left child")
assert.NotNil(t, node.right, "expected node to have right child")
// 5, B
node = tree.root.right.left
assert.Equal(t, treeTestInt(5), node.key, "got unexpected node key")
assert.Equal(t, "five", node.value, "got unexpected node value")
assert.Equal(t, false, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.Nil(t, node.right, "expected node to have no right child")
// 7, B
node = tree.root.right.right
assert.Equal(t, treeTestInt(7), node.key, "got unexpected node key")
assert.Equal(t, "seven", node.value, "got unexpected node value")
assert.Equal(t, false, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.NotNil(t, node.right, "expected node to have right child")
// 8, R
node = tree.root.right.right.right
assert.Equal(t, treeTestInt(8), node.key, "got unexpected node key")
assert.Equal(t, "eight", node.value, "got unexpected node value")
assert.Equal(t, true, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.Nil(t, node.right, "expected node to have no right child")
value, found := tree.Search(treeTestInt(7))
assert.True(t, found, "expected key to be found in tree")
assert.Equal(t, "seven", value, "expected search return value of 'seven'")
value, found = tree.Search(treeTestInt(9))
assert.False(t, found, "expected key to not be found in tree")
assert.Equal(t, nil, value, "expected search to return nil")
}
func TestDuplicateInsert(t *testing.T) {
tree := makeTree()
assert.Equal(t, 8, tree.Size(), "expected tree to have 8 nodes")
assert.True(t, tree.Insert(treeTestInt(9), "nine"), "failed, expected insertion success")
assert.Equal(t, 9, tree.Size(), "expected tree to have 9 nodes")
assert.False(t, tree.Insert(treeTestInt(1), "one"), "success, expected insertion to fail (duplicate value)")
assert.Equal(t, 9, tree.Size(), "expected tree to have 9 nodes")
}
func TestRemoveInsert(t *testing.T) {
tree := makeTree()
assert.Equal(t, 8, tree.Size(), "expected tree to have 8 nodes")
assert.True(t, tree.Delete(treeTestInt(2)), "failed, expected successful deletion")
assert.True(t, tree.Delete(treeTestInt(4)), "failed, expected successful deletion")
assert.Equal(t, 6, tree.Size(), "expected tree to have 6 nodes")
assert.True(t, tree.Insert(treeTestInt(2), "two"), "failed, expected insertions success")
_, err := validateRedBlackTree(tree.root)
assert.NoError(t, err, "expected tree to be a valid red black tree")
assert.Equal(t, 7, tree.Size(), "expected tree to have 7 nodes")
assert.True(t, tree.Insert(treeTestInt(4), "four"), "failed, expected insertion success")
_, err = validateRedBlackTree(tree.root)
assert.NoError(t, err, "expected tree to be a valid red black tree")
assert.Equal(t, 8, tree.Size(), "expected tree to have 8 nodes")
}
func TestDelete(t *testing.T) {
tree := makeTree()
height, err := validateRedBlackTree(tree.root)
assert.NoError(t, err, "expected tree to be a valid red black tree")
assert.Equal(t, 3, height, "expected tree to have black height of 3")
assert.Equal(t, 8, tree.Size(), "expected tree to have 8 nodes")
// 4,B
// / \
// 2,R 6,R
// / \ / \
// 1,B 3,B 5,B 7,B
// \
// 8,R
// REMOVE 1
assert.True(t, tree.Delete(treeTestInt(1)), "expected node to be found and removed from tree")
assert.Equal(t, 7, tree.Size(), "expected tree to have 7 nodes")
height, err = validateRedBlackTree(tree.root)
assert.NoError(t, err, "expected tree to be a valid red black tree")
assert.Equal(t, 3, height, "expected tree to have black height of 3")
// new tree:
// 4,B
// / \
// 2,B 6,R
// \ / \
// 3,R 5,B 7,B
// \
// 8,R
// 4,B
node := tree.root
assert.Equal(t, treeTestInt(4), node.key, "expected tree root key to be 4")
assert.Equal(t, "four", node.value, "expected tree root value to be 'four'")
assert.Equal(t, false, node.red, "expected tree root to be black")
assert.NotNil(t, node.left, "expected tree root to have left child")
assert.NotNil(t, node.right, "expected tree root to have right child")
// 2,R
node = tree.root.left
assert.Equal(t, treeTestInt(2), node.key, "got unexpected node key")
assert.Equal(t, "two", node.value, "got unexpected node value")
assert.Equal(t, false, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.NotNil(t, node.right, "expected node to have right child")
// 3,B
node = tree.root.left.right
assert.Equal(t, treeTestInt(3), node.key, "got unexpected node key")
assert.Equal(t, "three", node.value, "got unexpected node value")
assert.Equal(t, true, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.Nil(t, node.right, "expected node to have no right child")
// 6,R
node = tree.root.right
assert.Equal(t, treeTestInt(6), node.key, "got unexpected node key")
assert.Equal(t, "six", node.value, "got unexpected node value")
assert.Equal(t, true, node.red, "got unexpected node colour.")
assert.NotNil(t, node.left, "expected node to have left child")
assert.NotNil(t, node.right, "expected node to have right child")
// 5, B
node = tree.root.right.left
assert.Equal(t, treeTestInt(5), node.key, "got unexpected node key")
assert.Equal(t, "five", node.value, "got unexpected node value")
assert.Equal(t, false, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.Nil(t, node.right, "expected node to have no right child")
// 7, B
node = tree.root.right.right
assert.Equal(t, treeTestInt(7), node.key, "got unexpected node key")
assert.Equal(t, "seven", node.value, "got unexpected node value")
assert.Equal(t, false, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.NotNil(t, node.right, "expected node to have right child")
// 8, R
node = tree.root.right.right.right
assert.Equal(t, treeTestInt(8), node.key, "got unexpected node key")
assert.Equal(t, "eight", node.value, "got unexpected node value")
assert.Equal(t, true, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.Nil(t, node.right, "expected node to have no right child")
// REMOVE 2
assert.True(t, tree.Delete(treeTestInt(2)), "expected node to be found and removed from tree")
assert.Equal(t, 6, tree.Size(), "expected tree to have 6 nodes")
height, err = validateRedBlackTree(tree.root)
assert.NoError(t, err, "expected tree to be a valid red black tree")
assert.Equal(t, 3, height, "expected tree to have black height of 3")
// new tree:
// 6,B
// / \
// 4,R 7,B
// / \ \
// 3,B 5,B 8,R
// 6,B
node = tree.root
assert.Equal(t, treeTestInt(6), node.key, "expected tree root key to be 6")
assert.Equal(t, "six", node.value, "expected tree root value to be 6")
assert.Equal(t, false, node.red, "expected tree root to be black")
assert.NotNil(t, node.left, "expected tree root to have left child")
assert.NotNil(t, node.right, "expected tree root to have right child")
// 4,R
node = tree.root.left
assert.Equal(t, treeTestInt(4), node.key, "got unexpected node key")
assert.Equal(t, "four", node.value, "got unexpected node value")
assert.Equal(t, true, node.red, "got unexpected node colour")
assert.NotNil(t, node.left, "node should have left child")
assert.NotNil(t, node.right, "node should have right child")
// 3,B
node = tree.root.left.left
assert.Equal(t, treeTestInt(3), node.key, "got unexpected node key")
assert.Equal(t, "three", node.value, "got unexpected node value")
assert.Equal(t, false, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.Nil(t, node.right, "expected node to have no right child")
// 5,B
node = tree.root.left.right
assert.Equal(t, treeTestInt(5), node.key, "got unexpected node key")
assert.Equal(t, "five", node.value, "got unexpected node value")
assert.Equal(t, false, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.Nil(t, node.right, "expected node to have no right child")
// 7,B
node = tree.root.right
assert.Equal(t, treeTestInt(7), node.key, "got unexpected node key")
assert.Equal(t, "seven", node.value, "got unexpected node value")
assert.Equal(t, false, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.NotNil(t, node.right, "expected node to have right child")
// 8,R
node = tree.root.right.right
assert.Equal(t, treeTestInt(8), node.key, "got unexpected node key")
assert.Equal(t, "eight", node.value, "got unexpected node value")
assert.Equal(t, true, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.Nil(t, node.right, "expected node to have no right child")
// REMOVE 3
assert.True(t, tree.Delete(treeTestInt(3)), "expected node to be found and removed from tree")
assert.Equal(t, 5, tree.Size(), "expected tree to have 5 nodes")
height, err = validateRedBlackTree(tree.root)
assert.NoError(t, err, "expected tree to be a valid red black tree")
assert.Equal(t, 3, height, "expected tree to have black height of 3")
// new tree:
// 6,B
// / \
// 4,B 7,B
// \ \
// 5,R 8,R
// 6,B
node = tree.root
assert.Equal(t, treeTestInt(6), node.key, "expected tree root key to be 6")
assert.Equal(t, "six", node.value, "expected tree root value to be 6")
assert.Equal(t, false, node.red, "expected tree root to be black")
assert.NotNil(t, node.left, "expected tree root to have left child")
assert.NotNil(t, node.right, "expected tree root to have right child")
// 4,B
node = tree.root.left
assert.Equal(t, treeTestInt(4), node.key, "got unexpected node key")
assert.Equal(t, "four", node.value, "got unexpected node value")
assert.Equal(t, false, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.NotNil(t, node.right, "expected node to have right child")
// 5,R
node = tree.root.left.right
assert.Equal(t, treeTestInt(5), node.key, "got unexpected node key")
assert.Equal(t, "five", node.value, "got unexpected node value")
assert.Equal(t, true, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.Nil(t, node.right, "expected node to have no right child")
// 7,B
node = tree.root.right
assert.Equal(t, treeTestInt(7), node.key, "got unexpected node key")
assert.Equal(t, "seven", node.value, "got unexpected node value")
assert.Equal(t, false, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.NotNil(t, node.right, "expected node to have right child")
// 8,R
node = tree.root.right.right
assert.Equal(t, treeTestInt(8), node.key, "got unexpected node key")
assert.Equal(t, "eight", node.value, "got unexpected node value")
assert.Equal(t, true, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.Nil(t, node.right, "expected node to have no right child")
// REMOVE 4
assert.True(t, tree.Delete(treeTestInt(4)), "expected node to be found and removed from tree")
assert.Equal(t, 4, tree.Size(), "expected tree to have 4 nodes")
height, err = validateRedBlackTree(tree.root)
assert.NoError(t, err, "expected tree to be a valid red black tree")
assert.Equal(t, 3, height, "expected tree to have black height of 3")
// new tree:
// 6,B
// / \
// 5,B 7,B
// \
// 8,R
// 6,B
node = tree.root
assert.Equal(t, treeTestInt(6), node.key, "expected tree root key to be 6")
assert.Equal(t, "six", node.value, "expected tree root value to be 6")
assert.Equal(t, false, node.red, "expected tree root to be black")
assert.NotNil(t, node.left, "expected tree root to have left child")
assert.NotNil(t, node.right, "expected tree root to have right child")
// 5,B
node = tree.root.left
assert.Equal(t, treeTestInt(5), node.key, "got unexpected node key")
assert.Equal(t, "five", node.value, "got unexpected node value")
assert.Equal(t, false, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.Nil(t, node.right, "expected node to have no right child")
// 7,B
node = tree.root.right
assert.Equal(t, treeTestInt(7), node.key, "got unexpected node key")
assert.Equal(t, "seven", node.value, "got unexpected node value")
assert.Equal(t, false, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.NotNil(t, node.right, "expected node to have right child")
// 8,R
node = tree.root.right.right
assert.Equal(t, treeTestInt(8), node.key, "got unexpected node key")
assert.Equal(t, "eight", node.value, "got unexpected node value")
assert.Equal(t, true, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.Nil(t, node.right, "expected node to have no right child")
// REMOVE 5
assert.True(t, tree.Delete(treeTestInt(5)), "expected node to be found and removed from tree")
assert.Equal(t, 3, tree.Size(), "expected tree to have 3 nodes")
height, err = validateRedBlackTree(tree.root)
assert.NoError(t, err, "expected tree to be a valid red black tree")
assert.Equal(t, 3, height, "expected tree to have black height of 3")
// new tree:
// 7,B
// / \
// 6,B 8,B
// 7,B
node = tree.root
assert.Equal(t, treeTestInt(7), node.key, "got unexpected node key")
assert.Equal(t, "seven", node.value, "got unexpected node value")
assert.Equal(t, false, node.red, "got unexpected node colour")
assert.NotNil(t, node.left, "expected node to have left child")
assert.NotNil(t, node.right, "expected node to have right child")
// 6,B
node = tree.root.left
assert.Equal(t, treeTestInt(6), node.key, "expected tree root key to be 6")
assert.Equal(t, "six", node.value, "expected tree root value to be 6")
assert.Equal(t, false, node.red, "expected tree root to be black")
assert.Nil(t, node.left, "expected tree root to have left child")
assert.Nil(t, node.right, "expected tree root to have right child")
// 8,R
node = tree.root.right
assert.Equal(t, treeTestInt(8), node.key, "got unexpected node key")
assert.Equal(t, "eight", node.value, "got unexpected node value")
assert.Equal(t, false, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.Nil(t, node.right, "expected node to have no right child")
// REMOVE 5
assert.True(t, tree.Delete(treeTestInt(6)), "expected node to be found and removed from tree")
assert.Equal(t, 2, tree.Size(), "expected tree to have 2 nodes")
height, err = validateRedBlackTree(tree.root)
assert.NoError(t, err, "expected tree to be a valid red black tree")
assert.Equal(t, 2, height, "expected tree to have black height of 2")
// new tree:
// 7,B
// \
// 8,R
// 7,B
node = tree.root
assert.Equal(t, treeTestInt(7), node.key, "got unexpected node key")
assert.Equal(t, "seven", node.value, "got unexpected node value")
assert.Equal(t, false, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.NotNil(t, node.right, "expected node to have right child")
// 8,R
node = tree.root.right
assert.Equal(t, treeTestInt(8), node.key, "got unexpected node key")
assert.Equal(t, "eight", node.value, "got unexpected node value")
assert.Equal(t, true, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.Nil(t, node.right, "expected node to have no right child")
// REMOVE 7
assert.True(t, tree.Delete(treeTestInt(7)), "expected node to be found and removed from tree")
assert.Equal(t, 1, tree.Size(), "expected tree to have 1 node")
height, err = validateRedBlackTree(tree.root)
assert.NoError(t, err, "expected tree to be a valid red black tree")
assert.Equal(t, 2, height, "expected tree to have black height of 2")
// new tree:
// 8,B
// 8,B
node = tree.root
assert.Equal(t, treeTestInt(8), node.key, "got unexpected node key")
assert.Equal(t, "eight", node.value, "got unexpected node value")
assert.Equal(t, false, node.red, "got unexpected node colour")
assert.Nil(t, node.left, "expected node to have no left child")
assert.Nil(t, node.right, "expected node to have no right child")
// REMOVE 7
assert.True(t, tree.Delete(treeTestInt(8)), "expected node to be found and removed from tree")
assert.Equal(t, 0, tree.Size(), "expected tree to be empty")
height, err = validateRedBlackTree(tree.root)
assert.NoError(t, err, "expected tree to be a valid red black tree")
assert.Equal(t, 1, height, "expected tree to have black height of 2")
// EMPTY TREE!
assert.Nil(t, tree.root, "tree root is nil")
assert.False(t, tree.Delete(treeTestInt(1)), "success, expected deletion to fail with empty tree")
assert.Equal(t, 0, tree.Size(), "expected tree to be empty")
height, err = validateRedBlackTree(tree.root)
assert.NoError(t, err, "expected tree to be a valid red black tree")
assert.Equal(t, 1, height, "expected tree to have black height of 1")
}
func TestSearchEmpty(t *testing.T) {
tree := redBlackTree{}
str, ok := tree.Search(treeTestInt(5))
assert.False(t, ok, "expected node to not be found")
assert.Equal(t, nil, str, "expected value to be nil")
}
func TestSearch(t *testing.T) {
tree := makeTree()
// 4,B
// / \
// 2,R 6,R
// / \ / \
// 1,B 3,B 5,B 7,B
// \
// 8,R
value, ok := tree.Search(treeTestInt(5))
assert.True(t, ok, "expected node to be found")
assert.Equal(t, "five", value, "expected value to be 'five'")
value, ok = tree.Search(treeTestInt(3))
assert.True(t, ok, "expected node to be found")
assert.Equal(t, "three", value, "expected value to be 'three'")
value, ok = tree.Search(treeTestInt(8))
assert.True(t, ok, "expected node to be found")
assert.Equal(t, "eight", value, "expected value to be 'three'")
value, ok = tree.Search(treeTestInt(9))
assert.False(t, ok, "expected node to not be found")
assert.Equal(t, nil, value, "expected value to be nil")
}
func TestBig(t *testing.T) {
tree := redBlackTree{}
random := rand.New(rand.NewSource(1337))
for i := 0; i < 2000; i++ {
n := random.Intn(10000)
tree.Insert(treeTestInt(n), strconv.Itoa(n))
}
_, err := validateRedBlackTree(tree.root)
assert.NoError(t, err, "expected tree to be a valid red black tree")
for i := 0; i < 1000; i++ {
n := random.Intn(10000)
tree.Delete(treeTestInt(n))
}
_, err = validateRedBlackTree(tree.root)
assert.NoError(t, err, "expected tree to be a valid red black tree")
}
func TestTraverseOrder(t *testing.T) {
tree := makeTree()
// 4,B
// / \
// 2,R 6,R
// / \ / \
// 1,B 3,B 5,B 7,B
// \
// 8,R
var last keytype
tree.root.traverseWhile(func(n *redBlackNode) bool {
current := n.key
if last != nil {
assert.True(t, current.Compare(last) > 0, "expected walk to walk the nodes in natural order as dictated by the Compare function")
}
last = current
return true
})
}
func TestTraverseEscape(t *testing.T) {
tree := makeTree()
// 4,B
// / \
// 2,R 6,R
// / \ / \
// 1,B 3,B 5,B 7,B
// \
// 8,R
var visited []int
tree.root.traverseWhile(func(n *redBlackNode) bool {
number := int(n.key.(treeTestInt))
visited = append(visited, number)
// stop at node 5, it should exit on a left, right and visiting node,
// this covers all exit cases
return number < 5
})
assert.Equal(t, []int{1, 2, 3, 4, 5}, visited, "expected all nodes up to five to be visited")
}
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
//
// BENCHMARKS
//
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
func BenchmarkRedBlackTreeInsert(b *testing.B) {
for n := 0; n < b.N; n++ {
tree := redBlackTree{}
for i := 0; i < 1000000; i++ {
tree.Insert(treeTestInt(i), "something")
}
}
}
func BenchmarkRedBlackTreeDelete(b *testing.B) {
for n := 0; n < b.N; n++ {
b.StopTimer()
// stop timer while tree is created
tree := redBlackTree{}
for i := 0; i < 1000000; i++ {
tree.Insert(treeTestInt(i), "something")
}
b.StartTimer()
// restart timer and time only deletion
for i := 0; i < 1000000; i++ {
tree.Delete(treeTestInt(i))
}
}
}
func BenchmarkRedBlackTreeSearch(b *testing.B) {
b.StopTimer()
tree := redBlackTree{}
for i := 0; i < 1000000; i++ {
tree.Insert(treeTestInt(i), "something")
}
b.StartTimer()
for n := 0; n < b.N; n++ {
for i := 0; i < 1000000; i++ {
tree.Search(treeTestInt(i))
}
}
}
| true |
51aebca8d2bbaf599d2108504adb40bc16a555c1
|
Go
|
shiki0083/beego
|
/go_dev/day3/example/example3/main/main.go
|
UTF-8
| 464 | 3.59375 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
)
func add(a int, arg ...int) int {
var sum int = a
for i := 0; i < len(arg); i++ {
sum += arg[i]
}
return sum
}
func test(a, b int) int {
result := func(a1 int, b1 int) int {
return a1 + b1
}(a, b)
return result
}
func main() {
sum := add(10, 3, 3)
fmt.Println(sum)
var i int = 0
defer fmt.Println("aaa", i)
defer fmt.Println("second", i)
i = 10
fmt.Println("ccc", i)
fmt.Println("result", test(100, 200))
}
| true |
ef212370ec8fe062ddcf8f807e6949c11785ff35
|
Go
|
psmorrow/knights-tour
|
/knights.go
|
UTF-8
| 5,176 | 3.5625 | 4 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
// A knight's tour is a sequence of moves of a knight on a chessboard such that the knight visits every square only once.
// A brute-force search for a knight's tour is impractical on all but the smallest boards; for example, on an 8 × 8 board there are approximately 4×1051 possible move sequences, and it is well beyond the capacity of modern computers (or networks of computers) to perform operations on such a large set.
// The heuristics approach is described here: https://en.wikipedia.org/wiki/Knight%27s_tour
package main
import (
"fmt"
"os"
"sort"
"time"
)
type move struct {
row int
column int
heuristic int
}
const squaresOnSide int = 6
const squaresOnBoard int = squaresOnSide * squaresOnSide
var possibleMoves = []move { {+1, -2, 0}, {+1, +2, 0}, {+2, -1, 0}, {+2, +1, 0}, {-1, -2, 0}, {-1, +2, 0}, {-2, +1, 0}, {-2, +1, 0} }
var heuristics [squaresOnSide][squaresOnSide]int
var heuristicMoves [squaresOnSide][squaresOnSide][]move
var board [squaresOnSide][squaresOnSide]int
func promptUser(promptText string, minValue int, maxValue int, errorText string) int {
var value int
// input 1 based
fmt.Print(promptText)
_, err := fmt.Scan(&value)
if err != nil {
fmt.Println("Invalid input:", err)
os.Exit(1)
}
if value < minValue || value > maxValue {
fmt.Println(errorText)
os.Exit(2)
}
// adjust to 0 based
value--
return value
}
func calculateHeuristics() {
// calculate heuristic values for each square
for row := 0; row < squaresOnSide; row++ {
for column := 0; column < squaresOnSide; column++ {
var squareHeuristic int = 0
for _, nextMove := range possibleMoves {
if row+nextMove.row >= 0 && row+nextMove.row < squaresOnSide && column+nextMove.column >= 0 && column+nextMove.column < squaresOnSide {
squareHeuristic += 1
}
}
heuristics[row][column] = squareHeuristic
}
}
// calculate heuristic moves for each square
for row := 0; row < squaresOnSide; row++ {
for column := 0; column < squaresOnSide; column++ {
var squareHeuristics []move
for _, nextMove := range possibleMoves {
if row+nextMove.row >= 0 && row+nextMove.row < squaresOnSide && column+nextMove.column >= 0 && column+nextMove.column < squaresOnSide {
squareHeuristics = append(squareHeuristics, move{ nextMove.row, nextMove.column, heuristics[row+nextMove.row][column+nextMove.column] })
}
}
// sort possible move heuristics
sort.SliceStable(squareHeuristics, func(i, j int) bool { return squareHeuristics[i].heuristic < squareHeuristics[j].heuristic })
heuristicMoves[row][column] = squareHeuristics
}
}
}
func solveBoard(row int, column int, level int) bool {
// is this move invalid? it is off the board or the space is occupied
if row < 0 || row >= squaresOnSide || column < 0 || column >= squaresOnSide || board[row][column] != 0 {
return false
}
// mark the position occupied by setting it to the level
board[row][column] = level
// is the board solved?
if level == squaresOnBoard {
return true
}
// calculate the next position (heuristics order of next moves)
var heuristicMoves = heuristicMoves[row][column]
for _, nextMove := range heuristicMoves {
if solveBoard(row+nextMove.row, column+nextMove.column, level+1) {
return true
}
}
// next move failed, so this one does too, undo current move
board[row][column] = 0
return false
}
func printBoard() {
// print out the board as a matrix displaying the move numbers at each row and column
fmt.Println("Board");
for row := 0; row < squaresOnSide; row++ {
for column := 0; column < squaresOnSide; column++ {
if column > 0 {
fmt.Print(" ");
}
fmt.Print(fmt.Sprintf("%02d", board[row][column]))
}
fmt.Println("")
}
fmt.Println("")
}
func main() {
fmt.Println("Knight's Tour")
fmt.Println(fmt.Sprintf("%d x %d Board", squaresOnSide, squaresOnSide))
fmt.Println("")
// ask the user for the beginning board position, both row and column
fmt.Println("Choose a beginning square on the board.")
var row int = promptUser(fmt.Sprintf("Enter the row (1-%d): ", squaresOnSide), 1, squaresOnSide, fmt.Sprintf("Invalid row: You must enter a number between 1-%d inclusive.", squaresOnSide))
var column int = promptUser(fmt.Sprintf("Enter the column (1-%d): ", squaresOnSide), 1, squaresOnSide, fmt.Sprintf("Invalid column: You must enter a number between 1-%d inclusive.", squaresOnSide))
fmt.Println("")
// start calulating the solution based upon the user's beginning position
var start time.Time = time.Now()
calculateHeuristics()
solveBoard(row, column, 1)
// output the solution and duration it took to calculate
printBoard()
fmt.Println("Elapsed time (ms): ", time.Since(start))
}
| true |
af985c39d266e989728b3d0ebf90ef0bad8627e9
|
Go
|
nathanpaulyoung/dumb-wow-calc
|
/weights.go
|
UTF-8
| 3,072 | 3.28125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"io/ioutil"
"log"
"gopkg.in/yaml.v2"
)
type weight struct {
FileName string
Class string `yaml:"class"`
Role string `yaml:"role"`
TopEnd float32 `yaml:"top-end-dmg"`
DPS float32 `yaml:"dps"`
Strength float32 `yaml:"strength"`
Agility float32 `yaml:"agility"`
Intellect float32 `yaml:"intellect"`
Spirit float32 `yaml:"spirit"`
Mp5 float32 `yaml:"mp5"`
SpellDamage float32 `yaml:"spell-damage"`
SpellHealing float32 `yaml:"spell-healing"`
MeleeAttackPower float32 `yaml:"melee-attack-power"`
RangedAttackPower float32 `yaml:"ranged-attack-power"`
MeleeHit float32 `yaml:"melee-hit"`
RangedHit float32 `yaml:"ranged-hit"`
SpellHit float32 `yaml:"spell-hit"`
MeleeCrit float32 `yaml:"melee-crit"`
RangedCrit float32 `yaml:"ranged-crit"`
SpellCrit float32 `yaml:"spell-crit"`
}
type weights []*weight
func newWeight(file string) *weight {
weight := new(weight)
weight.FileName = file
return weight
}
func (w *weight) getWeightsFromFile() {
yamlFile, err := ioutil.ReadFile("weightfiles/" + w.FileName + ".yaml")
if err != nil {
log.Printf("Weight file not found: %v", err)
}
err = yaml.Unmarshal(yamlFile, &w)
if err != nil {
log.Fatalf("Unmarshal: %v", err)
}
}
func (ws weights) getWeightsByClass(class string) weights {
var out weights
for i := 0; i < len(ws); i++ {
if ws[i].Class == class {
out = append(out, ws[i])
}
}
return out
}
func (ws weights) getWeightsByRole(role string) weights {
var out weights
for i := 0; i < len(ws); i++ {
if ws[i].Role == role {
out = append(out, ws[i])
}
}
return out
}
func (ws weights) averageWeights() *weight {
w := newWeight("")
for i := 0; i < len(ws); i++ {
w.TopEnd += ws[i].TopEnd
w.DPS += ws[i].DPS
w.Strength += ws[i].Strength
w.Agility += ws[i].Agility
w.Intellect += ws[i].Intellect
w.Spirit += ws[i].Spirit
w.Mp5 += ws[i].Mp5
w.SpellDamage += ws[i].SpellDamage
w.SpellHealing += ws[i].SpellHealing
w.MeleeAttackPower += ws[i].MeleeAttackPower
w.RangedAttackPower += ws[i].RangedAttackPower
w.MeleeHit += ws[i].MeleeHit
w.RangedHit += ws[i].RangedHit
w.SpellHit += ws[i].SpellHit
w.MeleeCrit += ws[i].MeleeCrit
w.RangedCrit += ws[i].RangedCrit
w.SpellCrit += ws[i].SpellCrit
}
w.TopEnd /= float32(len(ws) + 1)
w.DPS /= float32(len(ws) + 1)
w.Strength /= float32(len(ws) + 1)
w.Agility /= float32(len(ws) + 1)
w.Intellect /= float32(len(ws) + 1)
w.Spirit /= float32(len(ws) + 1)
w.Mp5 /= float32(len(ws) + 1)
w.SpellDamage /= float32(len(ws) + 1)
w.SpellHealing /= float32(len(ws) + 1)
w.MeleeAttackPower /= float32(len(ws) + 1)
w.RangedAttackPower /= float32(len(ws) + 1)
w.MeleeHit /= float32(len(ws) + 1)
w.RangedHit /= float32(len(ws) + 1)
w.SpellHit /= float32(len(ws) + 1)
w.MeleeCrit /= float32(len(ws) + 1)
w.RangedCrit /= float32(len(ws) + 1)
w.SpellCrit /= float32(len(ws) + 1)
return w
}
| true |
33dfa8eb4d928591b50890b2c8677e438979d2fa
|
Go
|
image-server/image-server
|
/uploader/manta/manta.go
|
UTF-8
| 2,390 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package manta
import (
"io"
"log"
"os"
"path/filepath"
"github.com/golang/glog"
client "github.com/image-server/image-server/uploader/manta/client"
)
type MantaClient interface {
PutObject(destination string, contentType string, object io.Reader) error
PutDirectory(path string) error
}
type Uploader struct {
Client MantaClient
}
var (
MantaURL string
MantaUser string
MantaKeyID string
SDCIdentity string
)
func DefaultUploader() *Uploader {
c := client.DefaultClient()
return &Uploader{
Client: c,
}
}
func (u *Uploader) Upload(source string, destination string, contType string) error {
log.Println("About to Upload:", source)
fi, err := os.Open(source)
if err != nil {
glog.Infof("Manta::sentToManta unable to read file %s, %s", source, err)
return err
}
// content type should be set depending of the type of file uploaded
contentType := "application/octet-stream"
err = u.Client.PutObject(destination, contentType, fi)
if err != nil {
glog.Infof("Error uploading image to manta: %s", err)
} else {
glog.Infof("Uploaded file to manta: %s", destination)
}
return err
}
func (u *Uploader) CreateDirectory(dir string) error {
err := u.createDirectory(dir)
if err != nil {
// need to create sub directories
dir2 := filepath.Dir(dir)
dir3 := filepath.Dir(dir2)
dir4 := filepath.Dir(dir3)
dir5 := filepath.Dir(dir4)
err = u.createDirectory(dir5)
if err != nil {
return err
}
err = u.createDirectory(dir4)
if err != nil {
return err
}
err = u.createDirectory(dir3)
if err != nil {
return err
}
err = u.createDirectory(dir2)
if err != nil {
return err
}
err = u.createDirectory(dir)
if err != nil {
return err
}
}
return nil
}
func (u *Uploader) ListDirectory(directory string) ([]string, error) {
var names []string
return names, nil
}
func Initialize(baseDir string, url string, user string, keyID string, identityPath string) error {
u := DefaultUploader()
MantaURL = url
MantaUser = user
MantaKeyID = keyID
SDCIdentity = identityPath
client.Initialize(MantaURL, MantaUser, MantaKeyID, SDCIdentity)
return u.CreateDirectory(baseDir)
}
func (u *Uploader) createDirectory(path string) error {
if path == "." {
return nil
}
err := u.Client.PutDirectory(path)
if err != nil {
return err
}
glog.Infof("Created directory on manta: %s", path)
return nil
}
| true |
c6491175e25b79fa5fd7b1ffcdfd7c929f4ccf13
|
Go
|
shihyu/golang
|
/goWebActualCombat/chapter5/socket-rw-server1.go
|
UTF-8
| 988 | 3.21875 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
//++++++++++++++++++++++++++++++++++++++++
// 《Go Web编程实战派从入门到精通》源码
//++++++++++++++++++++++++++++++++++++++++
// Author:廖显东(ShirDon)
// Blog:https://www.shirdon.com/
// 仓库地址:https://gitee.com/shirdonl/goWebActualCombat
// 仓库地址:https://github.com/shirdonl/goWebActualCombat
//++++++++++++++++++++++++++++++++++++++++
package main
import (
"fmt"
"log"
"net"
)
func handle(c net.Conn) {
defer c.Close()
for {
var buf = make([]byte, 10)
log.Println("start to read from conn")
n, err := c.Read(buf)
if err != nil {
log.Println("conn read error:", err)
return
}
log.Printf("read %d bytes, the content is %s\n", n, string(buf[:n]))
}
}
func main() {
l, err := net.Listen("tcp", ":8058")
if err != nil {
fmt.Println("listen error:", err)
return
}
for {
c, err := l.Accept()
if err != nil {
fmt.Println("accept error:", err)
break
}
// 开启协程来处理连接
go handle(c)
}
}
| true |
3360f1e640a891fee00b3239d32aa73710cdb94f
|
Go
|
jatinjindal/Riscygo
|
/tests/src/tester.go
|
UTF-8
| 371 | 2.796875 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
func main()
type s struct{
a int;
b[5][5] int;
};
type t struct{
x[10] s;
};
func f( a[5]* int, b[5][5]int) {
b[1][2] = 10;
}
func main() {
var a[10][10]int;
var b[10][10]int;
var c[5]*int;
var y t;
var i int;
var fp *int;
y.x[3].b[1][2] = 4;
f(c,y.x[3].b);
printInt(y.x[3].b[1][2]);
}
| true |
837cad02987beefebc087a42104d76ca079b570a
|
Go
|
deverso/go-to-json
|
/main.go
|
UTF-8
| 791 | 3.15625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"encoding/json"
"log"
"net/http"
"text/template"
)
var tmpl = template.Must(template.ParseGlob("form/*"))
type Dog struct {
Breed string
WeightKg int
}
type Page struct {
Json string
Go string
}
func Index(w http.ResponseWriter, r *http.Request) {
d := Dog{
Breed: "dalmation",
WeightKg: 45,
}
b, _ := json.Marshal(d)
json := Page{Json: string(b)}
tmpl.ExecuteTemplate(w, "Index", json)
}
func main () {
log.Println("Server started on: http://localhost:8080")
http.HandleFunc("/", Index)
http.ListenAndServe(":8080", nil)
}
// type Dog struct {
// Breed string
// WeightKg int
// }
// func main() {
// d := Dog{
// Breed: "dalmation",
// WeightKg: 45,
// }
// b, _ := json.Marshal(d)
// fmt.Println(string(b))
// }
| true |
c11150722f81f0e9573766f4d5ef51f4b7ecd941
|
Go
|
yuzameOne/staticwebsite
|
/main.go
|
UTF-8
| 694 | 2.734375 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func HomeHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "static/index.html")
}
func main() {
fmt.Println("Server start ")
r := mux.NewRouter()
cssHandler := http.FileServer(http.Dir("./static/css/"))
imagesHandler := http.FileServer(http.Dir("./static/img/"))
jsHandler := http.FileServer(http.Dir("./static/js"))
http.Handle("/css/", http.StripPrefix("/css/", cssHandler))
http.Handle("/img/", http.StripPrefix("/img/", imagesHandler))
http.Handle("/js/", http.StripPrefix("/js/", jsHandler))
r.HandleFunc("/", HomeHandler)
http.Handle("/", r)
http.ListenAndServe(":8080", nil)
}
| true |
e758bc69a55af2492be3695edd4617fa1df7526e
|
Go
|
SezalAgrawal/GoProjects
|
/message-queue/rabbitmq/second_tutorial_work_queue/worker.go
|
UTF-8
| 2,684 | 3.21875 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
// It fakes a second of work for every dot in message body.
// Pops message form queue and performs the task
// If started multiple workers, they work in a round-robin dispatching way
// Thus, if there is a lot of backlog of works, one could deploy extra worker nodes,
// this will help in scaling. On average every consumer gets equal messages
import (
"bytes"
"log"
"time"
"github.com/streadway/amqp"
)
func main() {
url := "amqp://guest:guest@localhost:5672"
// connect to RabbitMQ instance
connection, err := amqp.Dial(url)
if err != nil {
panic("could not establish connection with RabbitMQ:" + err.Error())
}
defer connection.Close()
// create a channel from the connection. Use channels to communicate with the queues rather than the connection itself.
channel, err := connection.Channel()
if err != nil {
panic("could not open RabbitMQ channel:" + err.Error())
}
defer channel.Close()
// create queue. A message is published to a queue
// Queue is declared on both sender and receiver as we might start consumer before publisher
// and we want to make sure queue exists before we start consuming messages from it.
q, err := channel.QueueDeclare(
"task_queue",
true, // durable -> This tells that queue will survive rabbitMQ node restart
false,
false,
false,
nil,
)
if err != nil {
panic("error declaring the queue: " + err.Error())
}
// fair dispatch of messages
// here prefetch count 1 means that the queue would not send more than 1
// message to a worker. It will wait till it receives ack.
// This ensures that heavy and light tasks are efficiently distributed
err = channel.Qos(
1, // prefetch count
0, // prefetch size
false, // global
)
if err != nil {
panic("error sending Qos: " + err.Error())
}
// create a consumer to consume messages from channel
msgs, err := channel.Consume(
q.Name,
"",
false, // auto-ack set to false
false,
false,
false,
nil,
)
if err != nil {
panic("error registering a consumer:" + err.Error())
}
forever := make(chan bool)
go func() {
for msg := range msgs {
log.Printf("Received a message: %s", msg.Body)
dotCount := bytes.Count(msg.Body, []byte("."))
duration := time.Duration(dotCount)
time.Sleep(duration * time.Second)
log.Printf("done")
// For this auto-ack in channel is set to false
// when a consumer consumes a message it sends an ack
// back to the receiver, thereby deleting from the queue.
// If did not receive ack, then the message gets delivered using
// some other worker node
msg.Ack(false)
}
}()
log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
<-forever
}
| true |
0fbb60e0fac34944c20fbf0faade96915869e280
|
Go
|
hxfighting/over-blog
|
/back-end/Go/iris/helper/helper.go
|
UTF-8
| 4,029 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package helper
import (
"blog/config"
"errors"
"github.com/kataras/iris/v12"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
)
const (
YMDHIS = "2006-01-02 15:04:05"
YMD = "2006-01-02"
)
func GetCurrentDirectory() string {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal(err)
}
return strings.Replace(dir, "\\", "/", -1)
}
/**
验证电话号码
*/
func VerifyMobileFormat(mobileNum string) bool {
regular := "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$"
reg := regexp.MustCompile(regular)
return reg.MatchString(mobileNum)
}
/**
检查是否调试
*/
func CheckDebug() bool {
var res bool
var err error
debugStr := config.GetConfig("app.debug").(string)
if debugStr != "" {
res, err = strconv.ParseBool(debugStr)
if err != nil {
res = false
}
}
return res
}
/**
格式化时间戳
*/
func GetDateTime(unix int64, format string) string {
return time.Unix(unix, 0).Format(format)
}
/**
时间转时间戳
*/
func GetUnixTimeFromDate(date, format string) (int64, error) {
loc, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
return 0, errors.New("时区设置失败")
}
tt, err := time.ParseInLocation(format, date, loc)
if err != nil {
return 0, errors.New("时间转换失败!")
}
return tt.Unix(), nil
}
/**
获取post、put的json请求数据
*/
func GetRequestData(ctx iris.Context) (map[string]interface{}, error) {
var request interface{}
err := ctx.ReadJSON(&request)
if err != nil {
return map[string]interface{}{}, err
}
request_values, ok := request.(map[string]interface{})
if !ok {
return map[string]interface{}{}, errors.New("数据格式错误!")
}
return request_values, nil
}
/**
获取http请求结果
*/
func GetHttpResponse(http_url, method string, body io.Reader) ([]byte, string, error) {
res := []byte{}
request, e := http.NewRequest(method, http_url, body)
if e != nil {
return res, "", e
}
response, e := http.DefaultClient.Do(request)
if e != nil {
return res, "", e
}
defer response.Body.Close()
body_byte, e := ioutil.ReadAll(response.Body)
if e != nil {
return res, "", e
}
contentType := response.Header.Get("Content-Type")
return body_byte, contentType, nil
}
/**
获取今日23:59:59
*/
func GetTimeRemainingToday() (time.Time, error) {
loc, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
return time.Time{}, errors.New("时区设置失败")
}
tt, err := time.ParseInLocation(YMDHIS, time.Now().Format(YMD)+" 23:59:59", loc)
if err != nil {
return time.Time{}, errors.New("时间转换失败!")
}
return tt, nil
}
/**
获取两个日期相差多少天
dayFirst Y-m-d
dayLast Y-m-d
*/
func GetDateDiffDay(dayFirst, dayLast string) (int, error) {
loc, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
return 0, errors.New("时区设置失败")
}
tt, err := time.ParseInLocation(YMD, dayFirst, loc)
if err != nil {
return 0, errors.New("时间转换失败!")
}
tt_two, err := time.ParseInLocation(YMD, dayLast, loc)
if err != nil {
return 0, errors.New("时间转换失败!")
}
hours := tt_two.Sub(tt).Hours()
if hours <= 0 {
return 0, errors.New("时间错误")
}
if hours < 24 {
// may same day
t1y, t1m, t1d := tt.Date()
t2y, t2m, t2d := tt_two.Date()
isSameDay := (t1y == t2y && t1m == t2m && t1d == t2d)
if isSameDay {
return 0, errors.New("时间错误")
} else {
return 1, nil
}
} else {
if (hours/24)-float64(int(hours/24)) == 0 {
return int(hours / 24), nil
} else {
return int(hours/24) + 1, nil
}
}
}
/**
反转义html
*/
func DecodeHtml(str string) string {
var s = ""
if len(str) <= 0 {
return ""
}
s = strings.Replace(str, "&", "&", -1)
s = strings.Replace(s, "<", "<", -1)
s = strings.Replace(s, ">", ">", -1)
s = strings.Replace(s, "'", "'", -1)
s = strings.Replace(s, """, "\"", -1)
s = strings.Replace(s, "&huhu;", "\n", -1)
return s
}
| true |
c091873a62348cf49291476400c02b5958c1a104
|
Go
|
jfmorgenstern/fzb
|
/src/go/fzb.go
|
UTF-8
| 4,861 | 3.0625 | 3 |
[] |
no_license
|
[] |
no_license
|
package fzb
import (
"encoding/xml"
"errors"
"fmt"
"io/ioutil"
// "os"
"path/filepath"
"strings"
)
const (
MinimumInstances = 4
)
// the fritzing fzb format go utility
type Fzb struct {
XMLName xml.Name `xml:"module" json:"-" yaml:"-"`
Title string `xml:"title" json:"title" yaml:"title"`
Icon string `xml:"icon,attr" json:"icon" yaml:"icon"`
FritzingVersion string `xml:"fritzingVersion,attr" json:"fritzingVersion" yaml:"fritzingVersion"`
Instances []Instance `xml:"instances>instance" json:"instances" yaml:"instances"`
}
// NewFzb return a new Fzb object
func NewFzb() Fzb {
f := Fzb{}
f.Instances = make([]Instance, 0)
return f
}
// PrettyPrint the data to stdout
func (f *Fzb) PrettyPrint() {
fmt.Printf("Title = %q\n", f.Title)
fmt.Printf("Icon = %q\n", f.Icon)
fmt.Printf("FritzingVersion = %q\n", f.FritzingVersion)
totalInstances := f.TotalInstances()
for k, v := range f.Instances {
fmt.Printf("\nInstance %v of %v\n", k, totalInstances)
v.PrettyPrint()
}
}
// ReadFile read the given file and return a Fzb object
func ReadFile(src string) (Fzb, error) {
fzbBytes, err := ioutil.ReadFile(src)
if err != nil {
return Fzb{}, err
}
fzbData, err := UnmarshalXML(fzbBytes)
return fzbData, err
}
// type FzbDir map[string]Fzb
//
// func ReadDir() FzbDir {
// store := FzbDir{}
// return store
// }
func UnmarshalXML(src []byte) (Fzb, error) {
f := Fzb{}
err := xml.Unmarshal(src, &f)
return f, err
}
// MarshalXML return the marshaled data as byte array
func (f *Fzb) ParseXML() ([]byte, error) {
b, err := xml.MarshalIndent(f, "", " ")
return b, err
}
func (f *Fzb) TotalInstances() int {
return len(f.Instances)
}
func (f *Fzb) Validate(basepath string) (error, string) {
errMsg := ""
warnMsg := ""
if f.Title == "" {
errMsg += "ERROR > Missing Title\n"
}
if f.FritzingVersion == "" {
warnMsg += "WARN > Missing FritzingVersion\n"
}
// check if icon exist...
if f.Icon == "" {
warnMsg += "WARN > Missing Icon Path\n"
}
// check if icon is lowercase
if f.Icon != strings.ToLower(f.Icon) {
warnMsg += fmt.Sprintf("WARN > Icon Filename is not lowercase. %s\n", f.Icon)
}
iconExt := filepath.Ext(f.Icon)
if iconExt != ".png" {
warnMsg += fmt.Sprintf("WARN > Icon Extension not '.png' - %s\n", iconExt)
}
// check fi file exist / is file readable...
tmpPath := filepath.Join(basepath, f.Icon)
_, err := ioutil.ReadFile(tmpPath)
if err != nil {
errMsg += fmt.Sprintf("ERROR > Icon File %q - %s\n", f.Icon, err)
}
// fmt.Println("icon exist", tmpPath)
tmptotal := f.TotalInstances()
if tmptotal < MinimumInstances {
errMsg += fmt.Sprintf("ERROR > Minimum number of Instances must be 4! current %v\n", tmptotal)
}
// check if a instance file exist
// for _, v := range f.Instances {
// fmt.Println("PATH", v.Path)
// if v.Path != "" {
// instancePathExt := filepath.Ext(v.Path)
// // fmt.Println("instancePathExt", instancePathExt)
// if instancePathExt == "" {
// errMsg += "WARN > Instance Path has no .fzp extension - " + v.Path + "\n"
// } else if instancePathExt != ".fzp" {
// errMsg += "WARN > Instance Path is not a .fzp file. " + v.Path + "\n"
// } else if instancePathExt == ".fzp" {
// _, err := ioutil.ReadFile(v.Path)
// if err != nil {
// errMsg += "ERROR> file not found " + v.Path + "\n"
// }
// }
// }
// }
if errMsg != "" {
return errors.New(errMsg), warnMsg
}
return nil, warnMsg
}
// ValidateFile validate a .fzb file and print result to stdout
func ValidateFile(basepath, src string) string {
tmpReport := ""
// check if file is a fzb
if filepath.Ext(src) == ".fzb" {
fzbData, err := ReadFile(src)
if err != nil {
return fmt.Sprintf("ERROR> %q Read File: %s\n", src, err)
}
// fmt.Println("Validate Data...")
err, warn := fzbData.Validate(basepath)
if warn == "" && err == nil {
return ""
}
if warn != "" || err != nil {
tmpReport = fmt.Sprintf("\n===== @ %q\n", src)
}
if warn != "" {
tmpReport += warn
}
if err != nil {
tmpReport += err.Error()
}
}
return tmpReport
}
// ValidateDir validate all .fzb files at the given directory.
func ValidateDir(src string) string {
d, err := ioutil.ReadDir(src)
if err != nil {
fmt.Println(err)
return err.Error()
}
// totalFiles := len(d)
// fmt.Println("Total Files", totalFiles)
// fmt.Println("Start Validating files...")
tmpReport := ""
for _, v := range d {
tmpfilepath := src + "/" + v.Name()
// fmt.Println("tmpfilepath", tmpfilepath)
tmpReport += ValidateFile(src, tmpfilepath)
// err, _ =
// if err != nil {
// fmt.Println("\n", v.Name())
// fmt.Println(err)
// }
}
return tmpReport
}
| true |
e3f5c56a66e5b82c02452d6a651ad0c3ec6b12af
|
Go
|
rcholic/GoLang
|
/Workspace/src/github.com/rcholic/hello/varTest.go
|
UTF-8
| 257 | 3.15625 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
var c, python, java bool
var i, j = 1, -10
func main() {
k, m := 100, -20
fmt.Println(i, c, python, java)
if !c {
fmt.Println("c is false")
}
fmt.Printf("i = %d, j = %d\n", i, j)
fmt.Printf("k = %d, m = %d\n", k, m)
}
| true |
0063b023c0624362926596412c143bfe4e4db35e
|
Go
|
tychoish/grip
|
/send/interceptor_test.go
|
UTF-8
| 732 | 2.65625 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package send
import (
"testing"
"github.com/tychoish/grip/level"
"github.com/tychoish/grip/message"
)
func TestInterceptor(t *testing.T) {
base := MakeInternal()
base.SetName("test")
base.SetPriority(level.Debug)
var count int
filter := func(m message.Composer) { count++ }
icept := MakeFilter(base, filter)
if base.Len() != 0 {
t.Error("elements should be equal")
}
icept.Send(NewSimpleString(level.Info, "hello"))
if base.Len() != 1 {
t.Error("elements should be equal")
}
if count != 1 {
t.Error("elements should be equal")
}
icept.Send(NewSimpleString(level.Trace, "hello"))
if base.Len() != 2 {
t.Error("elements should be equal")
}
if count != 2 {
t.Error("elements should be equal")
}
}
| true |
a36f9da5343ff2596fb201f755a8869ee1fc0047
|
Go
|
phuslu/go-callprivate
|
/examples.go
|
UTF-8
| 607 | 3.234375 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"github.com/spance/go-callprivate/private"
"net/http"
"reflect"
"runtime"
)
type obj int
func (o *obj) private() {
fmt.Println("private func LOL.", runtime.GOOS, runtime.GOARCH)
}
func main() {
// example 1: Call *obj.private()
var o obj
method := reflect.ValueOf(&o).MethodByName("private")
private.SetAccessible(method)
method.Call(nil) // stdout ...
// example 2: Call http.Header.clone()
var h = http.Header{"k": {"v"}}
clone := reflect.ValueOf(h).MethodByName("clone")
private.SetAccessible(clone)
fmt.Println(clone.Call(nil)[0]) // stdout map[k:[v]]
}
| true |
2b4b129a3fcf74da3a5bc9e95e2259840717aed4
|
Go
|
naturalCloud/GoLearn
|
/concurrencyModels/quit.go
|
UTF-8
| 620 | 3.578125 | 4 |
[] |
no_license
|
[] |
no_license
|
package concurrencyModels
import (
"fmt"
"math/rand"
"time"
)
func boring(str string, quit chan string) (c chan string) {
c = make(chan string)
go func() {
for i := 0; ; i++ {
select {
case c <- fmt.Sprintf("%s: %d", str, i):
// do something
case <-quit:
// 退出前的清理动作
// clean up()
quit <- "well done"
return
}
}
}()
return
}
// RunQuit1 退出模式
func RunQuit1() {
quit := make(chan string)
c := boring("xiaoming", quit)
rand.Seed(time.Now().Unix())
for i := rand.Intn(10); i >= 0; i-- {
fmt.Println(<-c)
}
quit <- "bye"
fmt.Println(<-quit)
}
| true |
ff69df9ac4d048e2a9a2beb77ba11b9a3af31dfb
|
Go
|
tlsalstn/baekjoon
|
/step/stage6/go/main/nSum.go
|
UTF-8
| 273 | 3.625 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
w := bufio.NewWriter(os.Stdout)
defer w.Flush()
intArray := []int{1, 2, 3, 4, 5, 6}
fmt.Fprint(w, sum(intArray))
}
func sum(a []int) int {
sum := 0
for _, num := range a {
sum += num
}
return sum
}
| true |
17196451a2786255ef53428e81ed6f6acecead3e
|
Go
|
sunhailiang/blockChain_Study
|
/src/demo/day5/function/main.go
|
UTF-8
| 352 | 3.765625 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import(
"fmt"
)
type person struct{
gender string
name string
age int
score float32
}
//声明一个函数并只想person
func (p *person) init(gender string,name string,age int,score float32){
p.gender=gender
p.age=age
p.name=name
p.score=score
fmt.Println(p)
}
func main(){
var stu person
stu.init("man","harry",27,95)
}
| true |
87226bb9b7277616154872e3eb90a7789928bf6e
|
Go
|
tengge1/ShadowEditor
|
/utils/proto/main.go
|
UTF-8
| 628 | 2.734375 | 3 |
[
"MIT",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
[
"MIT",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
package main
import (
"log"
"example.com/proto/example"
"github.com/golang/protobuf/proto"
)
func main() {
test := &example.Test{
Label: proto.String("hello"),
Type: proto.Int32(17),
Reps: []int64{1, 2, 3},
}
data, err := proto.Marshal(test)
if err != nil {
log.Fatal("marshaling error: ", err)
}
newTest := &example.Test{}
err = proto.Unmarshal(data, newTest)
if err != nil {
log.Fatal("unmarshaling error: ", err)
}
// Now test and newTest contain the same data.
if test.GetLabel() != newTest.GetLabel() {
log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
}
// etc.
}
| true |
e5a74f2638dd56b73df71b9f8c508c265a0c9f8e
|
Go
|
John-Lin/ovs-cni
|
/ovs/backend/disk/backend.go
|
UTF-8
| 1,402 | 2.921875 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package disk
import (
"io/ioutil"
"os"
"path/filepath"
"strings"
)
const defaultDataDir = "/var/lib/cni/networks"
// Store is a simple disk-backed store that creates one file per network namespace
// container ID is a given filename. The contents of the file are the interface name for ovs.
type Store struct {
dataDir string
}
func New(network, dataDir string) (*Store, error) {
if dataDir == "" {
dataDir = defaultDataDir
}
dir := filepath.Join(dataDir, network)
if err := os.MkdirAll(dir, 0755); err != nil {
return nil, err
}
return &Store{dir}, nil
}
func (s *Store) Reserve(id, ovsIfaceName string) (bool, error) {
fname := strings.TrimSpace(id)
fpath := filepath.Join(s.dataDir, fname)
f, err := os.OpenFile(fpath, os.O_RDWR|os.O_EXCL|os.O_CREATE, 0644)
if os.IsExist(err) {
return false, nil
}
if err != nil {
return false, err
}
if _, err := f.WriteString(ovsIfaceName); err != nil {
f.Close()
os.Remove(f.Name())
return false, err
}
if err := f.Close(); err != nil {
os.Remove(f.Name())
return false, err
}
return true, nil
}
func (s *Store) ReleaseByID(id string) (string, error) {
fname := strings.TrimSpace(id)
fpath := filepath.Join(s.dataDir, fname)
data, err := ioutil.ReadFile(fpath)
if err != nil {
return "", err
}
if err := os.Remove(fpath); err != nil {
return "", err
}
return strings.TrimSpace(string(data)), nil
}
| true |
cc50178528cef360acb9b7a89fe4958cbc783363
|
Go
|
nerd010/goexamples
|
/db3/db3.go
|
UTF-8
| 1,141 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"database/sql"
t "tools"
_ "github.com/mattn/go-sqlite3"
)
func main() {
dbFileT := `c:\test\test.db`
if !t.FileExists(dbFileT) {
t.Printfln("数据库文件%v不存在", dbFileT)
return
}
// 打开已存在的库
dbT, errT := sql.Open("sqlite3", dbFileT)
if errT != nil {
t.Printfln("打开数据库时发生错误:%v", errT.Error())
return
}
defer dbT.Close()
// 查询表中所有符合条件的记录总数
var countT int64
errT = dbT.QueryRow("select count(*) from TEST").Scan(&countT)
if errT != nil {
t.Printfln("执行SQL查询语句时发生错误:%v", errT.Error())
return
}
t.Printfln("库表中共有%v条记录", countT)
// 删除库表
_, errT = dbT.Exec(`drop table TEST`)
if errT != nil {
t.Printfln("删除库表时发生错误:%v", errT.Error())
return
}
// 再次查询时会提示出错,因为库表已经被删除了
errT = dbT.QueryRow("select count(*) from TEST").Scan(&countT)
if errT != nil {
t.Printfln("执行SQL查询语句时发生错误:%v", errT.Error())
return
}
t.Printfln("库表中共有%v条记录", countT)
}
| true |
aecb1073a0edd11c536f084cbe4663b855120a16
|
Go
|
beatlabs/patron
|
/cache/redis/redis.go
|
UTF-8
| 1,736 | 3.046875 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
// Package redis contains the concrete implementation of a cache that supports TTL.
package redis
import (
"context"
"errors"
"time"
"github.com/beatlabs/patron/cache"
"github.com/beatlabs/patron/client/redis"
)
var _ cache.TTLCache = &Cache{}
// Cache encapsulates a Redis-based caching mechanism.
type Cache struct {
rdb redis.Client
}
// Options exposes the struct from go-redis package.
type Options redis.Options
// New creates a cache returns a new Redis client that will be used as the cache store.
func New(opt Options) (*Cache, error) {
redisDB := redis.New(redis.Options(opt))
return &Cache{rdb: redisDB}, nil
}
// Get executes a lookup and returns whether a key exists in the cache along with its value.
func (c *Cache) Get(ctx context.Context, key string) (interface{}, bool, error) {
res, err := c.rdb.Do(ctx, "get", key).Result()
if err != nil {
if errors.Is(err, redis.Nil) { // cache miss
return nil, false, nil
}
return nil, false, err
}
return res, true, nil
}
// Set registers a key-value pair to the cache.
func (c *Cache) Set(ctx context.Context, key string, value interface{}) error {
return c.rdb.Do(ctx, "set", key, value).Err()
}
// Purge evicts all keys present in the cache.
func (c *Cache) Purge(ctx context.Context) error {
return c.rdb.FlushAll(ctx).Err()
}
// Remove evicts a specific key from the cache.
func (c *Cache) Remove(ctx context.Context, key string) error {
return c.rdb.Do(ctx, "del", key).Err()
}
// SetTTL registers a key-value pair to the cache, specifying an expiry time.
func (c *Cache) SetTTL(ctx context.Context, key string, value interface{}, ttl time.Duration) error {
return c.rdb.Do(ctx, "set", key, value, "px", int(ttl.Milliseconds())).Err()
}
| true |
bd1b167ff4e2be6bc3f1287fb8df7ac5ae6d5bf5
|
Go
|
harman666666/StreetRep
|
/docs/algorithms/htn.go
|
UTF-8
| 151 | 2.6875 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
import "time"
func main() {
for i:=0;; i++ {
time.Sleep(time.Second);
fmt.Printf("User %d just joined!\n", i);
}
}
| true |
fb6884c58303fe9a4e8f8b0de6d1f8682b147ac6
|
Go
|
pallscall/way-jasy-cron
|
/common/util/time/time.go
|
UTF-8
| 182 | 2.609375 | 3 |
[] |
no_license
|
[] |
no_license
|
package time
import "time"
func Parse(t time.Time) time.Time {
parse, _ := time.Parse("2006-01-02 15:04:05", time.Unix(t.Unix(), 0).Format("2006-01-02 15:04:05"))
return parse
}
| true |
a17d37b6c2ff88cfac02075c3d2e7a26a1d305e2
|
Go
|
poptip/ftc
|
/server.go
|
UTF-8
| 10,506 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
// Copyright (c) 2014, Markover Inc.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
// Source code and contact info at http://github.com/poptip/ftc
package ftc
import (
"encoding/json"
"expvar"
"fmt"
"io"
"net/http"
"strings"
"time"
"code.google.com/p/go.net/websocket"
"github.com/golang/glog"
)
var numClients = expvar.NewInt("num_clients")
const (
// Protocol error codes and mappings.
errorTransportUnknown = 0
errorUnknownSID = 1
errorBadHandshakeMethod = 2
errorBadRequest = 3
// Query parameters used in client requests.
paramTransport = "transport"
paramSessionID = "sid"
// Available transports.
transportWebSocket = "websocket"
transportPolling = "polling"
// The default time before closed connections are cleaned from
// the client pool.
clientReapTimeout = 5 * time.Second
)
var errorMessage = map[int]string{
errorTransportUnknown: "Transport unknown",
errorUnknownSID: "Session ID unknown",
errorBadHandshakeMethod: "Bad handshake method",
errorBadRequest: "Bad request",
}
var (
validTransports = map[string]bool{
transportWebSocket: true,
transportPolling: true,
}
validUpgrades = map[string]bool{
transportWebSocket: true,
}
)
// getValidUpgrades returns a slice containing the valid protocols
// that a connection can upgrade to.
func getValidUpgrades() []string {
upgrades := make([]string, len(validUpgrades))
i := 0
for u := range validUpgrades {
upgrades[i] = u
i++
}
return upgrades
}
// A Handler is called by the server when a connection is
// opened successfully.
type Handler func(*Conn)
type server struct {
// Handler handles an FTC connection.
Handler
basePath string
cookieName string
clients *clientSet // The set of connections (some may be closed).
wsServer *websocket.Server // The underlying WebSocket server.
}
// The defaults for options passed to the server.
const (
defaultBasePath = "/engine.io/"
defaultCookieName = "io"
)
// Options are the parameters passed to the server.
type Options struct {
// BasePath is the base URL path that the server handles requests for.
BasePath string
// CookieName is the name of the cookie set upon successful handshake.
CookieName string
}
// NewServer allocates and returns a new server with the given
// options and handler. If nil options are passed, the defaults
// specified in the constants above are used instead.
func NewServer(o *Options, h Handler) *server {
opts := Options{}
if o != nil {
opts = *o
}
if len(opts.BasePath) == 0 {
opts.BasePath = defaultBasePath
}
if len(opts.CookieName) == 0 {
opts.CookieName = defaultCookieName
}
s := &server{
Handler: h,
basePath: opts.BasePath,
cookieName: opts.CookieName,
clients: &clientSet{clients: map[string]*conn{}},
}
go s.startReaper()
s.wsServer = &websocket.Server{Handler: s.wsHandler}
return s
}
// startReaper continuously removes closed connections from the
// client set via the reap function.
func (s *server) startReaper() {
for {
if s.clients == nil {
glog.Fatal("server cannot have a nil client set")
}
s.clients.reap()
numClients.Set(int64(s.clients.len()))
time.Sleep(clientReapTimeout)
}
}
// handlePacket takes the given packet and writes the appropriate
// response to the given connection.
func (s *server) handlePacket(p packet, c *conn) error {
glog.Infof("handling packet type: %c, data: %s, upgraded: %t", p.typ, p.data, c.upgraded())
var encode func(packet) error
if c.upgraded() {
encode = newPacketEncoder(c).encode
} else {
encode = func(pkt packet) error {
return newPayloadEncoder(c).encode([]packet{pkt})
}
}
switch p.typ {
case packetTypePing:
return encode(packet{typ: packetTypePong, data: p.data})
case packetTypeMessage:
if c.pubConn != nil {
c.pubConn.onMessage(p.data)
}
case packetTypeClose:
c.Close()
}
return nil
}
// wsHandler continuously receives on the given WebSocket
// connection and delegates the packets received to the
// appropriate handler functions.
func (s *server) wsHandler(ws *websocket.Conn) {
// If the client initially attempts to connect directly using
// WebSocket transport, the session ID parameter will be empty.
// Otherwise, the connection with the given session ID will
// need to be upgraded.
glog.Infoln("Starting websocket handler...")
var c *conn
wsEncoder, wsDecoder := newPacketEncoder(ws), newPacketDecoder(ws)
for {
if c != nil {
var pkt packet
if err := wsDecoder.decode(&pkt); err != nil {
glog.Errorf("could not decode packet: %v", err)
break
}
glog.Infof("WS: got packet type: %c, data: %s", pkt.typ, pkt.data)
if pkt.typ == packetTypeUpgrade {
// Upgrade the connection to use this WebSocket Conn.
c.upgrade(ws)
continue
}
if err := s.handlePacket(pkt, c); err != nil {
glog.Errorf("could not handle packet: %v", err)
break
}
continue
}
id := ws.Request().FormValue(paramSessionID)
c = s.clients.get(id)
if len(id) > 0 && c == nil {
serverError(ws, errorUnknownSID)
break
} else if len(id) > 0 && c != nil {
// The initial handshake requires a ping (2) and pong (3) echo.
var pkt packet
if err := wsDecoder.decode(&pkt); err != nil {
glog.Errorf("could not decode packet: %v", err)
continue
}
glog.Infof("WS: got packet type: %c, data: %s", pkt.typ, pkt.data)
if pkt.typ == packetTypePing {
glog.Infof("got ping packet with data %s", pkt.data)
if err := wsEncoder.encode(packet{typ: packetTypePong, data: pkt.data}); err != nil {
glog.Errorf("could not encode pong packet: %v", err)
continue
}
// Force a polling cycle to ensure a fast upgrade.
glog.Infoln("forcing polling cycle")
payload := []packet{packet{typ: packetTypeNoop}}
if err := newPayloadEncoder(c).encode(payload); err != nil {
glog.Errorf("could not encode packet to force polling cycle: %v", err)
continue
}
}
} else if len(id) == 0 && c == nil {
// Create a new connection with this WebSocket Conn.
c = newConn()
c.ws = ws
s.clients.add(c)
b, err := handshakeData(c)
if err != nil {
glog.Errorf("could not get handshake data: %v", err)
}
if err := wsEncoder.encode(packet{typ: packetTypeOpen, data: b}); err != nil {
glog.Errorf("could not encode open packet: %v", err)
break
}
if s.Handler != nil {
go s.Handler(c.pubConn)
}
}
}
glog.Infof("closing websocket connection %p", ws)
c.Close()
}
// pollingHandler handles all XHR polling requests to the server, initiating
// a handshake if the request’s session ID does not already exist within
// the client set.
func (s *server) pollingHandler(w http.ResponseWriter, r *http.Request) {
setPollingHeaders(w, r)
id := r.FormValue(paramSessionID)
if len(id) > 0 {
c := s.clients.get(id)
if c == nil {
serverError(w, errorUnknownSID)
return
}
if r.Method == "POST" {
var payload []packet
if err := newPayloadDecoder(r.Body).decode(&payload); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer r.Body.Close()
for _, pkt := range payload {
s.handlePacket(pkt, c)
}
fmt.Fprintf(w, "ok")
return
} else if r.Method == "GET" {
glog.Infoln("GET request xhr polling data...")
// TODO(andybons): Requests can pile up, here. Drain the conn and
// then write the payload.
if _, err := io.Copy(w, c); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
return
}
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
s.pollingHandshake(w, r)
}
// pollingHandshake creates a new FTC Conn with the given HTTP Request and
// ResponseWriter, setting a persistence cookie if necessary and calling
// the server’s Handler.
func (s *server) pollingHandshake(w http.ResponseWriter, r *http.Request) {
c := newConn()
s.clients.add(c)
if len(s.cookieName) > 0 {
http.SetCookie(w, &http.Cookie{
Name: s.cookieName,
Value: c.id,
})
}
b, err := handshakeData(c)
if err != nil {
glog.Errorf("could not get handshake data: %v", err)
}
payload := []packet{packet{typ: packetTypeOpen, data: b}}
if err := newPayloadEncoder(w).encode(payload); err != nil {
glog.Errorf("could not encode open payload: %v", err)
return
}
if s.Handler != nil {
go s.Handler(c.pubConn)
}
}
// ServeHTTP implements the http.Handler interface for an FTC Server.
func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
remoteAddr := r.Header.Get("X-Forwarded-For")
if len(remoteAddr) == 0 {
remoteAddr = r.RemoteAddr
}
glog.Infof("%s (%s) %s %s %s", r.Proto, r.Header.Get("X-Forwarded-Proto"), r.Method, remoteAddr, r.URL)
transport := r.FormValue(paramTransport)
if strings.HasPrefix(r.URL.Path, s.basePath) && !validTransports[transport] {
serverError(w, errorTransportUnknown)
return
}
if transport == transportWebSocket {
s.wsServer.ServeHTTP(w, r)
} else if transport == transportPolling {
s.pollingHandler(w, r)
}
}
// handshakeData returns the JSON encoded data needed
// for the initial connection handshake.
func handshakeData(c *conn) ([]byte, error) {
return json.Marshal(map[string]interface{}{
"pingInterval": 25000,
"pingTimeout": 60000,
"upgrades": getValidUpgrades(),
"sid": c.id,
})
}
// serverError sends a JSON-encoded message to the given io.Writer
// with the given error code.
func serverError(w io.Writer, code int) {
if rw, ok := w.(http.ResponseWriter); ok {
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(http.StatusBadRequest)
}
msg := struct {
Code int `json:"code"`
Message string `json:"message"`
}{
Code: code,
Message: errorMessage[code],
}
if err := json.NewEncoder(w).Encode(msg); err != nil {
glog.Errorln("error encoding error msg %+v: %s", msg, err)
return
}
glog.Errorf("wrote server error: %+v", msg)
}
// setPollingHeaders sets the appropriate headers when responding
// to an XHR polling request.
func setPollingHeaders(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if len(origin) > 0 {
w.Header().Set("Access-Control-Allow-Credentials", "true")
} else {
origin = "*"
}
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Content-Type", "text/plain; charset=UTF-8")
}
| true |
845c1a43c613d36789676188437c35bf7c761226
|
Go
|
dochui/blockSelf
|
/chaincode/paylog/paylog.go
|
UTF-8
| 3,859 | 2.71875 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"github.com/hyperledger/fabric/core/chaincode/shim"
"github.com/hyperledger/fabric/protos/peer"
"encoding/json"
"bytes"
)
// Define the Smart Contract structure
type SmartContract struct {
}
// Define the car structure, with 4 properties. Structure tags are used by encoding/json library
type PayLog struct {
EntryAmount float64 `json:"entryAmount"`
EntryDate string `json:"entryDate"`
LoanNumber string `json:"loanNumber"`
Period int `json:"period"`
RepayFlag string `json:"repayFlag"`
TransactionCost float64 `json:"transactionCost"`
TransactionDate string `json:"transactionDate"`
TransactionInterest float64 `json:"transactionInterest"`
TransactionPenalty float64 `json:"transactionPenalty"`
TransactionPrincipal float64 `json:"transactionPrincipal"`
TransactionSerialNo string `json:"transactionSerialNo"`
}
func (s *SmartContract) Init(APIStub shim.ChaincodeStubInterface) peer.Response {
return shim.Success(nil)
}
func (s *SmartContract) Invoke(APIStub shim.ChaincodeStubInterface) peer.Response {
// Retrieve the requested Smart Contract function and arguments
function, args := APIStub.GetFunctionAndParameters()
// Route to the appropriate handler function to interact with the ledger appropriately
if function == "insert" {
return s.insert(APIStub, args)
} else if function == "query" {
return s.query(APIStub, args)
}
return shim.Error("Invalid Smart Contract function name.")
}
func (s *SmartContract) insert(APIStub shim.ChaincodeStubInterface, args []string) peer.Response {
if len(args) != 1 {
return shim.Error("Incorrect number of arguments. Expecting 1")
}
var payLog PayLog
payLogBytes := []byte(args[0])
err := json.Unmarshal(payLogBytes, &payLog)
if err != nil {
return shim.Error(fmt.Sprintf("json unmarshal failed because: %s", err.Error()))
}
err = APIStub.PutState(payLog.TransactionSerialNo, payLogBytes)
if err != nil {
return shim.Error(err.Error())
}
compositeKey3, _ := APIStub.CreateCompositeKey("payLogDate", []string{payLog.TransactionDate, payLog.TransactionSerialNo})
err = APIStub.PutState(compositeKey3, payLogBytes)
if err != nil {
return shim.Error(err.Error())
}
compositeKey4, _ := APIStub.CreateCompositeKey("payLog", []string{payLog.LoanNumber, payLog.TransactionSerialNo})
err = APIStub.PutState(compositeKey4, payLogBytes)
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
}
func (s *SmartContract) query(APIStub shim.ChaincodeStubInterface, args []string) peer.Response {
if len(args) != 3 {
return shim.Error("Incorrect number of arguments. Expecting 2")
}
var buf bytes.Buffer
buf.WriteString("[")
if args[0] == "" {
if args[1] == "" {
rqi, _ := APIStub.GetStateByPartialCompositeKey("payLogDate", []string{args[2]})
for rqi.HasNext() {
response, err := rqi.Next()
if err == nil {
buf.Write(response.Value)
if rqi.HasNext() {
buf.WriteString(",")
}
}
}
buf.WriteString("]")
return shim.Success(buf.Bytes())
} else {
rqi, _ := APIStub.GetStateByPartialCompositeKey("payLog", []string{args[1]})
for rqi.HasNext() {
response, err := rqi.Next()
if err == nil {
buf.Write(response.Value)
if rqi.HasNext() {
buf.WriteString(",")
}
}
}
buf.WriteString("]")
return shim.Success(buf.Bytes())
}
} else {
results, err := APIStub.GetState(args[0])
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(results)
}
}
// The main function is only relevant in unit test mode. Only included here for completeness.
func main() {
// Create a new Smart Contract
err := shim.Start(new(SmartContract))
if err != nil {
fmt.Printf("Error creating new Smart Contract: %s", err)
}
}
| true |
cae465fd206cec7a7bfab513b5fe6ce45d703b2c
|
Go
|
laonsx/gamelib
|
/graceful/graceful.go
|
UTF-8
| 2,806 | 2.796875 | 3 |
[] |
no_license
|
[] |
no_license
|
// +build !windows
package graceful
import (
"context"
"errors"
"flag"
"log"
"net"
"net/http"
"os"
"os/exec"
"os/signal"
"syscall"
"time"
)
var (
server *http.Server
listener net.Listener
graceful bool
)
func init() {
flag.BoolVar(&graceful, "graceful", false, "graceful")
}
func reload(listener net.Listener) error {
tl, ok := listener.(*net.TCPListener)
if !ok {
return errors.New("listener is not tcp listener")
}
f, err := tl.File()
if err != nil {
return err
}
args := os.Args[1:]
if !contains(args, "--graceful=true") {
args = append(args, "--graceful=true")
}
cmd := exec.Command(os.Args[0], args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.ExtraFiles = []*os.File{f}
return cmd.Start()
}
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func signalHandler(server *http.Server, listener net.Listener) {
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM, syscall.SIGUSR2)
for {
sig := <-ch
log.Println("[info] Signal received", "pid[", os.Getpid(), "] signal[", sig, "]")
ctx, _ := context.WithTimeout(context.Background(), 20*time.Second)
switch sig {
case syscall.SIGINT, syscall.SIGTERM:
log.Println("[warn] SignalHandler stop", "pid[", os.Getpid(), "] signal[", sig, "]")
signal.Stop(ch)
_ = server.Shutdown(ctx)
log.Println("[warn] SignalHandler graceful shutdown", "pid[", os.Getpid(), "] signal[", sig, "]")
return
case syscall.SIGUSR2:
log.Println("[warn] SignalHandler reload", "pid[", os.Getpid(), "] signal[", sig, "]")
err := reload(listener)
if err != nil {
log.Println("[error] SignalHandler graceful failed", "pid[", os.Getpid(), "] signal[", sig, "] error[", err, "]")
}
_ = server.Shutdown(ctx)
log.Println("[warn] SignalHandler graceful reload", "pid[", os.Getpid(), "] signal[", sig, "]")
return
}
}
}
func ListenAndServe(addr string, handler http.Handler) {
server = &http.Server{
Addr: addr,
Handler: handler,
}
var err error
if graceful {
log.Println("[info] Listening to existing file descriptor 3", "pid[", os.Getpid(), "] listen[", addr, "]")
f := os.NewFile(3, "")
listener, err = net.FileListener(f)
} else {
log.Println("[info] Listening on a new file descriptor", "pid[", os.Getpid(), "] listen[", addr, "]")
listener, err = net.Listen("tcp", server.Addr)
}
if err != nil {
log.Println("[error] listener error", "pid[", os.Getpid(), "] listen[", addr, "] error[", err, "]")
return
}
go func() {
err = server.Serve(listener)
if err != nil {
log.Println("[warn] server.Serve status", "pid[", os.Getpid(), "] listen[", addr, "] error[", err, "]")
}
}()
signalHandler(server, listener)
}
| true |
0ac2e63430426fbb2b8905591684e5ed2c6661f0
|
Go
|
qsock/qf
|
/store/ka/consumer.go
|
UTF-8
| 4,907 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package ka
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/Shopify/sarama"
"math/rand"
"sync"
)
type ConsumerConfig struct {
// broker的集群地址
Brokers []string `toml:"brokers"`
// topic 的名称
Topic string `toml:"topic"`
// 消费组名称
Group string `toml:"group"`
SASL struct {
Enable bool `toml:"enable"`
User string `toml:"user"`
Password string `toml:"password"`
} `toml:"sasl"`
// 多少个协程
Workers int `toml:"workers"`
// 是否从最老的开始消费
Oldest bool `toml:"oldest"`
}
func (c *ConsumerConfig) Check() bool {
if len(c.Topic) == 0 ||
len(c.Brokers) == 0 {
return false
}
if c.Group == "" {
c.Group = fmt.Sprintf("%s%.8x", gTestPrefix, rand.Int63())
}
if c.Workers == 0 {
c.Workers = 10
}
return true
}
func NewConsumer(cfg *ConsumerConfig) (*Consumer, error) {
return NewConsumerWithConfig(cfg, nil)
}
func NewConsumerWithInterceptor(cfg1 *ConsumerConfig, interceptor sarama.ConsumerInterceptor) (*Consumer, error) {
if !cfg1.Check() {
return nil, errors.New("config error")
}
cfg2 := sarama.NewConfig()
cfg2.Consumer.Return.Errors = true
cfg2.Version = GetVersion()
if cfg1.Oldest {
cfg2.Consumer.Offsets.Initial = sarama.OffsetOldest
} else {
cfg2.Consumer.Offsets.Initial = sarama.OffsetNewest
}
cfg2.Consumer.Interceptors = []sarama.ConsumerInterceptor{interceptor}
return NewConsumerWithConfig(cfg1, cfg2)
}
func NewConsumerWithConfig(cfg1 *ConsumerConfig, cfg2 *sarama.Config) (*Consumer, error) {
if !cfg1.Check() {
return nil, errors.New("config error")
}
if cfg2 == nil {
cfg2 = sarama.NewConfig()
cfg2.Consumer.Return.Errors = true
cfg2.Version = GetVersion()
if cfg1.Oldest {
cfg2.Consumer.Offsets.Initial = sarama.OffsetOldest
} else {
cfg2.Consumer.Offsets.Initial = sarama.OffsetNewest
}
if cfg1.SASL.Enable {
cfg2.Net.SASL.Enable = true
cfg2.Net.SASL.User = cfg1.SASL.User
cfg2.Net.SASL.Password = cfg1.SASL.Password
}
}
if err := cfg2.Validate(); err != nil {
return nil, err
}
// Start with a client
client, err := sarama.NewClient(cfg1.Brokers, cfg2)
if err != nil {
return nil, err
}
// Start a new consumer group
consumerGroup, err := sarama.NewConsumerGroupFromClient(cfg1.Group, client)
if err != nil {
return nil, err
}
c := new(Consumer)
c.cfg = cfg1
c.config = cfg2
c.group = consumerGroup
c.wg = &sync.WaitGroup{}
c.ctx, c.cancel = context.WithCancel(context.Background())
c.consumerHandlers = make(map[string]HandleConsumerFunc)
c.handlerLock = sync.RWMutex{}
return c, nil
}
type consumerGroupHandler struct {
consumer *Consumer
}
func (h consumerGroupHandler) getTopic() string {
return h.consumer.GetTopic()
}
func (consumerGroupHandler) Setup(_ sarama.ConsumerGroupSession) error { return nil }
func (consumerGroupHandler) Cleanup(_ sarama.ConsumerGroupSession) error { return nil }
func (h consumerGroupHandler) ConsumeClaim(sess sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {
for {
select {
case msg, ok := <-claim.Messages():
if !ok {
return nil
}
var err error
// 如果定义了需要原生接受的方法
if h.consumer.consumerMsgHandler != nil {
h.consumer.consumerMsgHandler(msg)
}
e := &Event{}
if ee := json.Unmarshal(msg.Value, e); ee != nil {
sess.MarkMessage(msg, gMsgDone)
continue
}
h.consumer.handlerLock.RLock()
handler, ok := h.consumer.consumerHandlers[e.Type]
h.consumer.handlerLock.RUnlock()
if ok {
if err = handler(e); err != nil {
// 如果标记了err,直接阻塞住,不让继续消费
return err
}
}
sess.MarkMessage(msg, gMsgDone)
}
}
}
func (c *Consumer) HandleError(e HandleErrorFunc) {
c.e = e
}
func (c *Consumer) GetTopic() string {
return c.cfg.Topic
}
func (c *Consumer) HandleEvent(eventType string, consumerFunc HandleConsumerFunc) {
c.handlerLock.Lock()
defer c.handlerLock.Unlock()
c.consumerHandlers[eventType] = consumerFunc
}
func (c *Consumer) HandleMsg(handler HandleConsumerMsgFunc) {
c.handlerLock.Lock()
defer c.handlerLock.Unlock()
c.consumerMsgHandler = handler
}
func (c *Consumer) Run() {
c.handlerLock.Lock()
defer c.handlerLock.Unlock()
if c.run {
return
}
go c.Handle()
for i := 0; i < c.cfg.Workers; i++ {
go c.Worker()
}
c.run = true
}
func (c *Consumer) Close() error {
c.cancel()
c.wg.Wait()
return c.group.Close()
}
func (c *Consumer) Worker() {
c.wg.Add(1)
defer c.wg.Done()
topics := []string{c.cfg.Topic}
handler := consumerGroupHandler{c}
for {
if err := c.group.Consume(c.ctx, topics, handler); err != nil {
if c.e != nil {
c.e(err)
}
}
if c.ctx.Err() != nil {
return
}
}
}
func (c *Consumer) Handle() {
for {
select {
case err, ok := <-c.group.Errors():
{
if !ok {
return
}
if c.e != nil {
c.e(err)
}
}
}
}
}
| true |
8d9ca4866fdf806f0e3073b6b0a3288e728bd061
|
Go
|
jasonrig/paypayopa-sdk-golang-example
|
/main.go
|
UTF-8
| 1,664 | 2.59375 | 3 |
[] |
no_license
|
[] |
no_license
|
package main
import (
"github.com/google/uuid"
"github.com/jasonrig/paypayopa-sdk-golang/api"
"github.com/jasonrig/paypayopa-sdk-golang/api/v2/codes"
"github.com/jasonrig/paypayopa-sdk-golang/request"
"log"
"net/http"
)
func main() {
// This will obtain credentials from your system environment
// Be sure to set PAYPAY_CLIENT_ID and PAYPAY_CLIENT_SECRET
auth, err := request.NewAuth(nil, nil)
if err != nil {
log.Panic(err)
}
// Define QR Code creation request parameters
paymentId, _ := uuid.NewRandom()
orderDescription := "This is your order description"
requestPayload := codes.PostPayload{
MerchantPaymentId: paymentId.String(),
Amount: api.Amount{
Amount: 100,
Currency: "JPY",
},
CodeType: "ORDER_QR",
OrderDescription: &orderDescription,
OrderItems: &[]api.OrderItems{
{
Name: "Fun thing",
UnitPrice: &api.Amount{
Amount: 50,
Currency: "JPY",
},
Quantity: 1,
},
{
Name: "Another fun thing",
UnitPrice: &api.Amount{
Amount: 50,
Currency: "JPY",
},
Quantity: 1,
},
},
}
// Set up the request
apiRequest := &codes.Post{
// Choose an execution environment
// - api.SandboxEnvironment
// - api.StagingEnvironment
// - api.ProductionEnvironment
Environment: api.SandboxEnvironment,
Payload: requestPayload,
}
// Execute the API request and collect the response
response := &codes.PostResponse{}
err = apiRequest.MakeRequest().Call(auth, &http.Client{}, response)
// Display the result
if err != nil {
log.Panicf("API call returned an error, %s", err)
} else {
log.Printf("QR Code URL: %s", *response.Url)
}
}
| true |
0d532bc8d0bc744864ffa1f2b952a66060047765
|
Go
|
superiqbal7/go-practice
|
/packages/utility/heheh.go
|
UTF-8
| 273 | 2.890625 | 3 |
[] |
no_license
|
[] |
no_license
|
package utility
// Hello hi
// a custom func to learn how to create package
func Hello() string {
return "hello from utility"
}
// Adder hi
// a custom func to learn how to create package
func Adder(args ...int) (sum int) {
for i := range args {
sum += i
}
return
}
| true |
dba7a54303e0034cbe9a18538983575ed0d9560b
|
Go
|
WoodsChoi/algorithm
|
/al/al-92.go
|
UTF-8
| 1,305 | 3.71875 | 4 |
[] |
no_license
|
[] |
no_license
|
// 反转链表 II
// medium
/*
* 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
*
* 说明:
* 1 ≤ m ≤ n ≤ 链表长度。
*
* 示例:
*
* 输入: 1->2->3->4->5->NULL, m = 2, n = 4
* 输出: 1->4->3->2->5->NULL
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*
* ---------------------------------------------------------
* 题解:
* 和整个链表翻转没区别,记好 p、q、t 仨指针的转移过程就好。
* 因为是部分翻转,所以需要一个头指针记录下起点,剩下的就是链表翻转了。注意判好起点终点完事。
*
*/
package main
func main() {
}
type ListNode struct {
Val int
Next *ListNode
}
func reverseBetween(head *ListNode, left int, right int) *ListNode {
if right-left == 0 {
return head
}
hair := &ListNode{0, head}
hair2 := hair
cnt := 1
var p, q, t *ListNode
for cnt < left {
hair2 = head
head = head.Next
cnt++
}
p = head
q = p.Next
if q != nil {
t = q.Next
}
head.Next = nil
for cnt < right {
q.Next = p
p = q
q = t
if t != nil {
t = t.Next
}
cnt++
}
hair2.Next = p
head.Next = q
return hair.Next
}
| true |
b878b8c0eb07bd89c08e773a2d2c3198b5300fb9
|
Go
|
luci/luci-go
|
/common/runtime/paniccatcher/catch.go
|
UTF-8
| 1,776 | 2.796875 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
// Copyright 2015 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package paniccatcher
import (
"runtime"
)
// The maximum stack buffer size (64K). This is the same value used by
// net.Conn's serve() method.
const maxStackBufferSize = (64 << 10)
// Panic is a snapshot of a panic, containing both the panic's reason and the
// system stack.
type Panic struct {
// Reason is the value supplied to the recover function.
Reason any
// Stack is a stack dump at the time of the panic.
Stack string
}
// Catch recovers from panic. It should be used as a deferred call.
//
// If the supplied panic callback is nil, the panic will be silently discarded.
// Otherwise, the callback will be invoked with the panic's information.
func Catch(cb func(p *Panic)) {
if reason := recover(); reason != nil && cb != nil {
stack := make([]byte, maxStackBufferSize)
count := runtime.Stack(stack, true)
cb(&Panic{
Reason: reason,
Stack: string(stack[:count]),
})
}
}
// Do executes f. If a panic occurs during execution, the supplied callback will
// be called with the panic's information.
//
// If the panic callback is nil, the panic will be caught and discarded silently.
func Do(f func(), cb func(p *Panic)) {
defer Catch(cb)
f()
}
| true |
03f57423c96bf471a3330f1ea16a6ceaf8a98fff
|
Go
|
maxshuang/diligent
|
/pkg/keygen/leveled_key_test.go
|
UTF-8
| 702 | 2.640625 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package keygen
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestLeveledStrKeys(t *testing.T) {
k1 := NewLeveledKey([]string{"A"}, "_")
assert.Equal(t, 1, k1.NumLevels())
assert.Equal(t, "A", k1.String())
assert.Equal(t, "A", k1.Prefix(0))
k2 := NewLeveledKey([]string{"A", "B"}, "_")
assert.Equal(t, 2, k2.NumLevels())
assert.Equal(t, "A_B", k2.String())
assert.Equal(t, "A", k2.Prefix(0))
assert.Equal(t, "A_B", k2.Prefix(1))
k3 := NewLeveledKey([]string{"A", "B", "C"}, "_")
assert.Equal(t, 3, k3.NumLevels())
assert.Equal(t, "A_B_C", k3.String())
assert.Equal(t, "A", k3.Prefix(0))
assert.Equal(t, "A_B", k3.Prefix(1))
assert.Equal(t, "A_B_C", k3.Prefix(2))
}
| true |
3e5db6479093df48d88251568b89396febdc5874
|
Go
|
aeolusheath/FrontExersize
|
/data-structure-algorithm/golang/21. Merge Two Sorted Lists.go
|
UTF-8
| 700 | 3.84375 | 4 |
[] |
no_license
|
[] |
no_license
|
/**
Merge two sorted linked lists and return it as a sorted list.
The list should be made by splicing together the nodes of the first two lists.
**/
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
head := &ListNode{}
pre := head
for l1 != nil && l2 != nil {
if l1.Val <= l2.Val {
head.Next = l1
l1 = l1.Next
}
else if l1.Val > l2.Val {
head.Next = l2
l2 = l2.Next
}
head = head.Next
}
for l1 != nil {
head.Next = l1
l1 = l1.Next
head = head.Next
}
for l2 != nil {
head.Next = l2
l2 = l2.Next
head = head.Next
}
return pre.Next
}
| true |
8dc14175bd81d9d0613a49b3ba579edcc5c7ff6e
|
Go
|
linuxdeepin/warm-sched
|
/vendor/src/github.com/BurntSushi/xgbutil/_examples/compress-events/main.go
|
UTF-8
| 6,877 | 2.96875 | 3 |
[
"WTFPL"
] |
permissive
|
[
"WTFPL"
] |
permissive
|
/*
Example compress-events shows how to manipulate the xevent package's event
queue to compress events that arrive more often than you'd like to process
them. This example in particular shows how to compress MotionNotify events,
but the same approach could be used to compress ConfigureNotify events.
Note that we show the difference between compressed and uncompressed
MotionNotify events by displaying two windows that listen for MotionNotify
events. The green window compresses them while the red window does not.
Hovering over each window will print the x and y positions in each
MotionNotify event received. You should notice that the red window
lags behind the pointer (particularly if you moved the pointer quickly in
and out of the window) while the green window always keeps up, regardless
of the speed of the pointer.
In each case, we simulate work by sleeping for some amount of time. (The
whole point of compressing events is that there is too much work to be done
for each event.)
Note that when compressing events, you should always make sure that the
event you're compressing *ought* to be compressed. For example, with
MotionNotify events, if the Event field changes, then it applies to a
different window and probably shouldn't be compressed with MotionNotify
events for other windows.
Finally, compressing events implicitly assumes that the event handler doing
the compression is the *only* event handler for a particular (event, window)
tuple. If there is more than one event handler for a single (event, window)
tuple and one of them does compression, the other will be left out in the
cold. (Since the main event loop is subverted and won't process the
compressed events in the usual way.)
N.B. This functionality isn't included in xgbutil because event compression
isn't something that is always desirable, and the conditions under which
compression happens can vary. In particular, compressing ConfigureRequest
events from the perspective of the window manager can be faulty, since
changes to other properties (like WM_NORMAL_HINTS) can change the semantics
of a ConfigureRequest event. (i.e., your compression would need to
specifically look for events that could change future ConfigureRequest
events.)
*/
package main
import (
"fmt"
"log"
"time"
"github.com/BurntSushi/xgb/xproto"
"github.com/BurntSushi/xgbutil"
"github.com/BurntSushi/xgbutil/xevent"
"github.com/BurntSushi/xgbutil/xwindow"
)
// workTime is the amount of time to sleep to simulate "work" in response to
// MotionNotify events. Increasing this will exacerbate the difference
// between the green and red windows. But if you increase it too much,
// the red window starts to *really* lag, and you'll probably have to kill
// the program.
var workTime = 50 * time.Millisecond
// newWindow creates a new window that listens to MotionNotify events with
// the given backgroundcolor.
func newWindow(X *xgbutil.XUtil, color uint32) *xwindow.Window {
win, err := xwindow.Generate(X)
if err != nil {
log.Fatal(err)
}
err = win.CreateChecked(X.RootWin(), 0, 0, 400, 400,
xproto.CwBackPixel|xproto.CwEventMask,
color, xproto.EventMaskPointerMotion)
if err != nil {
log.Fatal(err)
}
win.Map()
return win
}
// compressMotionNotify takes a MotionNotify event, and inspects the event
// queue for any future MotionNotify events that can be received without
// blocking. The most recent MotionNotify event is then returned.
// Note that we need to make sure that the Event, Child, Detail, State, Root
// and SameScreen fields are the same to ensure the same window/action is
// generating events. That is, we are only compressing the RootX, RootY,
// EventX and EventY fields.
// This function is not thread safe, since Peek returns a *copy* of the
// event queue---which could be out of date by the time we dequeue events.
func compressMotionNotify(X *xgbutil.XUtil,
ev xevent.MotionNotifyEvent) xevent.MotionNotifyEvent {
// We force a round trip request so that we make sure to read all
// available events.
X.Sync()
xevent.Read(X, false)
// The most recent MotionNotify event that we'll end up returning.
laste := ev
// Look through each event in the queue. If it's an event and it matches
// all the fields in 'ev' that are detailed above, then set it to 'laste'.
// In which case, we'll also dequeue the event, otherwise it will be
// processed twice!
// N.B. If our only goal was to find the most recent relevant MotionNotify
// event, we could traverse the event queue backwards and simply use
// the first MotionNotify we see. However, this could potentially leave
// other MotionNotify events in the queue, which we *don't* want to be
// processed. So we stride along and just pick off MotionNotify events
// until we don't see any more.
for i, ee := range xevent.Peek(X) {
if ee.Err != nil { // This is an error, skip it.
continue
}
// Use type assertion to make sure this is a MotionNotify event.
if mn, ok := ee.Event.(xproto.MotionNotifyEvent); ok {
// Now make sure all appropriate fields are equivalent.
if ev.Event == mn.Event && ev.Child == mn.Child &&
ev.Detail == mn.Detail && ev.State == mn.State &&
ev.Root == mn.Root && ev.SameScreen == mn.SameScreen {
// Set the most recent/valid motion notify event.
laste = xevent.MotionNotifyEvent{&mn}
// We cheat and use the stack semantics of defer to dequeue
// most recent motion notify events first, so that the indices
// don't become invalid. (If we dequeued oldest first, we'd
// have to account for all future events shifting to the left
// by one.)
defer func(i int) { xevent.DequeueAt(X, i) }(i)
}
}
}
// This isn't strictly necessary, but is correct. We should update
// xgbutil's sense of time with the most recent event processed.
// This is typically done in the main event loop, but since we are
// subverting the main event loop, we should take care of it.
X.TimeSet(laste.Time)
return laste
}
func main() {
X, err := xgbutil.NewConn()
if err != nil {
log.Fatal(err)
}
// Create window for receiving compressed MotionNotify events.
cwin := newWindow(X, 0x00ff00)
// Attach event handler for MotionNotify that compresses events.
xevent.MotionNotifyFun(
func(X *xgbutil.XUtil, ev xevent.MotionNotifyEvent) {
ev = compressMotionNotify(X, ev)
fmt.Printf("COMPRESSED: (EventX %d, EventY %d)\n",
ev.EventX, ev.EventY)
time.Sleep(workTime)
}).Connect(X, cwin.Id)
// Create window for receiving uncompressed MotionNotify events.
uwin := newWindow(X, 0xff0000)
// Attach event handler for MotionNotify that does not compress events.
xevent.MotionNotifyFun(
func(X *xgbutil.XUtil, ev xevent.MotionNotifyEvent) {
fmt.Printf("UNCOMPRESSED: (EventX %d, EventY %d)\n",
ev.EventX, ev.EventY)
time.Sleep(workTime)
}).Connect(X, uwin.Id)
xevent.Main(X)
}
| true |
88570e7c0b81433e4d73031c9f628dd1ca1f9de7
|
Go
|
emiddleton/zapi
|
/base.go
|
UTF-8
| 3,430 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package zapi
import (
"bytes"
"fmt"
"io/ioutil"
//"log"
"encoding/json"
"net/http"
"net/url"
//"strings"
"time"
)
type Client struct {
Url string `json:"url"`
Username string `json:"username"`
Password string `json:"password"`
Token string `json:"token"`
httpClient *http.Client `json:"-"`
}
func NewClientFromFile(path string) (client Client, err error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return client, err
}
if err := json.Unmarshal(data, &client); err != nil {
return client, err
}
client.httpClient = &http.Client{}
return client, err
}
func NewPasswordClient(url, username, password string) Client {
return Client{
Username: username,
Password: password,
httpClient: &http.Client{Transport: &http.Transport{}},
}
}
func NewTokenClient(url, username, token string) Client {
return Client{
Username: username,
Token: token,
httpClient: &http.Client{Transport: &http.Transport{}},
}
}
type Filter struct {
Key string
Value string
}
type Filters []Filter
func (filters Filters) toParams(vals *url.Values) *url.Values {
for _, filter := range filters {
vals.Add(filter.Key, filter.Value)
}
return vals
}
type Date time.Time
func (d *Date) MarshalJSON() ([]byte, error) {
t := time.Time(*d).Format(fmt.Sprintf("\"%s\"", time.RFC3339))
return []byte(t), nil
}
func (d *Date) UnmarshalJSON(b []byte) error {
t, err := time.Parse(fmt.Sprintf("\"%s\"", time.RFC3339), string(b))
if err != nil {
return err
}
*d = Date(t)
return nil
}
func (c *Client) Do(req *http.Request) ([]byte, error) {
req.Header.Add("Content-Type", "application/json")
if c.Token == "" {
req.SetBasicAuth(c.Username, c.Password)
} else {
req.SetBasicAuth(fmt.Sprintf("%s/token", c.Username), c.Token)
}
//fmt.Printf("%#v\n", req.URL)
//fmt.Printf("%#v\n", req)
resp, err := c.httpClient.Do(req)
//fmt.Printf("%#v\n", resp)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
func (client *Client) Get(path string, params *url.Values) ([]byte, error) {
urlPath := fmt.Sprintf("%s%s", client.Url, path)
urlRaw, err := url.Parse(urlPath)
if err != nil {
return nil, err
}
if params != nil {
urlRaw.RawQuery = params.Encode()
}
//fmt.Printf("%s\n", urlRaw.String())
req, err := http.NewRequest("GET", urlRaw.String(), nil)
if err != nil {
return nil, err
}
return client.Do(req)
}
func (client *Client) Put(path string, params *url.Values, requestBody []byte) ([]byte, error) {
urlPath := fmt.Sprintf("%s%s", client.Url, path)
urlRaw, err := url.Parse(urlPath)
if err != nil {
return nil, err
}
if params != nil {
urlRaw.RawQuery = params.Encode()
}
//fmt.Printf("%s\n", urlRaw.String())
req, err := http.NewRequest("PUT", urlRaw.String(), bytes.NewBufferString(string(requestBody)))
if err != nil {
return nil, err
}
return client.Do(req)
}
func (client *Client) Post(path string, params *url.Values, requestBody []byte) ([]byte, error) {
urlPath := fmt.Sprintf("%s%s", client.Url, path)
urlRaw, err := url.Parse(urlPath)
if err != nil {
return nil, err
}
if params != nil {
urlRaw.RawQuery = params.Encode()
}
//fmt.Printf("%s\n", urlRaw.String())
req, err := http.NewRequest("POST", urlRaw.String(), bytes.NewBufferString(string(requestBody)))
if err != nil {
return nil, err
}
return client.Do(req)
}
| true |
76c35bfe00a04f2bcf095570b12c10eecf144007
|
Go
|
fossabot/go-nimona
|
/dht/provider_response.go
|
UTF-8
| 1,623 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package dht
import (
"github.com/mitchellh/mapstructure"
"nimona.io/go/peers"
"nimona.io/go/primitives"
)
type ProviderResponse struct {
RequestID string `json:"requestID,omitempty"`
Providers []*Provider `json:"providers,omitempty"`
ClosestPeers []*peers.PeerInfo `json:"closestPeers,omitempty"`
Signature *primitives.Signature `json:"-"`
}
func (r *ProviderResponse) Block() *primitives.Block {
return &primitives.Block{
Type: "nimona.io/dht.provider.response",
Payload: map[string]interface{}{
"requestID": r.RequestID,
"providers": r.Providers,
"closestPeers": r.ClosestPeers,
},
Signature: r.Signature,
}
}
func (r *ProviderResponse) FromBlock(block *primitives.Block) {
t := &struct {
RequestID string `mapstructure:"requestID,omitempty"`
PeerInfo *primitives.Block `mapstructure:"peerInfo,omitempty"`
Providers []map[string]interface{} `mapstructure:"providers,omitempty"`
ClosestPeers []map[string]interface{} `mapstructure:"closestPeers,omitempty"`
}{}
mapstructure.Decode(block.Payload, t)
if len(t.Providers) > 0 {
r.Providers = []*Provider{}
for _, pb := range t.Providers {
pi := &Provider{}
pi.FromBlock(primitives.BlockFromMap(pb))
r.Providers = append(r.Providers, pi)
}
}
if len(t.ClosestPeers) > 0 {
r.ClosestPeers = []*peers.PeerInfo{}
for _, pb := range t.ClosestPeers {
pi := &peers.PeerInfo{}
pi.FromBlock(primitives.BlockFromMap(pb))
r.ClosestPeers = append(r.ClosestPeers, pi)
}
}
r.RequestID = t.RequestID
r.Signature = block.Signature
}
| true |
ffa2bbd388e1735a1ba11e3a14751fb5d2745661
|
Go
|
campoy/links
|
/step2/links/repository/repository.go
|
UTF-8
| 515 | 3.015625 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package repository
import "errors"
// A LinkRepository provides all the operations to create and store links.
type LinkRepository interface {
New(url string) (*Link, error)
Get(id string) (*Link, error)
CountVisit(id string) error
}
// A Link contains the information related to a shorten link.
type Link struct {
ID string `json:"id"`
URL string `json:"url"`
Count int `json:"count"`
}
// ErrNoSuchLink is returned when a given Link does not exist.
var ErrNoSuchLink = errors.New("no such link")
| true |
958dc909ea9cf7cf3544118ab5054a4eebd36f63
|
Go
|
lancelot-ru/golang-microservice
|
/golang-microservice/http-server.go
|
UTF-8
| 1,982 | 2.875 | 3 |
[] |
no_license
|
[] |
no_license
|
// http-server
package main
import (
"bytes"
"encoding/json"
"log"
"net/http"
)
func answerSystemsHTTP(url string, m Message) Message {
b, err := json.Marshal(m)
checkError(err, "marshalling")
log.Println(string(b))
req, err := http.NewRequest("POST", url, bytes.NewReader(b))
req.Header.Set("X-Custom-Header", "fromServer")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
checkError(err, "client")
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&m)
checkError(err, "decoding JSON")
defer resp.Body.Close()
return m
}
func handleJSON(rw http.ResponseWriter, request *http.Request) {
decoder := json.NewDecoder(request.Body)
var m Message
err := decoder.Decode(&m)
checkError(err, "decoding JSON")
if m.System == "A" {
fl := findAId(m.OperationID, m.Action)
if fl == 1 {
log.Println("Already in the table!")
m.System = "SRV"
m.OperationID = 0
m.Action = "Already in the table!"
} else if fl == 0 {
insertNewAction(m.OperationID, m.Action)
log.Println("Sending to B...")
m = answerSystemsHTTP("http://localhost:8083/b", m)
} else {
log.Println("Error!")
m.System = "SRV"
m.OperationID = 0
m.Action = "Error!"
}
showAllRows()
}
if m.System == "B" {
fl := updateBId(m.OperationID, m.Action, false)
log.Println("Sending to A...")
if fl == true {
log.Println("Success!")
m.System = "SRV"
m.OperationID = 0
m.Action = "Success!"
} else {
log.Println("Error!")
m.System = "SRV"
m.OperationID = 0
m.Action = "Error!"
}
showAllRows()
}
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(http.StatusCreated)
json.NewEncoder(rw).Encode(m)
}
func serveHTTP() {
log.Println("Staring HTTP Server..")
r := http.NewServeMux()
r.HandleFunc("/", handleJSON)
log.Fatal(http.ListenAndServe(":8080", r))
}
| true |
397f5f03157ad42a944f991cc2dbdf380c797faa
|
Go
|
stuart-warren/serveit
|
/router/router.go
|
UTF-8
| 2,794 | 3.265625 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package router
import (
"net/http"
"regexp"
"sync"
"github.com/stuart-warren/serveit/access"
)
type Route interface {
Match(path string) bool
Permit(permitted access.Permitted) Route
Permitted() access.Permitted
}
type textRoute struct {
path string
permitted access.Permitted
}
func NewTextRoute(path string) Route {
return textRoute{
path: path,
permitted: access.Permitted{},
}
}
func (t textRoute) Permit(permitted access.Permitted) Route {
t.permitted = permitted
return t
}
func (t textRoute) Permitted() access.Permitted {
return t.permitted
}
func (t textRoute) Match(path string) bool {
return path == t.path
}
func (t textRoute) String() string {
return t.path
}
type regexRoute struct {
pattern *regexp.Regexp
permitted access.Permitted
}
func NewRegexRoute(pattern *regexp.Regexp) Route {
return regexRoute{
pattern: pattern,
permitted: access.Permitted{},
}
}
func (x regexRoute) Permit(permitted access.Permitted) Route {
x.permitted = permitted
return x
}
func (x regexRoute) Permitted() access.Permitted {
return x.permitted
}
func (x regexRoute) Match(path string) bool {
return x.pattern.MatchString(path)
}
func (x regexRoute) String() string {
return x.pattern.String()
}
type prefixRoute struct {
prefix string
permitted access.Permitted
}
func NewPrefixRoute(prefix string) Route {
return prefixRoute{
prefix: prefix,
permitted: access.Permitted{},
}
}
func (p prefixRoute) Permit(permitted access.Permitted) Route {
p.permitted = permitted
return p
}
func (p prefixRoute) Permitted() access.Permitted {
return p.permitted
}
func (p prefixRoute) Match(path string) bool {
// strings.HasPrefix(s, prefix string) bool
return len(path) >= len(p.prefix) && path[0:len(p.prefix)] == p.prefix
}
func (p prefixRoute) String() string {
return p.prefix
}
type Router struct {
mu sync.RWMutex
routes []Route
handler http.Handler
authorized func(http.ResponseWriter, *http.Request, Route) bool
}
func NewRouter(handler http.Handler, authorized func(w http.ResponseWriter, r *http.Request, route Route) bool) *Router {
return &Router{
routes: []Route{},
handler: handler,
authorized: authorized,
}
}
func (o *Router) Reset() {
o.mu.Lock()
defer o.mu.Unlock()
o.routes = []Route{}
}
func (o *Router) Handle(route Route) {
o.mu.Lock()
defer o.mu.Unlock()
o.routes = append(o.routes, route)
}
func (o *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for _, route := range o.routes {
if route.Match(r.URL.Path) {
if o.authorized(w, r, route) {
o.handler.ServeHTTP(w, r)
return
} else {
http.Error(w, "403 Forbidden", http.StatusForbidden)
return
}
}
}
http.Error(w, "404 page not found", http.StatusNotFound)
}
| true |
c5de7cbd5a3efedd51b34635bf958a0b12a601cb
|
Go
|
gyliu513/liqo
|
/pkg/liqonet/ipam.go
|
UTF-8
| 17,959 | 2.65625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
package liqonet
import (
"fmt"
"strings"
"k8s.io/client-go/dynamic"
"k8s.io/kubernetes/pkg/util/slice"
goipam "github.com/metal-stack/go-ipam"
"inet.af/netaddr"
"k8s.io/klog"
)
/* IPAM Interface */
type Ipam interface {
GetSubnetPerCluster(network, clusterID string) (string, error)
FreeSubnetPerCluster(clusterID string) error
AcquireReservedSubnet(network string) error
FreeReservedSubnet(network string) error
AddNetworkPool(network string) error
RemoveNetworkPool(network string) error
}
/* IPAM implementation */
type IPAM struct {
ipam goipam.Ipamer
ipamStorage IpamStorage
}
/* NewIPAM returns a IPAM instance */
func NewIPAM() *IPAM {
return &IPAM{}
}
/* Constant slice containing private IPv4 networks */
var Pools = []string{
"10.0.0.0/8",
"192.168.0.0/16",
"172.16.0.0/12",
}
/* Init uses the Ipam resource to retrieve and allocate reserved networks */
func (liqoIPAM *IPAM) Init(pools []string, dynClient dynamic.Interface) error {
var err error
// Set up storage
liqoIPAM.ipamStorage, err = NewIPAMStorage(dynClient)
if err != nil {
return fmt.Errorf("cannot set up storage for ipam:%w", err)
}
liqoIPAM.ipam = goipam.NewWithStorage(liqoIPAM.ipamStorage)
// Get resource
ipamPools, err := liqoIPAM.ipamStorage.getPools()
if err != nil {
return fmt.Errorf("cannot get Ipam config: %w", err)
}
// Have network pools been already set? If not, take them from caller
if len(ipamPools) == 0 {
for _, network := range pools {
if _, err := liqoIPAM.ipam.NewPrefix(network); err != nil {
return fmt.Errorf("failed to create a new prefix for network %s", network)
}
ipamPools = append(ipamPools, network)
klog.Infof("Pool %s has been successfully added to the pool list", network)
}
err = liqoIPAM.ipamStorage.updatePools(ipamPools)
if err != nil {
return fmt.Errorf("cannot set pools: %w", err)
}
}
return nil
}
// reservePoolInHalves handles the special case in which a network pool has to be entirely reserved
// Since AcquireSpecificChildPrefix would return an error, reservePoolInHalves acquires the two
// halves of the network pool
func (liqoIPAM *IPAM) reservePoolInHalves(pool string) error {
klog.Infof("Network %s is equal to a network pool, acquiring first half..", pool)
mask, err := GetMask(pool)
if err != nil {
return fmt.Errorf("cannot retrieve mask lenght from cidr:%w", err)
}
mask += 1
_, err = liqoIPAM.ipam.AcquireChildPrefix(pool, mask)
if err != nil {
return fmt.Errorf("cannot acquire first half of pool %s", pool)
}
klog.Infof("Acquiring second half..")
_, err = liqoIPAM.ipam.AcquireChildPrefix(pool, mask)
if err != nil {
return fmt.Errorf("cannot acquire second half of pool %s", pool)
}
klog.Infof("Network %s has successfully been reserved", pool)
return nil
}
/* AcquireReservedNetwork marks as used the network received as parameter */
func (liqoIPAM *IPAM) AcquireReservedSubnet(reservedNetwork string) error {
klog.Infof("Request to reserve network %s has been received", reservedNetwork)
klog.Infof("Checking if network %s overlaps with any cluster network", reservedNetwork)
cluster, overlaps, err := liqoIPAM.overlapsWithCluster(reservedNetwork)
if err != nil {
return fmt.Errorf("cannot acquire network %s:%w", reservedNetwork, err)
}
if overlaps {
return fmt.Errorf("network %s cannot be reserved because it overlaps with network of cluster %s", reservedNetwork, cluster)
}
klog.Infof("Network %s does not overlap with any cluster network", reservedNetwork)
klog.Infof("Checking if network %s belongs to any pool", reservedNetwork)
pool, ok, err := liqoIPAM.getPoolFromNetwork(reservedNetwork)
if err != nil {
return err
}
if ok && reservedNetwork == pool {
return liqoIPAM.reservePoolInHalves(pool)
}
if ok && reservedNetwork != pool {
klog.Infof("Network %s is contained in pool %s", reservedNetwork, pool)
if _, err := liqoIPAM.ipam.AcquireSpecificChildPrefix(pool, reservedNetwork); err != nil {
return fmt.Errorf("cannot reserve network %s:%w", reservedNetwork, err)
}
klog.Infof("Network %s has successfully been reserved", reservedNetwork)
return nil
}
klog.Infof("Network %s is not contained in any pool", reservedNetwork)
if _, err := liqoIPAM.ipam.NewPrefix(reservedNetwork); err != nil {
return fmt.Errorf("cannot reserve network %s:%w", reservedNetwork, err)
}
klog.Infof("Network %s has successfully been reserved.", reservedNetwork)
return nil
}
func (liqoIPAM *IPAM) overlapsWithCluster(network string) (string, bool, error) {
// Get resource
clusterSubnets, err := liqoIPAM.ipamStorage.getClusterSubnet()
if err != nil {
return "", false, fmt.Errorf("cannot get Ipam config: %w", err)
}
for cluster, clusterSubnet := range clusterSubnets {
if err := liqoIPAM.ipam.PrefixesOverlapping([]string{clusterSubnet}, []string{network}); err != nil {
//overlaps
return cluster, true, nil
}
}
return "", false, nil
}
func (liqoIPAM *IPAM) overlapsWithPool(network string) (string, bool, error) {
// Get resource
pools, err := liqoIPAM.ipamStorage.getPools()
if err != nil {
return "", false, fmt.Errorf("cannot get Ipam config: %w", err)
}
for _, pool := range pools {
if err := liqoIPAM.ipam.PrefixesOverlapping([]string{pool}, []string{network}); err != nil {
//overlaps
return pool, true, nil
}
}
return "", false, nil
}
/* Function that receives a network as parameter and returns the pool to which this network belongs to. The second return parameter is a boolean: it is false if the network does not belong to any pool */
func (liqoIPAM *IPAM) getPoolFromNetwork(network string) (string, bool, error) {
var poolIPset netaddr.IPSetBuilder
// Get resource
pools, err := liqoIPAM.ipamStorage.getPools()
if err != nil {
return "", false, fmt.Errorf("cannot get Ipam config: %w", err)
}
// Build IPSet for new network
ipprefix, err := netaddr.ParseIPPrefix(network)
if err != nil {
return "", false, err
}
for _, pool := range pools {
// Build IPSet for pool
c, err := netaddr.ParseIPPrefix(pool)
if err != nil {
return "", false, err
}
poolIPset.AddPrefix(c)
// Check if the pool contains network
if poolIPset.IPSet().ContainsPrefix(ipprefix) {
return pool, true, nil
}
}
return "", false, nil
}
func (liqoIPAM *IPAM) clusterSubnetEqualToPool(pool, clusterID string) (string, error) {
klog.Infof("Network %s is equal to a pool, looking for a mapping..", pool)
mappedNetwork, err := liqoIPAM.mapNetwork(pool)
if err != nil {
klog.Infof("Mapping not found, acquiring the entire network pool..")
err = liqoIPAM.reservePoolInHalves(pool)
if err != nil {
return "", fmt.Errorf("cannot get any network for cluster %s", clusterID)
}
return pool, nil
}
return mappedNetwork, nil
}
/* GetSubnetPerCluster tries to reserve the network received as parameter for cluster clusterID. If it cannot allocate the network itself, GetSubnetPerCluster maps it to a new network. The network returned can be the original network, or the mapped network */
func (liqoIPAM *IPAM) GetSubnetPerCluster(network, clusterID string) (string, error) {
var mappedNetwork string
// Get resource
clusterSubnet, err := liqoIPAM.ipamStorage.getClusterSubnet()
if err != nil {
return "", fmt.Errorf("cannot get Ipam config: %w", err)
}
if value, ok := clusterSubnet[clusterID]; ok {
return value, nil
}
klog.Infof("Network %s allocation request for cluster %s", network, clusterID)
_, err = liqoIPAM.ipam.NewPrefix(network)
if err != nil && !strings.Contains(err.Error(), "overlaps") {
/* Overlapping is not considered an error in this context. */
return "", fmt.Errorf("cannot reserve network %s:%w", network, err)
}
if err == nil {
klog.Infof("Network %s successfully assigned for cluster %s", network, clusterID)
clusterSubnet[clusterID] = network
if err := liqoIPAM.ipamStorage.updateClusterSubnet(clusterSubnet); err != nil {
return "", err
}
return network, nil
}
/* Since NewPrefix failed, network belongs to a pool or it has been already reserved */
klog.Infof("Cannot allocate network %s, checking if it belongs to any pool...", network)
pool, ok, err := liqoIPAM.getPoolFromNetwork(network)
if err != nil {
return "", err
}
if ok && network == pool {
/* GetSubnetPerCluster could behave as AcquireReservedSubnet does in this condition, but in this case
is better to look first for a mapping rather than acquire the entire network pool.
Consider the impact of having a network pool n completely filled and multiple clusters asking for
networks in n. This would create the necessity of nat-ting the traffic towards these clusters. */
mappedNetwork, err = liqoIPAM.clusterSubnetEqualToPool(pool, clusterID)
if err != nil {
return "", err
}
klog.Infof("Network %s successfully mapped to network %s", mappedNetwork, network)
klog.Infof("Network %s successfully assigned to cluster %s", mappedNetwork, clusterID)
clusterSubnet[clusterID] = mappedNetwork
if err := liqoIPAM.ipamStorage.updateClusterSubnet(clusterSubnet); err != nil {
return "", err
}
return mappedNetwork, nil
}
if ok && network != pool {
klog.Infof("Network %s belongs to pool %s, trying to acquire it...", network, pool)
_, err := liqoIPAM.ipam.AcquireSpecificChildPrefix(pool, network)
if err != nil && !strings.Contains(err.Error(), "is not available") {
/* Uknown error, return */
return "", fmt.Errorf("cannot acquire prefix %s from prefix %s: %w", network, pool, err)
}
if err == nil {
klog.Infof("Network %s successfully assigned to cluster %s", network, clusterID)
clusterSubnet[clusterID] = network
if err := liqoIPAM.ipamStorage.updateClusterSubnet(clusterSubnet); err != nil {
return "", err
}
return network, nil
}
/* Network is not available, need a mapping */
klog.Infof("Cannot acquire network %s from pool %s", network, pool)
}
/* Network is already reserved, need a mapping */
klog.Infof("Looking for a mapping for network %s...", network)
mappedNetwork, err = liqoIPAM.mapNetwork(network)
if err != nil {
return "", fmt.Errorf("Cannot assign any network to cluster %s", clusterID)
}
klog.Infof("Network %s successfully mapped to network %s", mappedNetwork, network)
klog.Infof("Network %s successfully assigned to cluster %s", mappedNetwork, clusterID)
clusterSubnet[clusterID] = mappedNetwork
if err := liqoIPAM.ipamStorage.updateClusterSubnet(clusterSubnet); err != nil {
return "", err
}
return mappedNetwork, nil
}
// mapNetwork allocates a suitable (same mask length) network used to map the network received as first parameter which probably cannot be used due to some collision with existing networks
func (liqoIPAM *IPAM) mapNetwork(network string) (string, error) {
// Get resource
pools, err := liqoIPAM.ipamStorage.getPools()
if err != nil {
return "", fmt.Errorf("cannot get Ipam config: %w", err)
}
for _, pool := range pools {
mask, err := GetMask(network)
if err != nil {
return "", fmt.Errorf("cannot get mask from cidr:%w", err)
}
klog.Infof("Trying to acquire a child prefix from prefix %s (mask lenght=%d)", pool, mask)
if mappedNetwork, err := liqoIPAM.ipam.AcquireChildPrefix(pool, mask); err == nil {
klog.Infof("Network %s has been mapped to network %s", network, mappedNetwork)
return mappedNetwork.String(), nil
}
}
return "", fmt.Errorf("there are no more networks available")
}
func (liqoIPAM *IPAM) freePoolInHalves(pool string) error {
// Get halves mask length
mask, err := GetMask(pool)
if err != nil {
return fmt.Errorf("cannot retrieve mask lenght from cidr:%w", err)
}
mask += 1
// Get first half CIDR
halfCidr, err := SetMask(pool, mask)
if err != nil {
return err
}
klog.Infof("Network %s is equal to a network pool, freeing first half..", pool)
err = liqoIPAM.ipam.ReleaseChildPrefix(liqoIPAM.ipam.PrefixFrom(halfCidr))
if err != nil {
return fmt.Errorf("cannot free first half of pool %s", pool)
}
// Get second half CIDR
halfCidr, err = Next(halfCidr)
if err != nil {
return err
}
klog.Infof("Freeing second half..")
err = liqoIPAM.ipam.ReleaseChildPrefix(liqoIPAM.ipam.PrefixFrom(halfCidr))
if err != nil {
return fmt.Errorf("cannot free second half of pool %s", pool)
}
klog.Infof("Network %s has successfully been freed", pool)
return nil
}
/* FreeReservedSubnet marks as free a reserved subnet */
func (liqoIPAM *IPAM) FreeReservedSubnet(network string) error {
var p *goipam.Prefix
// Check existence
if p = liqoIPAM.ipam.PrefixFrom(network); p == nil {
return fmt.Errorf("network %s is already available", network)
}
// Check if it is equal to a network pool
pool, ok, err := liqoIPAM.getPoolFromNetwork(network)
if err != nil {
return err
}
if ok && pool == network {
return liqoIPAM.freePoolInHalves(pool)
}
// Try to release it as a child prefix
if err := liqoIPAM.ipam.ReleaseChildPrefix(p); err != nil {
klog.Infof("Cannot release subnet %s previously allocated from the pools", network)
// It is not a child prefix, then it is a parent prefix, so delete it
if _, err := liqoIPAM.ipam.DeletePrefix(network); err != nil {
klog.Errorf("Cannot delete prefix %s", network)
return fmt.Errorf("cannot remove subnet %s", network)
}
}
klog.Infof("Network %s has just been freed", network)
return nil
}
func (liqoIPAM *IPAM) deleteClusterSubnet(clusterID string, clusterSubnet map[string]string) error {
delete(clusterSubnet, clusterID)
if err := liqoIPAM.ipamStorage.updateClusterSubnet(clusterSubnet); err != nil {
return err
}
klog.Infof("Network assigned to cluster %s has just been freed", clusterID)
return nil
}
/* FreeSubnetPerCluster marks as free the network previously allocated for cluster clusterID */
func (liqoIPAM *IPAM) FreeSubnetPerCluster(clusterID string) error {
var subnet string
var ok bool
// Get resource
clusterSubnet, err := liqoIPAM.ipamStorage.getClusterSubnet()
if err != nil {
return fmt.Errorf("cannot get Ipam config: %w", err)
}
if subnet, ok = clusterSubnet[clusterID]; !ok {
//Network does not exists
return fmt.Errorf("network is not assigned to any cluster")
}
// Check if it is equal to a network pool
pool, ok, err := liqoIPAM.getPoolFromNetwork(subnet)
if err != nil {
return err
}
if ok && pool == subnet {
err := liqoIPAM.freePoolInHalves(pool)
if err != nil {
return err
}
return liqoIPAM.deleteClusterSubnet(clusterID, clusterSubnet)
}
if err := liqoIPAM.FreeReservedSubnet(subnet); err != nil {
return err
}
return liqoIPAM.deleteClusterSubnet(clusterID, clusterSubnet)
}
// AddNetworkPool adds a network to the set of network pools
func (liqoIPAM *IPAM) AddNetworkPool(network string) error {
// Get resource
ipamPools, err := liqoIPAM.ipamStorage.getPools()
if err != nil {
return fmt.Errorf("cannot get Ipam config: %w", err)
}
// Check overlapping with existing pools
// Either this and the following checks are carried out also within NewPrefix. Perform them here permits a more detailed error description.
pool, overlaps, err := liqoIPAM.overlapsWithPool(network)
if err != nil {
return fmt.Errorf("cannot establish if new network pool overlaps with existing network pools:%w", err)
}
if overlaps {
return fmt.Errorf("cannot add new network pool %s because it overlaps with existing network pool %s", network, pool)
}
// Check overlapping with cluster subnets
cluster, overlaps, err := liqoIPAM.overlapsWithCluster(network)
if err != nil {
return fmt.Errorf("cannot establish if new network pool overlaps with a reserved subnet:%w", err)
}
if overlaps {
return fmt.Errorf("cannot add network pool %s because it overlaps with network of cluster %s", network, cluster)
}
// Add network pool
_, err = liqoIPAM.ipam.NewPrefix(network)
if err != nil {
return fmt.Errorf("cannot add network pool %s:%w", network, err)
}
ipamPools = append(ipamPools, network)
klog.Infof("Network pool %s added to IPAM", network)
// Update configuration
err = liqoIPAM.ipamStorage.updatePools(ipamPools)
if err != nil {
return fmt.Errorf("cannot update Ipam configuration:%w", err)
}
return nil
}
// RemoveNetworkPool removes a network from the set of network pools
func (liqoIPAM *IPAM) RemoveNetworkPool(network string) error {
// Get resource
ipamPools, err := liqoIPAM.ipamStorage.getPools()
if err != nil {
return fmt.Errorf("cannot get Ipam config: %w", err)
}
// Get cluster subnets
clusterSubnet, err := liqoIPAM.ipamStorage.getClusterSubnet()
if err != nil {
return fmt.Errorf("cannot get cluster subnets: %w", err)
}
// Check existence
if exists := slice.ContainsString(ipamPools, network, nil); !exists {
return fmt.Errorf("network %s is not a network pool", network)
}
// Cannot remove a default one
if contains := slice.ContainsString(Pools, network, nil); contains {
return fmt.Errorf("cannot remove a default network pool")
}
// Check overlapping with cluster networks
cluster, overlaps, err := liqoIPAM.overlapsWithCluster(network)
if err != nil {
return fmt.Errorf("cannot check if network pool %s overlaps with cluster networks:%w", network, err)
}
if overlaps {
return fmt.Errorf("cannot remove network pool %s because it overlaps with network %s of cluster %s", network, clusterSubnet[cluster], cluster)
}
// Release it
_, err = liqoIPAM.ipam.DeletePrefix(network)
if err != nil {
return fmt.Errorf("cannot remove network pool %s:%w", network, err)
}
// Delete it
var i int
for index, value := range ipamPools {
if value == network {
i = index
break
}
}
if i == (len(ipamPools) - 1) {
ipamPools = ipamPools[:len(ipamPools)-1]
} else {
copy(ipamPools[i:], ipamPools[i+1:])
ipamPools = ipamPools[:len(ipamPools)-1]
}
err = liqoIPAM.ipamStorage.updatePools(ipamPools)
if err != nil {
return fmt.Errorf("cannot update Ipam configuration:%w", err)
}
klog.Infof("Network pool %s has just been removed", network)
return nil
}
| true |
729e4cdf9930c8a834580eac85827a170d8c3c27
|
Go
|
hieult1393/gobench
|
/master/monitor_test.go
|
UTF-8
| 568 | 3.21875 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
package master
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestMyUptime(t *testing.T) {
// Make sure we print this stuff right.
s := 22 * time.Second
m := 4 * time.Minute
h := 4 * time.Hour
d := 32 * 24 * time.Hour
y := 22 * 365 * 24 * time.Hour
var flagtests = []struct {
in time.Duration
out string
}{
{s, "22s"},
{m + s, "4m22s"},
{h + m + s, "4h4m22s"},
{d + h + m + s, "32d4h4m22s"},
{y + d + h + m + s, "22y32d4h4m22s"},
}
for _, tt := range flagtests {
assert.Equal(t, tt.out, myUptime(tt.in))
}
}
| true |
7a059b1db04f77b01b2ffe802d965dd559cac941
|
Go
|
nkostadinov/websocket
|
/server/client.go
|
UTF-8
| 2,657 | 3.0625 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package server
import (
"golang.org/x/net/websocket"
"log"
"encoding/json"
"io"
)
// Chat client.
type Client struct {
ws *websocket.Conn
server *Server
ch chan *Message
events chan *Event
done chan bool
channels []string
session string
}
// write channel buffer size
const channelBufSize = 1000
// Create new chat client.
func NewClient(ws *websocket.Conn, server *Server, session string) *Client {
if ws == nil {
panic("ws cannot be nil")
} else if server == nil {
panic("server cannot be nil")
}
ch := make(chan *Message, channelBufSize)
done := make(chan bool)
channels := make([]string, 0)
events := make(chan *Event)
return &Client{ws, server, ch, events, done, channels, session}
}
// Get websocket connection.
func (self *Client) Conn() *websocket.Conn {
return self.ws
}
// Get Write channel
func (self *Client) Write() chan <- *Message {
return (chan <- *Message)(self.ch)
}
// Get done channel.
func (self *Client) Done() chan <- bool {
return (chan <- bool)(self.done)
}
// Listen Write and Read request via chanel
func (self *Client) Listen() {
go self.listenWrite()
self.listenRead()
}
// Listen write request via chanel
func (self *Client) listenWrite() {
//log.Println("Listening write to client")
for {
select {
// send message to the client
case msg := <-self.ch:
log.Println("Send:", msg)
websocket.JSON.Send(self.ws, msg)
//receive event from client
case event := <-self.events:
log.Println("Event: ", event)
if(event.Event == "join") {
self.server.joinChannel(event.Data, self)
}
// receive done request
case <-self.done:
self.server.RemoveClient() <- self
for _, ch := range self.channels {
log.Println("removing from ", ch)
self.server.channels[ch].removeClient <- self
}
self.done <- true // for listenRead method
return
}
}
}
// Listen read request via chanel
func (self *Client) listenRead() {
//log.Println("Listening read from client")
for {
select {
// receive done request
case <-self.done:
self.server.RemoveClient() <- self
for _, ch := range self.channels {
log.Println("removing from ", ch)
self.server.channels[ch].removeClient <- self
}
self.done <- true // for listenWrite method
return
default:
var in []byte
if err := websocket.Message.Receive(self.ws, &in); err != nil {
if err == io.EOF {
self.done <- true
return
} else if err != nil {
panic(err)
}
}
log.Println("Recieved: ", string(in))
var event Event
if err := json.Unmarshal(in, &event); err != nil {
panic(err)
}
self.events <- &event
}
}
}
| true |
8287921aaa9ab05b12472a578b074514c7e5c08c
|
Go
|
Anuja2508/CabBooking
|
/routing/cab.go
|
UTF-8
| 2,816 | 2.90625 | 3 |
[] |
no_license
|
[] |
no_license
|
package routing
import (
"GoCab/controller"
"GoCab/model"
"errors"
"fmt"
"net/http"
"github.com/labstack/echo"
"github.com/labstack/gommon/log"
)
// Cab router
type Cab struct {
cabController controller.Cab
}
// NewCabRouter will create new cab router
func NewCabRouter(
cabController controller.Cab,
) Cab {
return Cab{
cabController: cabController,
}
}
// Register will create new routes
func (router Cab) Register(group *echo.Group) {
group.POST("/near-by-cab", router.nearBycab)
group.POST("/book-cab", router.bookCab)
group.POST("/booking-status", router.updatebookingStatus)
group.GET("/booking-history", router.historyOfBooking)
}
func (router Cab) nearBycab(context echo.Context) error {
type Request struct {
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
}
req := new(Request)
// bind request to context
if err := context.Bind(req); err != nil {
log.Error(err)
return errors.New("Invalid Request")
}
// create user in database
cabList, err := router.cabController.FindNearByCab(req.Latitude, req.Longitude)
if err != nil {
return err
}
// return response
return context.JSON(http.StatusOK, map[string]interface{}{
"Status": "success",
"cabList": cabList,
})
}
func (router Cab) bookCab(context echo.Context) error {
req := new(model.BookingRequest)
// bind request to context
if err := context.Bind(req); err != nil {
log.Error(err)
return errors.New("Invalid Request")
}
user := context.Get("User").(*model.User)
fmt.Println(user)
req.UserID = user.ID
// create user in database
err := router.cabController.BookCab(req)
if err != nil {
return err
}
// return response
return context.JSON(http.StatusOK, map[string]interface{}{
"Status": "success",
"Message": "cab is on the way to pick you",
})
}
func (router Cab) updatebookingStatus(context echo.Context) error {
type Request struct {
Status int `json:"status"`
BookingID uint `json:"booking_id"`
}
req := new(Request)
// bind request to context
if err := context.Bind(req); err != nil {
log.Error(err)
return errors.New("Invalid Request")
}
// create user in database
err := router.cabController.UpdateBookingStatus(req.Status, req.BookingID)
if err != nil {
return err
}
// return response
return context.JSON(http.StatusOK, map[string]interface{}{
"Status": "success",
"Message": "Your Booking status is updated",
})
}
func (router Cab) historyOfBooking(context echo.Context) error {
user := context.Get("User").(*model.User)
// create user in database
bookingList, err := router.cabController.HistoryOfBooking(user.ID)
if err != nil {
return err
}
// return response
return context.JSON(http.StatusOK, map[string]interface{}{
"Status": "success",
"BookingList": bookingList,
})
}
| true |
b07dc95dac4bc74c6187de07d796b5dc70838624
|
Go
|
pxsalehi/reconciler
|
/pkg/reconciler/instances/ory/db/db_test.go
|
UTF-8
| 5,039 | 2.53125 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package db
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
"k8s.io/apimachinery/pkg/types"
)
const (
postgresYaml = `
global:
postgresql:
postgresqlDatabase: db4hydra
postgresqlUsername: hydra
postgresqlPassword: secretpw
ory:
hydra:
persistence:
enabled: true
postgresql:
enabled: true`
gcloudYaml = `
global:
ory:
hydra:
persistence:
enabled: true
gcloud:
enabled: true
saJson: testsa
user: hydra
password: secretpw
dbUrl: ory-gcloud-sqlproxy.kyma-system:5432
dbName: db4hydra
dbType: postgres`
mysqlDBYaml = `
global:
ory:
hydra:
persistence:
enabled: true
gcloud:
enabled: false
user: hydra
password: secretpw
dbUrl: mydb.mynamespace:1234
dbName: db4hydra
dbType: mysql`
customDBYaml = `
global:
ory:
hydra:
persistence:
enabled: true
gcloud:
enabled: false
user: hydra
password: secretpw
dbUrl: mydb.mynamespace:1234
dbName: db4hydra
dbType: cockroach`
noDBYaml = `
global:
ory:
hydra:
persistence:
enabled: false`
wrongYaml = `
---
global:
oryt:
hydra:
persistence:
enabled: true
postgresql:
enabled: true`
)
func TestDBSecret(t *testing.T) {
t.Run("Deployment with Postgres SQL in cluster", func(t *testing.T) {
// given
t.Parallel()
name := types.NamespacedName{Name: "test-postgres-secret", Namespace: "test"}
values, err := unmarshalTestValues(postgresYaml)
require.NoError(t, err)
cfg, errNew := newDBConfig(values)
dsnExpected := cfg.preparePostgresDSN()
// when
secret, errGet := Get(name, values)
// then
require.NoError(t, errNew)
require.NoError(t, errGet)
assert.Equal(t, secret.StringData["postgresql-password"], "secretpw")
assert.Equal(t, secret.StringData["dsn"], dsnExpected)
})
t.Run("Deployment with GCloud SQL", func(t *testing.T) {
// given
t.Parallel()
name := types.NamespacedName{Name: "test-gcloud-secret", Namespace: "test"}
values, err := unmarshalTestValues(gcloudYaml)
require.NoError(t, err)
cfg, errNew := newDBConfig(values)
dsnExpected := cfg.prepareGenericDSN()
// when
secret, errGet := Get(name, values)
// then
require.NoError(t, errNew)
require.NoError(t, errGet)
assert.Equal(t, secret.StringData["dsn"], dsnExpected)
assert.Equal(t, secret.StringData["gcp-sa.json"], "testsa")
})
t.Run("Deployment with mysql DB", func(t *testing.T) {
// given
t.Parallel()
name := types.NamespacedName{Name: "test-mysqlDB-secret", Namespace: "test"}
values, err := unmarshalTestValues(mysqlDBYaml)
require.NoError(t, err)
cfg, errNew := newDBConfig(values)
dsnExpected := cfg.prepareMySQLDSN()
// when
secret, errGet := Get(name, values)
// then
require.NoError(t, errNew)
require.NoError(t, errGet)
assert.Equal(t, secret.StringData["dsn"], dsnExpected)
assert.Equal(t, secret.StringData["dbPassword"], "secretpw")
})
t.Run("Deployment with Custom DB", func(t *testing.T) {
// given
t.Parallel()
name := types.NamespacedName{Name: "test-customDB-secret", Namespace: "test"}
values, err := unmarshalTestValues(customDBYaml)
require.NoError(t, err)
cfg, errNew := newDBConfig(values)
dsnExpected := cfg.prepareGenericDSN()
// when
secret, errGet := Get(name, values)
// then
require.NoError(t, errNew)
require.NoError(t, errGet)
assert.Equal(t, secret.StringData["dsn"], dsnExpected)
assert.Equal(t, secret.StringData["dbPassword"], "secretpw")
})
t.Run("Deployment without database", func(t *testing.T) {
// given
t.Parallel()
name := types.NamespacedName{Name: "test-memory-secret", Namespace: "test"}
values, err := unmarshalTestValues(noDBYaml)
require.NoError(t, err)
// when
secret, err := Get(name, values)
// then
require.NoError(t, err)
assert.Equal(t, secret.StringData["dsn"], "memory")
})
t.Run("Deployment with yaml values error", func(t *testing.T) {
t.Parallel()
values, err := unmarshalTestValues(wrongYaml)
assert.Nil(t, values)
assert.Error(t, err)
})
}
func unmarshalTestValues(yamlValues string) (map[string]interface{}, error) {
var values map[string]interface{}
err := yaml.Unmarshal([]byte(yamlValues), &values)
if err != nil {
return nil, err
}
return values, nil
}
| true |
7efd319a80ba32eb149e3433f7cfb3ea5b13f170
|
Go
|
paulocsilvajr/controle_pessoal_de_financas
|
/API/v1/model/tipo_conta/tipo_conta.go
|
UTF-8
| 8,495 | 3.140625 | 3 |
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package tipo_conta
import (
"fmt"
"time"
"github.com/paulocsilvajr/controle_pessoal_de_financas/API/v1/helper"
"github.com/paulocsilvajr/controle_pessoal_de_financas/API/v1/model/erro"
)
// ITipoConta é uma interface que exige a implementação dos métodos obrigatórios em TipoConta
type ITipoConta interface {
String() string
Repr() string
VerificaAtributos() error
Altera(string, string, string) error
AlteraCampos(map[string]string) error
Ativa()
Inativa()
CorrigeData()
}
// TipoConta é uma struct que representa um tipo de conta. Possui notações JSON para cada campo e tem a composição da interface ITipoConta
type TipoConta struct {
Nome string `json:"nome" gorm:"primaryKey;size:50;not null"`
DescricaoDebito string `json:"descricao_debito" gorm:"size:20;not null"`
DescricaoCredito string `json:"descricao_credito" gorm:"size:20;not null"`
DataCriacao time.Time `json:"data_criacao" gorm:"not null;autoCreateTime"`
DataModificacao time.Time `json:"data_modificacao" gorm:"not null;autoUpdateTime"`
Estado bool `json:"estado" gorm:"not null;default:true"`
}
type TTipoConta TipoConta
func (TTipoConta) TableName() string {
return "tipo_conta"
}
// GetNomeTabelaTipoConta retorna o nome da tabela TipoConta
func GetNomeTabelaTipoConta() string {
return new(TTipoConta).TableName()
}
// MaxNome: tamanho máximo para o nome do tipo de conta
// MaxDescricao: tamanho máximo para as descrições de débito e crédito de tipo de conta
// MsgErroNome01: mensagem erro padrão 01 para nome
// MsgErroDescricao01: mensagem erro padrão 01 para descrição(débito)
// MsgErroDescricao02: mensagem erro padrão 02 para descrição(crédito)
const (
MaxNome = 50
MaxDescricao = 20
MsgErroNome01 = "Nome com tamanho inválido"
MsgErroDescricao01 = "Descrição do débito com tamanho inválido"
MsgErroDescricao02 = "Descrição do crédito com tamanho inválido"
)
// ITiposConta é uma interface que exige a implementação dos métodos ProcuraTipoConta e Len para representar um conjunto/lista(slice) de Tipos de Contas genéricas
type ITiposConta interface {
Len() int
ProcuraTipoConta(string) *TipoConta
}
// TiposConta representa um conjunto/lista(slice) de Tipos de Contas(*TipoConta)
type TiposConta []*TipoConta
// TTiposConta representa um conjunto/lista(slice) de Tipos de Contas de acordo com o GORM(*TTipoConta)
type TTiposConta []*TTipoConta
// New retorna uma novo Tipo de Conta(*TipoConta) através dos parâmetros informados(nome, descDebito e descCredito). Função equivalente a criação de um TipoConta via literal &TipoConta{Nome: ..., ...}. Data de criação e modificação são definidos como o horário atual e o estado é definido como ativo
func New(nome, descDebito, descCredito string) *TipoConta {
return &TipoConta{
Nome: nome,
DescricaoDebito: descDebito,
DescricaoCredito: descCredito,
DataCriacao: time.Now().Local(),
DataModificacao: time.Now().Local(),
Estado: true}
}
// NewTipoConta cria uma novo TipoConta semelhante a função New(), mas faz a validação dos campos informados nos parâmetros nome, descDebito e descCredito
func NewTipoConta(nome, descDebito, descCredito string) (tipoConta *TipoConta, err error) {
tipoConta = New(nome, descDebito, descCredito)
if err = tipoConta.VerificaAtributos(); err != nil {
tipoConta = nil
}
return
}
// GetTipoContaTest retorna um TipoConta teste usado para testes em geral
func GetTipoContaTest() (tipoConta *TipoConta) {
tipoConta = New("banco teste 01", "saque", "depósito")
tipoConta.DataCriacao = time.Date(2000, 2, 1, 12, 30, 0, 0, new(time.Location))
tipoConta.DataModificacao = time.Date(2000, 2, 1, 12, 30, 0, 0, new(time.Location))
tipoConta.Estado = true
return
}
// String retorna uma representação textual de um TipoConta. Datas são formatadas usando a função helper.DataFormatada() e campo estado é formatado usando a função helper.GetEstado()
func (t *TipoConta) String() string {
estado := helper.GetEstado(t.Estado)
dataCriacao := helper.DataFormatada(t.DataCriacao)
dataModificacao := helper.DataFormatada(t.DataModificacao)
return fmt.Sprintf("%s\t%s\t%s\t%s\t%s\t%s", t.Nome, t.DescricaoDebito, t.DescricaoCredito, dataCriacao, dataModificacao, estado)
}
// Repr é um método que retorna uma string da representação de um TipoConta, sem formatações especiais
func (t *TipoConta) Repr() string {
return fmt.Sprintf("%s\t%s\t%s\t%s\t%s\t%v", t.Nome, t.DescricaoDebito, t.DescricaoCredito, t.DataCriacao, t.DataModificacao, t.Estado)
}
// VerificaAtributos é um método de tipoConta que verifica os campos Nome, DescricaoDebito e DescricaoCredito, retornando um erro != nil caso ocorra um problema
func (t *TipoConta) VerificaAtributos() error {
return verifica(t.Nome, t.DescricaoDebito, t.DescricaoCredito)
}
// Altera é um método que modifica os dados do TipoConta a partir dos parâmetros informados depois da verificação de cada parâmetro e atualiza a data de modificação dele. Retorna um erro != nil, caso algum parâmetro seja inválido
func (t *TipoConta) Altera(nome string, descDebito string, descCredito string) (err error) {
if err = verifica(nome, descDebito, descCredito); err != nil {
return
}
t.Nome = nome
t.DescricaoDebito = descDebito
t.DescricaoCredito = descCredito
t.DataModificacao = time.Now().Local()
return
}
// AlteraCampos é um método para alterar os campos de um TipoConta a partir de hashMap informado no parâmetro campos. Somente as chaves informadas com um valor correto serão atualizadas. É atualizado a data de modificação do TipoConta. Caso ocorra um problema na validação dos campos, retorna um erro != nil. Campos permitidos: nome, descricaoDebito, descricaoCredito
func (t *TipoConta) AlteraCampos(campos map[string]string) (err error) {
for chave, valor := range campos {
switch chave {
case "nome":
if err = verificaNome(valor); err != nil {
return
}
t.Nome = valor
case "descricaoDebito":
if err = verificaDescricao(valor, false); err != nil {
return
}
t.DescricaoDebito = valor
case "descricaoCredito":
if err = verificaDescricao(valor, true); err != nil {
return
}
t.DescricaoCredito = valor
}
}
t.DataModificacao = time.Now().Local()
return
}
// Ativa é um método que define o TipoConta como ativo e atualiza a sua data de modificação
func (t *TipoConta) Ativa() {
t.alteraEstado(true)
}
// Inativa é um método que define o TipoConta como inativo e atualiza a sua data de modificação
func (t *TipoConta) Inativa() {
t.alteraEstado(false)
}
// CorrigeData é um método que converte a data(Time) no formato do timezone local
func (t *TipoConta) CorrigeData() {
t.DataCriacao = t.DataCriacao.Local()
t.DataModificacao = t.DataModificacao.Local()
}
// ProcuraTipoConta é um método que retorna um TipoConta a partir da busca em uma listagem de TiposConta. Caso não seja encontrado o TipoConta, retorna um erro != nil. A interface ITiposConta exige a implementação desse método
func (ts TiposConta) ProcuraTipoConta(tipoConta string) (t *TipoConta, err error) {
for _, tipoContaLista := range ts {
if tipoContaLista.Nome == tipoConta {
t = tipoContaLista
return
}
}
err = fmt.Errorf("Tipo de conta %s informada não existe na listagem", tipoConta)
return
}
// Len é um método de TiposConta que retorna a quantidade de elementos contidos dentro do slice de TipoConta. A interface ITiposConta exige a implementação desse método
func (ts TiposConta) Len() int {
return len(ts)
}
func (t *TipoConta) alteraEstado(estado bool) {
t.DataModificacao = time.Now().Local()
t.Estado = estado
}
func verifica(nome, descDebito, descCredito string) (err error) {
if err = verificaNome(nome); err != nil {
return
} else if err = verificaDescricao(descDebito, false); err != nil {
return
} else if err = verificaDescricao(descCredito, true); err != nil {
return
}
return
}
func verificaNome(nome string) (err error) {
if len(nome) == 0 || len(nome) > MaxNome {
err = erro.ErroTamanho(MsgErroNome01, len(nome))
}
return
}
func verificaDescricao(descricao string, tipoCredito bool) (err error) {
if len(descricao) == 0 || len(descricao) > MaxDescricao {
if tipoCredito {
err = erro.ErroTamanho(MsgErroDescricao02, len(descricao))
} else {
err = erro.ErroTamanho(MsgErroDescricao01, len(descricao))
}
}
return
}
| true |
13d03494464b29c7d0cb30e4127e5b51bd24a164
|
Go
|
chentaihan/leetcode
|
/mapTag/maxNumberOfBalloons.go
|
UTF-8
| 1,109 | 3.3125 | 3 |
[] |
no_license
|
[] |
no_license
|
package mapTag
/**
1189. “气球” 的最大数量
给你一个字符串 text,你需要使用 text 中的字母来拼凑尽可能多的单词 "balloon"(气球)。
字符串 text 中的每个字母最多只能被使用一次。请你返回最多可以拼凑出多少个单词 "balloon"。
示例 1:
输入:text = "nlaebolko"
输出:1
示例 2:
输入:text = "loonbalxballpoon"
输出:2
示例 3:
输入:text = "leetcode"
输出:0
提示:
1 <= text.length <= 10^4
text 全部由小写英文字母组成
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-number-of-balloons
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
func maxNumberOfBalloons(text string) int {
if len(text) < len("balloon") {
return 0
}
buf := [26]int{}
for i := 0; i < len(text); i++ {
buf[text[i]-'a']++
}
min := len(text)
for _, c := range "ban" {
if buf[c-'a'] < min {
min = buf[c-'a']
}
}
for _, c := range "lo" {
if buf[c-'a']/2 < min {
min = buf[c-'a'] / 2
}
}
return min
}
| true |
c2403d387f78539d0aade7495371de0779f8b571
|
Go
|
x4AEKx/go-hw2
|
/listing/listing02/main.go
|
UTF-8
| 976 | 4.1875 | 4 |
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
// defer вызывается после return но до момента получения значения вызывающей стороной
// При работе с defer - 3 правила
// 1) Аргументы вычисляются в момент выполнения строки ex: defer Add(a,b)
// 2) Defer'ы - выполняются по стеку
// 3) Defer может читать/писать в именованный возврат
func test() (x int) { // здесь defer может читать и присваивать в x - т.к. x - именованный возврат
defer func() {
x++
}()
x = 1
return
}
func anotherTest() int {
var x int
defer func() {
x++
}()
x = 1
return x // здесь defer не может поменять возвращаемое значение, т.к. не именованый возврат
}
func main() {
fmt.Println(test())
fmt.Println(anotherTest())
}
| true |
ba5a632e67595f78278cf2c0a90c068d57e2b825
|
Go
|
Guitarbum722/meetup-client
|
/meetup.go
|
UTF-8
| 3,067 | 2.609375 | 3 |
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package meetup
import (
"bytes"
"encoding/json"
"net/http"
"net/url"
"time"
"github.com/Guitarbum722/meetup-client/models"
)
const baseURL = "https://api.meetup.com"
// Clienter
type Clienter interface {
Members(int) (*models.Members, error)
Member(int) (*models.Member, error)
GroupByID([]int) (*models.Groups, error)
GroupByURLName([]string) (*models.Groups, error)
GroupByOrganizer([]int) (*models.Groups, error)
GroupByZip(int) (*models.Groups, error)
Categories() (*models.Categories, error)
EventsByGeo(string, string, string) (*models.Events, error)
EventsByGroup(string, []string, bool) (*models.Events, error)
EventByID(string, string) (*models.Event, error)
EventsByGroupID(int, []string, bool) (*models.Events, error)
EventComments(func(map[string][]string, url.Values), map[string][]string) (*models.Comments, error)
EventCommentByID(int) (*models.Comment, error)
EventRatings(func(map[string][]string, url.Values), map[string][]string) (*models.Ratings, error)
RateEvent(func(map[string][]string, url.Values), map[string][]string) (*models.Rating, error)
CommentOnEvent(func(map[string][]string, url.Values), map[string][]string) (*models.Comment, error)
LikeComment(int) error
UnlikeComment(int) error
RemoveEventComment(int) error
CreateEvent(func(map[string][]string, url.Values), map[string][]string) (*models.Event, error)
UpdateEvent(string, func(map[string][]string, url.Values), map[string][]string) (*models.Event, error)
DeleteEvent(string) error
}
// ClientOpts contains options to be passed in when creating a new
// meetup client value
type ClientOpts struct {
APIKey string
HTTPClient *http.Client
}
// Client represents a meetup client
type Client struct {
hc *http.Client
opts *ClientOpts
}
// NewClient creates a new Meetup client with the given parameters
func NewClient(opts *ClientOpts) Clienter {
if opts.HTTPClient != nil {
return &Client{
hc: opts.HTTPClient,
opts: opts,
}
}
return &Client{
hc: &http.Client{
Timeout: time.Duration(time.Second * 20),
},
opts: opts,
}
}
// call acts as a broker for the packages HTTP requests to the meetup.com API
func (c *Client) call(method, uri string, data *bytes.Buffer, result interface{}) error {
var req *http.Request
var err error
endpoint := baseURL + uri
switch method {
case http.MethodGet:
req, err = http.NewRequest(method, endpoint, nil)
if err != nil {
return err
}
case http.MethodPost:
req, err = http.NewRequest(method, endpoint, data)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
if err != nil {
return err
}
case http.MethodDelete:
req, err = http.NewRequest(method, endpoint, nil)
if err != nil {
return err
}
}
defer func() { req.Close = true }()
res, err := c.hc.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
return json.NewDecoder(res.Body).Decode(result)
}
// returns url.Values map with initialized API key
func (c *Client) urlValues() url.Values {
v := url.Values{}
v.Set("key", c.opts.APIKey)
return v
}
| true |
8f38375ba99aeb3dbd4a7f0bb27ff9cf8ce859f0
|
Go
|
LXG19961206/golang
|
/day09/day09.go
|
UTF-8
| 627 | 3.421875 | 3 |
[] |
no_license
|
[] |
no_license
|
// 今天没有精力学习新的内容,复习之前的东西
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
fmt.Println("欢迎开始")
test2()
}
func test() {
var time = time.Now()
rand.Seed(time.Unix())
var arr [21]int
var slice = make([]int, 21, 21)
for i := 0; i <= 20; i++ {
arr[i] = rand.Intn(20)
slice[i] = rand.Intn(30)
}
slice = append(slice, slice...)
fmt.Println(slice)
}
func test2() {
var time = time.Now().Unix()
rand.Seed(time)
var slice = make([]int, 20, 20)
for i := 0; i < 20; i++ {
slice[i] = rand.Intn(20)
}
slice = append(slice, slice...)
fmt.Println(slice)
}
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.