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
423885cee8f3d270f70c6a67417e212431bf52d7
Go
aquasecurity/vuln-list-update
/utils/utils.go
UTF-8
5,328
2.671875
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package utils import ( "bytes" "crypto/rand" "encoding/json" "fmt" "log" "math" "math/big" "os" "os/exec" "path/filepath" "strings" "time" "github.com/parnurzeal/gorequest" "golang.org/x/xerrors" pb "gopkg.in/cheggaaa/pb.v1" ) var vulnListDir = filepath.Join(CacheDir(), "vuln-list") func CacheDir() string { cacheDir, err := os.UserCacheDir() if err != nil { cacheDir = os.TempDir() } dir := filepath.Join(cacheDir, "vuln-list-update") return dir } func SetVulnListDir(dir string) { vulnListDir = dir } func VulnListDir() string { return vulnListDir } func SaveCVEPerYear(dirPath string, cveID string, data interface{}) error { s := strings.Split(cveID, "-") if len(s) != 3 { return xerrors.Errorf("invalid CVE-ID format: %s\n", cveID) } yearDir := filepath.Join(dirPath, s[1]) if err := os.MkdirAll(yearDir, os.ModePerm); err != nil { return err } filePath := filepath.Join(yearDir, fmt.Sprintf("%s.json", cveID)) if err := Write(filePath, data); err != nil { return xerrors.Errorf("failed to write file: %w", err) } return nil } func Write(filePath string, data interface{}) error { dir := filepath.Dir(filePath) if err := os.MkdirAll(dir, os.ModePerm); err != nil { return xerrors.Errorf("failed to create %s: %w", dir, err) } f, err := os.Create(filePath) if err != nil { return xerrors.Errorf("file create error: %w", err) } defer f.Close() b, err := json.MarshalIndent(data, "", " ") if err != nil { return xerrors.Errorf("JSON marshal error: %w", err) } _, err = f.Write(b) if err != nil { return xerrors.Errorf("file write error: %w", err) } return nil } // GenWorkers generate workders func GenWorkers(num, wait int) chan<- func() { tasks := make(chan func()) for i := 0; i < num; i++ { go func() { for f := range tasks { f() time.Sleep(time.Duration(wait) * time.Second) } }() } return tasks } // DeleteNil deletes nil in errs func DeleteNil(errs []error) (new []error) { for _, err := range errs { if err != nil { new = append(new, err) } } return new } // TrimSpaceNewline deletes space character and newline character(CR/LF) func TrimSpaceNewline(str string) string { str = strings.TrimSpace(str) return strings.Trim(str, "\r\n") } // FetchURL returns HTTP response body with retry func FetchURL(url, apikey string, retry int) (res []byte, err error) { for i := 0; i <= retry; i++ { if i > 0 { wait := math.Pow(float64(i), 2) + float64(RandInt()%10) log.Printf("retry after %f seconds\n", wait) time.Sleep(time.Duration(time.Duration(wait) * time.Second)) } res, err = fetchURL(url, map[string]string{"api-key": apikey}) if err == nil { return res, nil } } return nil, xerrors.Errorf("failed to fetch URL: %w", err) } func RandInt() int { seed, _ := rand.Int(rand.Reader, big.NewInt(math.MaxInt64)) return int(seed.Int64()) } func fetchURL(url string, headers map[string]string) ([]byte, error) { req := gorequest.New().Get(url) for key, value := range headers { req.Header.Add(key, value) } resp, body, errs := req.Type("text").EndBytes() if len(errs) > 0 { return nil, xerrors.Errorf("HTTP error. url: %s, err: %w", url, errs[0]) } if resp.StatusCode != 200 { return nil, xerrors.Errorf("HTTP error. status code: %d, url: %s", resp.StatusCode, url) } return body, nil } // FetchConcurrently fetches concurrently func FetchConcurrently(urls []string, concurrency, wait, retry int) (responses [][]byte, err error) { reqChan := make(chan string, len(urls)) resChan := make(chan []byte, len(urls)) errChan := make(chan error, len(urls)) defer close(reqChan) defer close(resChan) defer close(errChan) go func() { for _, url := range urls { reqChan <- url } }() bar := pb.StartNew(len(urls)) tasks := GenWorkers(concurrency, wait) for range urls { tasks <- func() { url := <-reqChan res, err := FetchURL(url, "", retry) if err != nil { errChan <- err return } resChan <- res } bar.Increment() } bar.Finish() var errs []error timeout := time.After(10 * 60 * time.Second) for range urls { select { case res := <-resChan: responses = append(responses, res) case err := <-errChan: errs = append(errs, err) case <-timeout: return nil, xerrors.New("Timeout Fetching URL") } } if 0 < len(errs) { return responses, fmt.Errorf("%s", errs) } return responses, nil } // Major returns major version func Major(osVer string) (majorVersion string) { return strings.Split(osVer, ".")[0] } func IsCommandAvailable(name string) bool { cmd := exec.Command(name, "--help") if err := cmd.Run(); err != nil { return false } return true } func Exists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return true, err } func Exec(command string, args []string) (string, error) { cmd := exec.Command(command, args...) var stdoutBuf, stderrBuf bytes.Buffer cmd.Stdout = &stdoutBuf cmd.Stderr = &stderrBuf if err := cmd.Run(); err != nil { log.Println(stderrBuf.String()) return "", xerrors.Errorf("failed to exec: %w", err) } return stdoutBuf.String(), nil } func LookupEnv(key, defaultValue string) string { if val, ok := os.LookupEnv(key); ok { return val } return defaultValue }
true
225f9dfee07ad1105dd31f864cec95933bc5ec63
Go
psirenny/flynn
/util/release/amis.go
UTF-8
3,685
2.578125
3
[ "BSD-3-Clause" ]
permissive
[ "BSD-3-Clause" ]
permissive
package main import ( "encoding/json" "log" "os" "sort" "strings" "github.com/flynn/flynn/Godeps/_workspace/src/github.com/cupcake/goamz/aws" "github.com/flynn/flynn/Godeps/_workspace/src/github.com/cupcake/goamz/ec2" "github.com/flynn/flynn/Godeps/_workspace/src/github.com/flynn/go-docopt" ) func amis(args *docopt.Args) { auth, err := aws.EnvAuth() if err != nil { log.Fatal(err) } manifest := &EC2Manifest{} if err := json.NewDecoder(os.Stdin).Decode(manifest); err != nil { log.Fatal(err) } for _, s := range strings.Split(args.String["<ids>"], ",") { regionID := strings.SplitN(s, ":", 2) resp, err := ec2.New(auth, aws.Regions[regionID[0]]).Images([]string{regionID[1]}, nil) if err != nil { log.Fatal(err) } if len(resp.Images) < 1 { log.Fatalln("Could not find image", regionID[1]) } image := resp.Images[0] var snapshotID string for _, mapping := range image.BlockDevices { if mapping.DeviceName == image.RootDeviceName { snapshotID = mapping.SnapshotId } } if snapshotID == "" { log.Fatalln("Could not determine RootDeviceSnapshotID for", regionID[1]) } manifest.Add(args.String["<version>"], &EC2Image{ ID: image.Id, Name: image.Name, Region: regionID[0], OwnerID: image.OwnerId, RootDeviceType: image.RootDeviceType, RootDeviceName: image.RootDeviceName, RootDeviceSnapshotID: snapshotID, VirtualizationType: image.VirtualizationType, Hypervisor: image.Hypervisor, }) } if err := json.NewEncoder(os.Stdout).Encode(manifest); err != nil { log.Fatal(err) } } type EC2Manifest struct { Name string `json:"name"` Versions []*EC2Version `json:"versions"` } // Add adds an image to the manifest. // // If the version is already in the manifest, the given image either // replaces any existing image with the same region, or is appended to // the existing list of images for that version. // // If the version is not already in the manifest a new version is added // containing the image. // // The number of versions in the manifest is capped at the value of maxVersions. func (m *EC2Manifest) Add(version string, image *EC2Image) { versions := make(sortVersions, 0, len(m.Versions)+1) for _, v := range m.Versions { if v.version() == version { images := make([]*EC2Image, len(v.Images)) added := false for n, i := range v.Images { if i.Region == image.Region { // replace existing image images[n] = image added = true continue } images[n] = i } if !added { images = append(images, image) } v.Images = images return } versions = append(versions, v) } versions = append(versions, &EC2Version{ Version: version, Images: []*EC2Image{image}, }) sort.Sort(sort.Reverse(versions)) m.Versions = make([]*EC2Version, 0, maxVersions) for i := 0; i < len(versions) && i < maxVersions; i++ { m.Versions = append(m.Versions, versions[i].(*EC2Version)) } } type EC2Version struct { Version string `json:"version"` Images []*EC2Image `json:"images"` } func (v *EC2Version) version() string { return v.Version } type EC2Image struct { ID string `json:"id"` Name string `json:"name"` Region string `json:"region"` OwnerID string `json:"owner_id"` RootDeviceType string `json:"root_device_type"` RootDeviceName string `json:"root_device_name"` RootDeviceSnapshotID string `json:"root_device_snapshot_id"` VirtualizationType string `json:"virtualization_type"` Hypervisor string `json:"hypervisor"` }
true
7e21fc879c8bfdf843e30873a3cf336ae4f90311
Go
gkarager/cluster-logging-operator
/pkg/utils/quantity_test.go
UTF-8
953
2.921875
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package utils import ( "testing" "k8s.io/apimachinery/pkg/api/resource" ) func TestParseQuantity(t *testing.T) { if _, err := ParseQuantity(""); err == nil { t.Errorf("expected empty string to return error") } table := []struct { input string expect resource.Quantity }{ {"750k", resource.MustParse("750Ki")}, {"750K", resource.MustParse("750Ki")}, {"750Ki", resource.MustParse("750Ki")}, {"8m", resource.MustParse("8Mi")}, {"8M", resource.MustParse("8Mi")}, {"8Mi", resource.MustParse("8Mi")}, {"1g", resource.MustParse("1Gi")}, {"1G", resource.MustParse("1Gi")}, {"1Gi", resource.MustParse("1Gi")}, } for _, item := range table { got, err := ParseQuantity(item.input) if err != nil { t.Errorf("%v: unexpected error: %v", item.input, err) continue } if actual, expect := got.Value(), item.expect.Value(); actual != expect { t.Errorf("%v: expected %v, got %v", item.input, expect, actual) } } }
true
f73acbbfc62cda70b78784dc11254b1317a35f49
Go
luoyong0603/LeetCode_golang
/leetCode/122. 买卖股票的最佳时机 II.go
UTF-8
402
3.609375
4
[]
no_license
[]
no_license
package main import "fmt" func main() { var l = []int{7, 1, 5, 3, 6, 4} fmt.Println(maxProfit2(l)) } //贪心算法 func maxProfit2(prices []int) int { // 设置当前收益为0 var max = 0 //假设从第二天开始买入, for i := 1; i <= len(prices); i++ { //当天价格高于前一天,就卖掉 if prices[i] > prices[i-1] { max += prices[i] - prices[i-1] } } return max }
true
416272a76b30e7db95ccb354253c1a64543dd091
Go
tweekmonster/nvim-go
/src/nvim-go/nvimutil/complete.go
UTF-8
1,569
2.75
3
[ "BSD-3-Clause" ]
permissive
[ "BSD-3-Clause" ]
permissive
// Copyright 2016 The nvim-go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package nvimutil import ( "io/ioutil" "os" "path/filepath" "strings" "nvim-go/pathutil" "github.com/neovim/go-client/nvim" ) // CompleteFiles provides a "-complete=file" completion exclude the non go files. func CompleteFiles(v *nvim.Nvim, a *nvim.CommandCompletionArgs, dir string) (filelist []string, err error) { switch { case len(a.ArgLead) > 0: a.ArgLead = filepath.Clean(a.ArgLead) if pathutil.IsDir(a.ArgLead) { // abs or rel directory path files, err := ioutil.ReadDir(a.ArgLead) if err != nil { return nil, err } for _, f := range files { if strings.HasSuffix(f.Name(), ".go") || f.IsDir() { filelist = append(filelist, a.ArgLead+string(filepath.Separator)+f.Name()) } } } else { // lacking directory path or filename files, err := ioutil.ReadDir(dir) if err != nil { return nil, err } return matchFile(files, a.ArgLead), nil } default: files, err := ioutil.ReadDir(dir) if err != nil { return nil, err } for _, f := range files { if filepath.Ext(f.Name()) == ".go" || f.IsDir() { filelist = append(filelist, f.Name()) } } } return filelist, nil } func matchFile(files []os.FileInfo, filename string) []string { var filelist []string for _, f := range files { if f.Name() == filename || strings.HasPrefix(f.Name(), filename) { filelist = append(filelist, f.Name()) } } return filelist }
true
b1e867cd022849792cf8a8f62575d16bfd0680f2
Go
yxho/redspider
/engine/concurrentEngine.go
UTF-8
1,428
3.09375
3
[]
no_license
[]
no_license
package engine import ( "fmt" "log" "redspider/fetcher" ) type Processor func(request Request) (ParseResult, error) type ConcurrentEngine struct { Scheduler Scheduler WorkCount int ItemChan chan Item RequestProcessor Processor } type Scheduler interface { Submit(Request) //configureWorkChan() Run() WorkReady(chan Request) } func (e *ConcurrentEngine) Run(seeds ...Request) { out := make(chan ParseResult) e.Scheduler.Run() for i := 0; i < e.WorkCount; i++ { e.CreateWork(out, e.Scheduler) } for _, r := range seeds { e.Scheduler.Submit(r) } //itemCount := 0 for { result := <-out for _, item := range result.Items { //log.Printf("Got item:%d,%v", itemCount, item) //itemCount++ go func() { e.ItemChan <- item }() } for _, request := range result.Requests { e.Scheduler.Submit(request) } } } func (e *ConcurrentEngine) CreateWork(out chan ParseResult, s Scheduler) { in := make(chan Request) go func() { for { s.WorkReady(in) request := <-in result, err := e.RequestProcessor(request) if err != nil { continue } out <- result } }() } func Worker(request Request) (ParseResult, error) { fmt.Printf("Fetch url:%s\n", request.Url) body, err := fetcher.Fetch(request.Url) if err != nil { log.Printf("Fetch Error:%s\n", request.Url) return ParseResult{}, err } return request.Parse.Parser(body, request.Url), nil }
true
d59c11e8f9a8e750f3296fcfd5b44f2fa9d37bf2
Go
RevanthTanneeru/lr-cli
/cmd/delete/account/account.go
UTF-8
1,742
2.859375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package account import ( "encoding/json" "errors" "fmt" "net/http" "github.com/MakeNowJust/heredoc" "github.com/loginradius/lr-cli/cmdutil" "github.com/loginradius/lr-cli/request" "github.com/spf13/cobra" ) var inpEmail string var inpUID string type creds struct { Key string `json:"Key"` Secret string `json:"Secret"` } type Result struct { IsDeleted bool `json:IsDeleted` RecordsDeleted int `json:RecordsDeleted` } func NewaccountCmd() *cobra.Command { cmd := &cobra.Command{ Use: "account", Short: "Delete an account", Long: `Use this command to delete a user from your app.`, Example: heredoc.Doc(`$ lr delete account --email <email> (or) --uid <uid> User account sucessfully deleted `), RunE: func(cmd *cobra.Command, args []string) error { if inpEmail == "" && inpUID != "" { return delete(inpUID, "uid") } else if inpUID == "" && inpEmail != "" { return delete(inpEmail, "email") } else { return &cmdutil.FlagError{Err: errors.New("Please enter exact one flag for this command")} } }, } fl := cmd.Flags() fl.StringVarP(&inpEmail, "email", "e", "", "Email id of the user you want to delete") fl.StringVarP(&inpUID, "uid", "u", "", "UID of the user you want to delete") return cmd } func delete(value string, field string) error { url := "" if field == "email" { url = "/identity/v2/manage/account?email=" + value } else if field == "uid" { url = "/identity/v2/manage/account/" + value } var resultResp Result resp, err := request.RestLRAPI(http.MethodDelete, url, nil, "") if err != nil { return err } err = json.Unmarshal(resp, &resultResp) if err != nil { return err } fmt.Println("User account sucessfully deleted") return nil }
true
33e6656194e33d93ef76e301790e2b0dbd53703c
Go
fengpf/go-implement-your-object-storage
/src/lib/objectstream/put_test.go
UTF-8
483
3.03125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package objectstream import ( "io" "io/ioutil" "net/http" "net/http/httptest" "testing" ) func putHandler(w http.ResponseWriter, r *http.Request) { b, _ := ioutil.ReadAll(r.Body) if string(b) == "test" { return } w.WriteHeader(http.StatusForbidden) } func TestPut(t *testing.T) { s := httptest.NewServer(http.HandlerFunc(putHandler)) defer s.Close() ps := NewPutStream(s.URL[7:], "any") io.WriteString(ps, "test") e := ps.Close() if e != nil { t.Error(e) } }
true
5fac79d741698f5040c771c9083abe62771e3e52
Go
paper42/makeweb
/formats.go
UTF-8
691
2.984375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package makeweb import ( "fmt" "gopkg.in/russross/blackfriday.v2" ) func toHTML(page Page) (Page, error) { format, ok := page.Vars["format"].(string) if ok { if format == "markdown" || format == "md" { page.Content = md2html(page.Content) } else if format == "html" { page.Content = html2html(page.Content) } else { return Page{}, fmt.Errorf("unknown format: %v", format) } } else { // undefined format, use html page.Vars["format"] = "html" page.Content = html2html(page.Content) } return page, nil } func md2html(text string) string { content := string(blackfriday.Run([]byte(text))) return content } func html2html(text string) string { return text }
true
ed5f682f526ef5dfe84171dea1e883d5aeba7b83
Go
nathankidd/aoc2017
/7b/sol.go
UTF-8
3,371
3.5625
4
[]
no_license
[]
no_license
package main import "fmt" import "os" import "bufio" import "strings" import "strconv" type Node struct { parent *Node children []*Node name string weight int // weight of this node itself totalweight int // weight of this node and all subnodes } func PopulateSubtreeWeight(node *Node) int { weight := node.weight for _, child := range node.children { PopulateSubtreeWeight(child) weight += child.totalweight } node.totalweight = weight return weight } func GetUnbalancedChild(children []*Node) *Node { if len(children) == 0 { return nil } if len(children) < 3 { fmt.Errorf("Found node (%s) without enough children to decide which is correct\n", children[0].parent.name) os.Exit(1) } for pos, child := range children { if child.totalweight != children[(pos+1)%len(children)].totalweight && child.totalweight != children[(pos+2)%len(children)].totalweight { return child } } return nil } func FindUnbalancedNode(node *Node, level int) *Node { var found *Node // Is the total subtree weight of any child unbalanced? child := GetUnbalancedChild(node.children) if child == nil { return nil } // If any grandchildren are unbalanced we need to go deeper in tree grandchild := GetUnbalancedChild(child.children) if grandchild != nil { found = FindUnbalancedNode(child, level+1) } // But if the grandchildren are balanced it means this child is unbalanced if found == nil { found = child } return found } func main() { file, err := os.Open("input") if err != nil { panic(err) } defer file.Close() tree := make(map[string]*Node) var root *Node scanner := bufio.NewScanner(file) for scanner.Scan() { var node *Node for pos, token := range strings.Fields(scanner.Text()) { if token[len(token)-1] == ',' { token = token[:len(token)-1] } switch pos { case 0: if n, exist := tree[token]; exist { node = n } else { node = new(Node) tree[token] = node node.name = token } root = node // any starting point case 1: num, err := strconv.Atoi(token[1 : len(token)-1]) if err != nil { panic(err) } node.weight = num case 2: // ignore -> default: var child *Node if n, exist := tree[token]; exist { child = n } else { child = new(Node) tree[token] = child child.name = token } child.parent = node node.children = append(node.children, child) } } } // root currently points to the last node added, find the real root node for { if root.parent == nil { break } root = root.parent } fmt.Printf("Root node: %s\n", root.name) PopulateSubtreeWeight(root) unb := FindUnbalancedNode(root, 0) if unb == nil { fmt.Printf("Could not find any unbalanced node.\n") os.Exit(1) } var sib *Node fmt.Printf("Unbalanced node: %s\n", unb.name) for _, child := range unb.children { fmt.Printf(" child -> %s (%d) (%d)\n", child.name, child.weight, child.totalweight) } for _, s := range unb.parent.children { if s.totalweight != unb.totalweight { sib = s } fmt.Printf(" sibling -> %s (%d) (%d)\n", s.name, s.weight, s.totalweight) } delta := sib.totalweight - unb.totalweight fmt.Printf("Node %s should weigh %d (%d%+d (+%d) = %d)\n", unb.name, unb.weight+delta, unb.weight, delta, unb.totalweight-unb.weight, sib.totalweight) }
true
5c2eb28c4cdc094f2ebf969026b0b6f669bd02a6
Go
LightningPeach/lnd
/channeldb/db_test.go
UTF-8
2,014
3.203125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package channeldb import ( "io/ioutil" "os" "path/filepath" "testing" ) func TestOpenWithCreate(t *testing.T) { t.Parallel() // First, create a temporary directory to be used for the duration of // this test. tempDirName, err := ioutil.TempDir("", "channeldb") if err != nil { t.Fatalf("unable to create temp dir: %v", err) } defer os.RemoveAll(tempDirName) // Next, open thereby creating channeldb for the first time. dbPath := filepath.Join(tempDirName, "cdb") cdb, err := Open(dbPath) if err != nil { t.Fatalf("unable to create channeldb: %v", err) } if err := cdb.Close(); err != nil { t.Fatalf("unable to close channeldb: %v", err) } // The path should have been successfully created. if !fileExists(dbPath) { t.Fatalf("channeldb failed to create data directory") } } // TestWipe tests that the database wipe operation completes successfully // and that the buckets are deleted. It also checks that attempts to fetch // information while the buckets are not set return the correct errors. func TestWipe(t *testing.T) { t.Parallel() // First, create a temporary directory to be used for the duration of // this test. tempDirName, err := ioutil.TempDir("", "channeldb") if err != nil { t.Fatalf("unable to create temp dir: %v", err) } defer os.RemoveAll(tempDirName) // Next, open thereby creating channeldb for the first time. dbPath := filepath.Join(tempDirName, "cdb") cdb, err := Open(dbPath) if err != nil { t.Fatalf("unable to create channeldb: %v", err) } defer cdb.Close() if err := cdb.Wipe(); err != nil { t.Fatalf("unable to wipe channeldb: %v", err) } // Check correct errors are returned _, err = cdb.FetchAllOpenChannels() if err != ErrNoActiveChannels { t.Fatalf("fetching open channels: expected '%v' instead got '%v'", ErrNoActiveChannels, err) } _, err = cdb.FetchClosedChannels(false) if err != ErrNoClosedChannels { t.Fatalf("fetching closed channels: expected '%v' instead got '%v'", ErrNoClosedChannels, err) } }
true
6289f4a6dd933b1c59617383fa9e8f377a50771d
Go
richardsenar/mycroft
/reIndexer.go
UTF-8
1,167
2.765625
3
[]
no_license
[]
no_license
package sherlock import "sync" /* o8o .o8 `"' "888 oooo ooo. .oo. .oooo888 .ooooo. oooo ooo `888 `888P"Y88b d88' `888 d88' `88b `88b..8P' 888 888 888 888 888 888ooo888 Y888' 888 888 888 888 888 888 .o .o8"'88b o888o o888o o888o `Y8bod88P" `Y8bod8P' o88' 888o */ type gcvKey struct { GCV string HseNum string StrtName string City string State string UnitNum string } type gcvVal struct { Value string SAPID string Col int Rule int HseNum string StrName string UnitNum string Zip string } type indexerGCV struct { idxr map[gcvKey][]gcvVal sync.RWMutex } func newIndexerGCV() *indexerGCV { return &indexerGCV{ idxr: make(map[gcvKey][]gcvVal), } } // define method to get values based on key func (i *indexerGCV) Get(key gcvKey) ([]gcvVal, bool) { i.RLock() result, ok := i.idxr[key] i.RUnlock() return result, ok } // define method to set values on key func (i *indexerGCV) Set(key gcvKey, val gcvVal) { i.Lock() i.idxr[key] = append(i.idxr[key], val) i.Unlock() }
true
07c596aa86aca5109d35bec662f52e752e4d6e25
Go
litixsoft/lxgo
/db/mongo.go
UTF-8
25,836
2.578125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package lxDb import ( "context" "errors" "github.com/google/go-cmp/cmp" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readpref" "time" ) const ( DefaultTimeout = time.Second * 30 Insert = "insert" Update = "update" Delete = "delete" ) type mongoBaseRepo struct { collection *mongo.Collection audit IBaseRepoAudit locale *string } // NewMongoBaseRepo, return base repo instance func NewMongoBaseRepo(collection *mongo.Collection, baseRepoAudit ...IBaseRepoAudit) IBaseRepo { // Default audit is nil var audit IBaseRepoAudit // Optional audit in args if len(baseRepoAudit) > 0 { audit = baseRepoAudit[0] } return &mongoBaseRepo{ collection: collection, audit: audit, locale: nil, } } // GetMongoDbClient, return new mongo driver client func GetMongoDbClient(uri string) (client *mongo.Client, err error) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() client, err = mongo.Connect(ctx, options.Client().ApplyURI(uri)) if err != nil { return } // Check connection err = client.Ping(ctx, readpref.Primary()) if err != nil { return client, err } return client, nil } // CreateIndexes, creates multiple indexes in the collection. // The names of the created indexes are returned. func (repo *mongoBaseRepo) CreateIndexes(indexes interface{}, args ...interface{}) ([]string, error) { timeout := DefaultTimeout opts := &options.CreateIndexesOptions{} for i := 0; i < len(args); i++ { switch val := args[i].(type) { case time.Duration: timeout = val case *options.CreateIndexesOptions: opts = val } } // Convert indexModels indexModels, ok := indexes.([]mongo.IndexModel) if !ok { return []string{}, ErrIndexConvert } // create indexes ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() return repo.collection.Indexes().CreateMany(ctx, indexModels, opts) } // InsertOne inserts a single document into the collection. func (repo *mongoBaseRepo) InsertOne(doc interface{}, args ...interface{}) (interface{}, error) { timeout := DefaultTimeout opts := &options.InsertOneOptions{} var authUser interface{} for i := 0; i < len(args); i++ { switch val := args[i].(type) { case time.Duration: timeout = val case *options.InsertOneOptions: opts = val case *AuditAuth: authUser = val.User } } ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() res, err := repo.collection.InsertOne(ctx, doc, opts) if err != nil { return nil, err } if authUser != nil && repo.audit != nil && repo.audit.IsActive() { // Convert doc to bson.M bm, err := ToBsonMap(doc) if err != nil { return nil, err } // Add _id to data if _, ok := bm["_id"]; !ok { bm["_id"] = res.InsertedID } // Send to audit repo.audit.Send(bson.M{ "collection": repo.collection.Name(), "action": Insert, "user": authUser, "data": bm, }) } return res.InsertedID, nil } // InsertMany inserts the provided documents. func (repo *mongoBaseRepo) InsertMany(docs []interface{}, args ...interface{}) (*InsertManyResult, error) { timeout := DefaultTimeout opts := &options.InsertManyOptions{} var authUser interface{} for i := 0; i < len(args); i++ { switch val := args[i].(type) { case time.Duration: timeout = val case *options.InsertManyOptions: opts = val case *AuditAuth: authUser = val.User } } // Return UpdateManyResult insertManyResult := new(InsertManyResult) // Audit with insert, when audit is active than insert one and audit if authUser != nil && repo.audit != nil && repo.audit.IsActive() { // InsertOne func for audit insert many insertOneFn := func(doc interface{}) (*mongo.InsertOneResult, error) { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() return repo.collection.InsertOne(ctx, doc) } // Array for audits var auditEntries []bson.M // Insert docs and create log entries for _, doc := range docs { // InsertOne res, err := insertOneFn(&doc) if err != nil || res.InsertedID == nil { // Error, increment FailedCount insertManyResult.FailedCount++ } else { // Add inserted id insertManyResult.InsertedIDs = append(insertManyResult.InsertedIDs, res.InsertedID) // Convert for audit bm, err := ToBsonMap(doc) if err != nil { return insertManyResult, err } // Check id exists and not empty if _, ok := bm["_id"]; !ok { bm["_id"] = res.InsertedID } // Audit only is inserted, auditEntries = append(auditEntries, bson.M{ "collection": repo.collection.Name(), "action": Insert, "user": authUser, "data": bm}) } } // Check audit entries if auditEntries == nil || len(auditEntries) == 0 { return insertManyResult, nil } // Send to audit repo.audit.Send(auditEntries) return insertManyResult, nil } ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() res, err := repo.collection.InsertMany(ctx, docs, opts) if err != nil { return insertManyResult, err } // Convert if res != nil { insertManyResult.InsertedIDs = res.InsertedIDs } return insertManyResult, nil } // CountDocuments gets the number of documents matching the filter. // For a fast count of the total documents in a collection see EstimatedDocumentCount. func (repo *mongoBaseRepo) CountDocuments(filter interface{}, args ...interface{}) (int64, error) { // Default values timeout := DefaultTimeout opts := &options.CountOptions{} for i := 0; i < len(args); i++ { switch val := args[i].(type) { case time.Duration: timeout = val case *options.CountOptions: opts = val } } ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() return repo.collection.CountDocuments(ctx, filter, opts) } // EstimatedDocumentCount gets an estimate of the count of documents in a collection using collection metadata. func (repo *mongoBaseRepo) EstimatedDocumentCount(args ...interface{}) (int64, error) { // Default values timeout := DefaultTimeout opts := &options.EstimatedDocumentCountOptions{} for i := 0; i < len(args); i++ { switch val := args[i].(type) { case time.Duration: timeout = val case *options.EstimatedDocumentCountOptions: opts = val } } ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() return repo.collection.EstimatedDocumentCount(ctx, opts) } // Find, find all matched by filter func (repo *mongoBaseRepo) Find(filter interface{}, result interface{}, args ...interface{}) error { // Default values timeout := DefaultTimeout opts := &options.FindOptions{} for i := 0; i < len(args); i++ { switch val := args[i].(type) { case time.Duration: timeout = val case *options.FindOptions: opts = val } } if repo.locale != nil && opts.Collation == nil { opts.SetCollation(&options.Collation{ Locale: *repo.locale, }) } ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() cur, err := repo.collection.Find(ctx, filter, opts) if err != nil { return err } return cur.All(ctx, result) } // Find, find all matched by filter func (repo *mongoBaseRepo) FindOne(filter interface{}, result interface{}, args ...interface{}) error { // Default values timeout := DefaultTimeout opts := &options.FindOneOptions{} for i := 0; i < len(args); i++ { switch val := args[i].(type) { case time.Duration: timeout = val case *options.FindOneOptions: opts = val } } if repo.locale != nil && opts.Collation == nil { opts.SetCollation(&options.Collation{ Locale: *repo.locale, }) } ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() // Find and convert no documents error err := repo.collection.FindOne(ctx, filter, opts).Decode(result) if err != nil { if errors.Is(err, mongo.ErrNoDocuments) { return ErrNotFound } return err } return nil } // FindOneAndDelete find a single document and deletes it, returning the // original in result. func (repo *mongoBaseRepo) FindOneAndDelete(filter interface{}, result interface{}, args ...interface{}) error { timeout := DefaultTimeout opts := &options.FindOneAndDeleteOptions{} var authUser interface{} for i := 0; i < len(args); i++ { switch val := args[i].(type) { case time.Duration: timeout = val case *options.FindOneAndDeleteOptions: opts = val case *AuditAuth: authUser = val.User } } if repo.locale != nil && opts.Collation == nil { opts.SetCollation(&options.Collation{ Locale: *repo.locale, }) } ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() if err := repo.collection.FindOneAndDelete(ctx, filter, opts).Decode(result); err != nil { if errors.Is(err, mongo.ErrNoDocuments) { return ErrNotFound } return err } // Audit if authUser != nil && repo.audit != nil && repo.audit.IsActive() { // Convert result to bson.M bm, err := ToBsonMap(result) if err != nil { return err } // Send to audit repo.audit.Send(bson.M{ "collection": repo.collection.Name(), "action": Delete, "user": authUser, "data": bson.M{"_id": bm["_id"]}, }) } return nil } // FindOneAndReplace finds a single document and replaces it, returning either // the original or the replaced document. func (repo *mongoBaseRepo) FindOneAndReplace(filter, replacement, result interface{}, args ...interface{}) error { timeout := DefaultTimeout opts := options.FindOneAndReplace() var authUser interface{} for i := 0; i < len(args); i++ { switch val := args[i].(type) { case time.Duration: timeout = val case *options.FindOneAndReplaceOptions: opts = val case *AuditAuth: authUser = val.User } } if repo.locale != nil && opts.Collation == nil { opts.SetCollation(&options.Collation{ Locale: *repo.locale, }) } // Audit only with options.After if authUser != nil && repo.audit != nil && repo.audit.IsActive() { // Check and set options if opts.ReturnDocument == nil || *opts.ReturnDocument != options.After && *opts.ReturnDocument != options.Before { // Set default to after opts.SetReturnDocument(options.After) } // Check option and replace with audit switch *opts.ReturnDocument { case options.After: // Save doc before replace for compare var beforeReplace bson.M // Set FindOne options findOneOpts := options.FindOne() // When FindOneAndUpdateOptions.Sort is set then set FindOneOptions if opts.Sort != nil { findOneOpts.SetSort(opts.Sort) } if err := repo.FindOne(filter, &beforeReplace, findOneOpts); err != nil { return err } // FindOne and update ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() if err := repo.collection.FindOneAndReplace(ctx, filter, replacement, opts).Decode(result); err != nil { return err } // Audit only is replaced // Create after replace map for compare afterReplace, err := ToBsonMap(result) if err != nil { return err } // Compare and audit if !cmp.Equal(beforeReplace, afterReplace) { // Send to audit repo.audit.Send(bson.M{ "collection": repo.collection.Name(), "action": Update, "user": authUser, "data": afterReplace, }) } case options.Before: // FindOne and replace ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() if err := repo.collection.FindOneAndReplace(ctx, filter, replacement, opts).Decode(result); err != nil { if errors.Is(err, mongo.ErrNoDocuments) { return ErrNotFound } return err } // Audit only is replaced // Create before replace map for compare beforeReplace, err := ToBsonMap(result) if err != nil { return err } // Save doc after replace for compare var afterReplace bson.M if err := repo.FindOne(bson.D{{"_id", beforeReplace["_id"]}}, &afterReplace); err != nil { return err } // Compare and audit if !cmp.Equal(beforeReplace, afterReplace) { // Send to audit repo.audit.Send(bson.M{ "collection": repo.collection.Name(), "action": Update, "user": authUser, "data": afterReplace, }) } } return nil } // Without audit simple FindOneAndUpdate with given opts ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() if err := repo.collection.FindOneAndReplace(ctx, filter, replacement, opts).Decode(result); err != nil { if errors.Is(err, mongo.ErrNoDocuments) { return ErrNotFound } return err } return nil } // FindOneAndUpdate finds a single document and updates it, returning either // the the updated. func (repo *mongoBaseRepo) FindOneAndUpdate(filter, update, result interface{}, args ...interface{}) error { timeout := DefaultTimeout opts := &options.FindOneAndUpdateOptions{} var authUser interface{} for i := 0; i < len(args); i++ { switch val := args[i].(type) { case time.Duration: timeout = val case *options.FindOneAndUpdateOptions: opts = val case *AuditAuth: authUser = val.User } } if repo.locale != nil && opts.Collation == nil { opts.SetCollation(&options.Collation{ Locale: *repo.locale, }) } // Audit only with options.After if authUser != nil && repo.audit != nil && repo.audit.IsActive() { // Check and set options if opts.ReturnDocument == nil || *opts.ReturnDocument != options.After && *opts.ReturnDocument != options.Before { // Set default to after opts.SetReturnDocument(options.After) } // Check option and update with audit switch *opts.ReturnDocument { case options.After: // Save doc before update for compare var beforeUpdate bson.M // Set FindOne options findOneOpts := options.FindOne() // When FindOneAndUpdateOptions.Sort is set then set FindOneOptions if opts.Sort != nil { findOneOpts.SetSort(opts.Sort) } if err := repo.FindOne(filter, &beforeUpdate, findOneOpts); err != nil { return err } // FindOne and update ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() if err := repo.collection.FindOneAndUpdate(ctx, filter, update, opts).Decode(result); err != nil { return err } // Audit only is updated // Create after update map for compare afterUpdate, err := ToBsonMap(result) if err != nil { return err } // Compare and audit if !cmp.Equal(beforeUpdate, afterUpdate) { // Send to audit repo.audit.Send(bson.M{ "collection": repo.collection.Name(), "action": Update, "user": authUser, "data": afterUpdate, }) } case options.Before: // FindOne and update ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() if err := repo.collection.FindOneAndUpdate(ctx, filter, update, opts).Decode(result); err != nil { if errors.Is(err, mongo.ErrNoDocuments) { return ErrNotFound } return err } // Audit only is updated // Create before update map for compare beforeUpdate, err := ToBsonMap(result) if err != nil { return err } // Save doc after update for compare var afterUpdate bson.M if err := repo.FindOne(bson.D{{"_id", beforeUpdate["_id"]}}, &afterUpdate); err != nil { return err } // Compare and audit if !cmp.Equal(beforeUpdate, afterUpdate) { // Send to audit repo.audit.Send(bson.M{ "collection": repo.collection.Name(), "action": Update, "user": authUser, "data": afterUpdate, }) } } return nil } // Without audit simple FindOneAndUpdate with given opts ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() if err := repo.collection.FindOneAndUpdate(ctx, filter, update, opts).Decode(result); err != nil { if errors.Is(err, mongo.ErrNoDocuments) { return ErrNotFound } return err } return nil } // UpdateOne updates a single document in the collection. func (repo *mongoBaseRepo) UpdateOne(filter interface{}, update interface{}, args ...interface{}) error { timeout := DefaultTimeout opts := &options.UpdateOptions{} var authUser interface{} for i := 0; i < len(args); i++ { switch val := args[i].(type) { case time.Duration: timeout = val case *options.UpdateOptions: opts = val case *AuditAuth: authUser = val.User } } if repo.locale != nil && opts.Collation == nil { opts.SetCollation(&options.Collation{ Locale: *repo.locale, }) } if authUser != nil && repo.audit != nil && repo.audit.IsActive() { // When audit then save doc before update for compare var beforeUpdate bson.M if err := repo.FindOne(filter, &beforeUpdate); err != nil { return err } ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() // Find and update doc save doc after updated foaOpts := &options.FindOneAndUpdateOptions{} foaOpts.SetReturnDocument(options.After) var afterUpdate bson.M if err := repo.collection.FindOneAndUpdate(ctx, filter, update, foaOpts).Decode(&afterUpdate); err != nil { if errors.Is(err, mongo.ErrNoDocuments) { return ErrNotFound } return err } // Audit only is updated if !cmp.Equal(beforeUpdate, afterUpdate) { // Send to audit repo.audit.Send(bson.M{ "collection": repo.collection.Name(), "action": Update, "user": authUser, "data": afterUpdate, }) } return nil } // Without audit can simple update ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() // Simple update doc res, err := repo.collection.UpdateOne(ctx, filter, update, opts) if res != nil && res.MatchedCount == 0 { //return NewNotFoundError() return ErrNotFound } return err } // UpdateMany updates multiple documents in the collection. func (repo *mongoBaseRepo) UpdateMany(filter interface{}, update interface{}, args ...interface{}) (*UpdateManyResult, error) { // Default values timeout := DefaultTimeout opts := &options.UpdateOptions{} var authUser interface{} // Check args for i := 0; i < len(args); i++ { switch val := args[i].(type) { case time.Duration: timeout = val case *options.UpdateOptions: opts = val case *AuditAuth: authUser = val.User } } if repo.locale != nil && opts.Collation == nil { opts.SetCollation(&options.Collation{ Locale: *repo.locale, }) } // Return UpdateManyResult updateManyResult := new(UpdateManyResult) // Audit if authUser != nil && repo.audit != nil && repo.audit.IsActive() { // UpdateOne func for audit update many updOneFn := func(subFilter bson.D, afterUpdate *bson.M) error { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() return repo.collection.FindOneAndUpdate(ctx, subFilter, update, options.FindOneAndUpdate().SetReturnDocument(options.After)).Decode(afterUpdate) } // Find all with filter for audit var allDocs []bson.M if err := repo.Find(filter, &allDocs); err != nil { return nil, err } // Array for audits var auditEntries []bson.M // Update docs and log entries for _, val := range allDocs { subFilter := bson.D{{"_id", val["_id"]}} // UpdateOne var afterUpdate bson.M if err := updOneFn(subFilter, &afterUpdate); err != nil { // Error, add subId to failedCount and Ids updateManyResult.FailedCount++ updateManyResult.FailedIDs = append(updateManyResult.FailedIDs, subFilter.Map()["_id"]) } else { updateManyResult.MatchedCount++ // Is Modified use DeepEqual if !cmp.Equal(val, afterUpdate) { updateManyResult.ModifiedCount++ // Audit only is modified auditEntries = append(auditEntries, bson.M{ "collection": repo.collection.Name(), "action": Update, "user": authUser, "data": afterUpdate}) } } } // Check audit entries if auditEntries == nil || len(auditEntries) == 0 { return updateManyResult, nil } // Send to audit repo.audit.Send(auditEntries) return updateManyResult, nil } // Context for update ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() // Without audit UpdateMany will be performed res, err := repo.collection.UpdateMany(ctx, filter, update, opts) // Convert to UpdateManyResult if res != nil { updateManyResult.MatchedCount = res.MatchedCount updateManyResult.ModifiedCount = res.ModifiedCount updateManyResult.UpsertedCount = res.UpsertedCount updateManyResult.UpsertedID = res.UpsertedID } return updateManyResult, err } // DeleteOne deletes a single document from the collection. func (repo *mongoBaseRepo) DeleteOne(filter interface{}, args ...interface{}) error { // Default values timeout := DefaultTimeout opts := &options.FindOneAndDeleteOptions{} var authUser interface{} for i := 0; i < len(args); i++ { switch val := args[i].(type) { case time.Duration: timeout = val case *options.FindOneAndDeleteOptions: opts = val case *AuditAuth: authUser = val.User } } if repo.locale != nil && opts.Collation == nil { opts.SetCollation(&options.Collation{ Locale: *repo.locale, }) } ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() // Find document before delete for audit var beforeDelete struct { ID primitive.ObjectID `bson:"_id"` } if err := repo.collection.FindOneAndDelete(ctx, filter, opts).Decode(&beforeDelete); err != nil { if errors.Is(err, mongo.ErrNoDocuments) { return ErrNotFound } return err } // Audit if authUser != nil && repo.audit != nil && repo.audit.IsActive() { // Send to audit repo.audit.Send(bson.M{ "collection": repo.collection.Name(), "action": Delete, "user": authUser, "data": bson.M{"_id": beforeDelete.ID}, }) } return nil } // DeleteMany deletes multiple documents from the collection. func (repo *mongoBaseRepo) DeleteMany(filter interface{}, args ...interface{}) (*DeleteManyResult, error) { // Default values timeout := DefaultTimeout opts := &options.DeleteOptions{} var authUser interface{} for i := 0; i < len(args); i++ { switch val := args[i].(type) { case time.Duration: timeout = val case *options.DeleteOptions: opts = val case *AuditAuth: authUser = val.User } } if repo.locale != nil && opts.Collation == nil { opts.SetCollation(&options.Collation{ Locale: *repo.locale, }) } // Return UpdateManyResult deleteManyResult := new(DeleteManyResult) // Audit if authUser != nil && repo.audit != nil && repo.audit.IsActive() { // Find all (only id field) with filter for audit var allDocs []bson.M if err := repo.Find(filter, &allDocs, options.Find().SetProjection(bson.D{{"_id", 1}})); err != nil { return deleteManyResult, err } // DeleteMany ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() res, err := repo.collection.DeleteMany(ctx, filter, opts) if err != nil { return deleteManyResult, err } if res != nil { deleteManyResult.DeletedCount = res.DeletedCount } // Start audit async if allDocs != nil && len(allDocs) > 0 { // create audit entries var auditEntries []bson.M for _, doc := range allDocs { // data save only sub id by deleted data := bson.M{"_id": doc["_id"]} auditEntries = append(auditEntries, bson.M{ "collection": repo.collection.Name(), "action": Delete, "user": authUser, "data": data}) } // Send to audit repo.audit.Send(auditEntries) } return deleteManyResult, nil } ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() res, err := repo.collection.DeleteMany(ctx, filter, opts) if res != nil { deleteManyResult.DeletedCount = res.DeletedCount } return deleteManyResult, err } // GetCollection get instance of repo collection. func (repo *mongoBaseRepo) GetCollection() interface{} { return repo.collection } // GetDb get instance of repo collection database. func (repo *mongoBaseRepo) GetDb() interface{} { return repo.collection.Database() } // GetRepoName, get name of repo (database/collection) func (repo *mongoBaseRepo) GetRepoName() string { return repo.collection.Database().Name() + "/" + repo.collection.Name() } // SetLocale, sets locale string for collation repository wide, empty string will be remove settings func (repo *mongoBaseRepo) SetLocale(code string) { if code == "" { repo.locale = nil } else { repo.locale = &code } } // Aggregate, performs a aggregation with binding to result func (repo *mongoBaseRepo) Aggregate(pipeline interface{}, result interface{}, args ...interface{}) error { // Default values timeout := DefaultTimeout opts := &options.AggregateOptions{} for i := 0; i < len(args); i++ { switch val := args[i].(type) { case time.Duration: timeout = val case *options.AggregateOptions: opts = val } } if repo.locale != nil && opts.Collation == nil { opts.SetCollation(&options.Collation{ Locale: *repo.locale, }) } ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() cur, err := repo.collection.Aggregate(ctx, pipeline, opts) if err != nil { return err } if result != nil { ctxCursor, cancelCursor := context.WithTimeout(context.Background(), timeout) defer cancelCursor() if err := cur.All(ctxCursor, result); err != nil { return err } } return nil }
true
27697ea40ea9c0cde85515d9dfdbd0252152a3a6
Go
iamjjanga-ouo/learn-go_restapi
/echo/5_route_parameters.go
UTF-8
1,225
3.328125
3
[]
no_license
[]
no_license
// Golang with Echo - route parameters // URI에 resource에 대한 접근을 parameter를 통해서 할 수 있다. // 그리고 이 parameter에 대한 roting역시 할 수 있어 마음껏 처리가 가능하다. package main import ( "fmt" "net/http" "os" "github.com/labstack/echo" ) func main() { port := os.Getenv("MY_APP_PORT") if port == "" { port = "8080" } e := echo.New() // products := []map[int]string{{1: "mobiles"}, {2: "tv"}, {3: "laptops"}} e.GET("/", func(c echo.Context) error { return c.String(http.StatusOK, "Well, hello there!!") }) e.GET("/products", func(c echo.Context) error { // return c.JSON(http.StatusOK, products) return c.JSON(http.StatusOK, []string{"apple", "banana", "mango"}) }) e.GET("/products/:vendor", func(c echo.Context) error { // return c.JSON(http.StatusOK, c.Param("vendor")) // [parameter에 대한 routing] GET http://localhost:8080/products/apple -> "apple" return c.JSON(http.StatusOK, c.QueryParam("olderThan")) // [query에 대한 routing] GET http://localhost:8080/products/apple?olderThan=iphone10 -> "iphone10" }) e.Logger.Print(fmt.Sprintf("Listening on port %s", port)) e.Logger.Fatal(e.Start(fmt.Sprintf("localhost:%s", port))) }
true
a75209df24d6c2a8f2a1b14fcb8c739a6612adaa
Go
lionkor/learn-go
/lion/variables_1.go
UTF-8
185
3
3
[]
no_license
[]
no_license
package main import "fmt" var c, python, java bool func printC() { c := true fmt.Println(c) } func main() { var i int printC() fmt.Println(i, c, python, java) }
true
15ee578898a137525c631de1fd074895d8056d44
Go
IamNator/Cousera0
/race_conditions/main.go
UTF-8
1,309
3.46875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( //"sync" "fmt" "sort" "bufio" "os" "strings" "strconv" "sync" ) //Please enter an array of integers seperated by , : //3,4,34,43,65,23,65,73,2,64,74, //[2 64 74] //[23 65 73] //[34 43 65] //[3 4] // //Sorted out Array : [2 3 4 23 34 43 64 65 65 73 74] func main(){ reader := bufio.NewReader(os.Stdin) fmt.Println("Please enter an array of integers seperated by , :") text, _ := reader.ReadString('\n') userInputStr := strings.Split(text, ",") var userNumInR []int var num int for _,str := range userInputStr { num, _ = strconv.Atoi(str) userNumInR = append(userNumInR,num) } userNumIn := userNumInR[0:len(userNumInR)] lenUserNum := len(userNumIn) - 1 var ( arr0 []int arr1 []int arr2 []int arr3 []int ) arr0 = userNumIn[0:(lenUserNum/4)] arr1 = userNumIn[(lenUserNum/4):(lenUserNum/2)] arr2 = userNumIn[(lenUserNum/2):(3*lenUserNum/4)] arr3 = userNumIn[(3*lenUserNum/4):(lenUserNum)] var syn sync.WaitGroup //ch := make(chan []int, 10) syn.Add(4) go SortNum(arr0, &syn) go SortNum(arr1, &syn) go SortNum(arr2, &syn) go SortNum(arr3, &syn) syn.Wait() sort.Ints(userNumIn) fmt.Printf("\nSorted out Array : %v", userNumIn[1:]) } func SortNum( sli []int, syn * sync.WaitGroup) { sort.Ints(sli) fmt.Println(sli) syn.Done() }
true
51d703d35a846cc04905697e5b6747b3e3cf955a
Go
jmhobbs/go-arnoldc
/cmd/arnoldc-compile/main_test.go
UTF-8
551
2.953125
3
[]
no_license
[]
no_license
package main import ( "testing" arnoldc "github.com/jmhobbs/go-arnoldc" ) func TestGoStringForValue(t *testing.T) { cases := []struct { value arnoldc.Value expect string }{ { arnoldc.NewVariableValue("aVariable"), "aVariable", }, { arnoldc.NewIntegerValue(5), "5", }, { arnoldc.NewStringValue("a string here"), `"a string here"`, }, } for _, test := range cases { v := goStringForValue(test.value) if v != test.expect { t.Errorf("bad string for value; got %v expected %v", v, test.expect) } } }
true
7203c0205f56549ed4b90ac20e2ca237a6093445
Go
ajunlonglive/gollum
/consumer/console.go
UTF-8
3,801
2.75
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
// Copyright 2015-2018 trivago N.V. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed 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 consumer import ( "io" "os" "strings" "sync" "time" "gollum/core" "github.com/trivago/tgo" "github.com/trivago/tgo/tio" ) const ( consoleBufferGrowSize = 256 ) // Console consumer // // This consumer reads from stdin or a named pipe. A message is generated after // each newline character. // // Metadata // // *NOTE: The metadata will only set if the parameter `SetMetadata` is active.* // // - pipe: Name of the pipe the message was received on (set) // // Parameters // // - Pipe: Defines the pipe to read from. This can be "stdin" or the path // to a named pipe. If the named pipe doesn't exist, it will be created. // By default this paramater is set to "stdin". // // - Permissions: Defines the UNIX filesystem permissions used when creating // the named pipe as an octal number. // By default this paramater is set to "0664". // // - ExitOnEOF: If set to true, the plusing triggers an exit signal if the // pipe is closed, i.e. when EOF is detected. // By default this paramater is set to "true". // // - SetMetadata: When this value is set to "true", the fields mentioned in the metadata // section will be added to each message. Adding metadata will have a // performance impact on systems with high throughput. // By default this parameter is set to "false". // // Examples // // This config reads data from stdin e.g. when starting gollum via unix pipe. // // ConsoleIn: // Type: consumer.Console // Streams: console // Pipe: stdin type Console struct { core.SimpleConsumer `gollumdoc:"embed_type"` pipe *os.File pipeName string `config:"Pipe" default:"stdin"` pipePerm uint32 `config:"Permissions" default:"0644"` hasToSetMetadata bool `config:"SetMetadata" default:"false"` autoExit bool `config:"ExitOnEOF" default:"true"` } func init() { core.TypeRegistry.Register(Console{}) } // Configure initializes this consumer with values from a plugin config. func (cons *Console) Configure(conf core.PluginConfigReader) { switch strings.ToLower(cons.pipeName) { case "stdin": cons.pipe = os.Stdin cons.pipeName = "stdin" default: cons.pipe = nil } } // Enqueue creates a new message func (cons *Console) Enqueue(data []byte) { if cons.hasToSetMetadata { metaData := core.NewMetadata() metaData.Set("pipe", cons.pipeName) cons.EnqueueWithMetadata(data, metaData) } else { cons.SimpleConsumer.Enqueue(data) } } // Consume listens to stdin. func (cons *Console) Consume(workers *sync.WaitGroup) { go cons.readPipe() cons.ControlLoop() } func (cons *Console) readPipe() { if cons.pipe == nil { var err error if cons.pipe, err = tio.OpenNamedPipe(cons.pipeName, cons.pipePerm); err != nil { cons.Logger.Error(err) time.AfterFunc(3*time.Second, cons.readPipe) return // ### return, try again ### } defer cons.pipe.Close() } buffer := tio.NewBufferedReader(consoleBufferGrowSize, 0, 0, "\n") for cons.IsActive() { err := buffer.ReadAll(cons.pipe, cons.Enqueue) switch err { case io.EOF: if cons.autoExit { cons.Logger.Info("Exit triggered by EOF.") tgo.ShutdownCallback() } case nil: // ignore default: cons.Logger.Error(err) } } }
true
759046b166663b4b3e272d2efbe91de755787e85
Go
holyzhuo/go-util
/time/time.go
UTF-8
2,203
3.328125
3
[]
no_license
[]
no_license
package time import ( "fmt" "strconv" "strings" "time" ) //DateFormat(time.Now(), "YYYY-MM-DD HH:mm:ss") func DateFormat(t time.Time, format string) string { res := strings.Replace(format, "MM", t.Format("01"), -1) res = strings.Replace(res, "M", t.Format("1"), -1) res = strings.Replace(res, "DD", t.Format("02"), -1) res = strings.Replace(res, "D", t.Format("2"), -1) res = strings.Replace(res, "YYYY", t.Format("2006"), -1) res = strings.Replace(res, "YY", t.Format("06"), -1) res = strings.Replace(res, "HH", fmt.Sprintf("%02d", t.Hour()), -1) res = strings.Replace(res, "H", fmt.Sprintf("%d", t.Hour()), -1) res = strings.Replace(res, "hh", t.Format("03"), -1) res = strings.Replace(res, "h", t.Format("3"), -1) res = strings.Replace(res, "mm", t.Format("04"), -1) res = strings.Replace(res, "m", t.Format("4"), -1) res = strings.Replace(res, "ss", t.Format("05"), -1) res = strings.Replace(res, "s", t.Format("5"), -1) return res } //获得某一天0点的时间戳 func GetDaysAgoZeroTime(day int) int64 { date := time.Now().AddDate(0, 0, day).Format("2006-01-02") t, _ := time.Parse("2006-01-02", date) return t.Unix() } //时间戳转人可读 func TimeToHuman(target int) string { var res = "" if target == 0 { return res } t := int(time.Now().Unix()) - target data := [7]map[string]interface{}{ {"key": 31536000, "value": "年"}, {"key": 2592000, "value": "个月"}, {"key": 604800, "value": "星期"}, {"key": 86400, "value": "天"}, {"key": 3600, "value": "小时"}, {"key": 60, "value": "分钟"}, {"key": 1, "value": "秒"}, } for _, v := range data { var c = t / v["key"].(int) if 0 != c { res = strconv.Itoa(c) + v["value"].(string) + "前" break } } return res } // 获取当前的时间 - 字符串 func GetCurrentDate() string { return time.Now().Format("2006/01/02 15:04:05") } // 获取当前的时间 - Unix时间戳 func GetCurrentUnix() int64 { return time.Now().Unix() } // 获取当前的时间 - 毫秒级时间戳 func GetCurrentMilliUnix() int64 { return time.Now().UnixNano() / 1000000 } // 获取当前的时间 - 纳秒级时间戳 func GetCurrentNanoUnix() int64 { return time.Now().UnixNano() }
true
f9f3c103bc489f0396edd489e653b9ed27b58f9b
Go
zzuse/coderunner
/Golang/src/ch43/func_test/func_test.go
UTF-8
2,059
3.8125
4
[]
no_license
[]
no_license
package func_test import ( "errors" "fmt" "testing" ) type Printer func(contents string) (n int, err error) func printToStd(contents string) (bytesNum int, err error) { return fmt.Println(contents) } func TestFunc(t *testing.T) { var p Printer p = printToStd p("something") } type operate func(x, y int) int type calculateFunc func(x, y int) (int, error) func calculate(x int, y int, op operate) (int, error) { if op == nil { return 0, errors.New("invalid operation") } return op(x, y), nil } func genCalculator(op operate) calculateFunc { return func(x int, y int) (int, error) { if op == nil { return 0, errors.New("invalid operation") } return op(x, y), nil } } func TestAdd(t *testing.T) { op := func(x, y int) int { return x + y } x, y := 56, 78 result, err := calculate(x, y, op) fmt.Printf("The result: %d (error: %v\n", result, err) add := genCalculator(op) result, err = add(x, y) fmt.Printf("The result: %d (error: %v\n", result, err) } func modifyArray(a [3]string) [3]string { a[1] = "x" return a } func TestArray(t *testing.T) { array1 := [3]string{"a", "b", "c"} fmt.Printf("The array: %v\n", array1) array2 := modifyArray(array1) fmt.Printf("The modified array: %v\n", array2) fmt.Printf("The original array: %v\n", array1) } func modifySlice(a []string) []string { a[1] = "1" return a } func TestSlice(t *testing.T) { slice1 := []string{"x", "y", "z"} fmt.Printf("The slice: %v\n", slice1) slice2 := modifySlice(slice1) fmt.Printf("The modified slice: %v\n", slice2) fmt.Printf("The original slice: %v\n", slice1) } func modifyComplexArray(a [3][]string) [3][]string { a[1][1] = "s" a[2] = []string{"o", "p", "q"} return a } func TestComplexArray(t *testing.T) { complexArray1 := [3][]string{ []string{"d", "e", "f"}, []string{"g", "h", "i"}, []string{"j", "k", "l"}, } fmt.Printf("The com array %v\n", complexArray1) complexArray2 := modifyComplexArray(complexArray1) fmt.Printf("The modified: %v\n", complexArray2) fmt.Printf("The original: %v\n", complexArray1) }
true
c9706f1a672568090ba859b662f41dad5642e50d
Go
peterstace/simplefeatures
/geom/alg_point_on_surface.go
UTF-8
3,909
3.3125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package geom import ( "math" "sort" ) func newNearestPointAccumulator(target Point) nearestPointAccumulator { return nearestPointAccumulator{target: target} } // nearestPointAccumulator keeps track of the point within a group of // candidates that is nearest to a target point. type nearestPointAccumulator struct { target Point point Point dist float64 } // consider considers if a candidate point is the new nearest point to the target. func (n *nearestPointAccumulator) consider(candidate Point) { targetXY, ok := n.target.XY() if !ok { return } candidateXY, ok := candidate.XY() if !ok { return } delta := targetXY.Sub(candidateXY) candidateDist := delta.lengthSq() if n.point.IsEmpty() || candidateDist < n.dist { n.dist = candidateDist n.point = candidate } } func pointOnAreaSurface(poly Polygon) (Point, float64) { // Algorithm overview: // // 1. Find the middle Y value of the envelope around the Polygon. // // 2. If the Y value of any control points in the polygon share that // mid-envelope Y value, then choose a new Y value. The new Y value is the // average of the mid-envelope Y value and the Y value of the next highest // control point. // // 3. Construct a bisector line that crosses through the polygon at the // height of the chosen Y value. Due to the choice of Y value, this // bisector won't pass through any control point in the polygon. // // 4. Find the largest portion of the bisector line that intersects with // the Polygon. // // 5. The PointOnSurface is the midpoint of that largest portion. // Find envelope midpoint. env := poly.Envelope() mid, ok := env.Center().XY() if !ok { return Point{}, 0 } midY := mid.Y // Adjust mid-y value if a control point has the same Y. var midYMatchesNode bool nextY := math.Inf(+1) for _, ring := range poly.rings { seq := ring.Coordinates() for i := 0; i < seq.Length(); i++ { xy := seq.GetXY(i) if xy.Y == midY { midYMatchesNode = true } if xy.Y < nextY && xy.Y > midY { nextY = xy.Y } } } if midYMatchesNode { midY = (midY + nextY) / 2 } // Create bisector. envMin, envMax, ok := env.MinMaxXYs() if !ok { return Point{}, 0 } bisector := line{ XY{envMin.X - 1, midY}, XY{envMax.X + 1, midY}, } // Find intersection points between the bisector and the polygon. var xIntercepts []float64 for _, ring := range poly.rings { seq := ring.Coordinates() n := seq.Length() for i := 0; i < n; i++ { ln, ok := getLine(seq, i) if !ok { continue } inter := ln.intersectLine(bisector) if inter.empty { continue } // It shouldn't _ever_ be the case that inter.ptA is different from // inter.ptB, as this would imply that there is a line in the // polygon that is horizontal and has the same Y value as our // bisector. But from the way the bisector was constructed, this // can't happen. So we can just use inter.ptA. xIntercepts = append(xIntercepts, inter.ptA.X) } } xIntercepts = sortAndUniquifyFloats(xIntercepts) // Find largest portion of bisector that intersects the polygon. if len(xIntercepts) < 2 || len(xIntercepts)%2 != 0 { // The only way this could happen is if the input Polygon is invalid, // or there is some sort of pathological case. So we just return an // arbitrary point on the Polygon. return poly.ExteriorRing().StartPoint(), 0 } bestA, bestB := xIntercepts[0], xIntercepts[1] for i := 2; i+1 < len(xIntercepts); i += 2 { newA, newB := xIntercepts[i], xIntercepts[i+1] if newB-newA > bestB-bestA { bestA, bestB = newA, newB } } midX := (bestA + bestB) / 2 return XY{midX, midY}.asUncheckedPoint(), bestB - bestA } func sortAndUniquifyFloats(fs []float64) []float64 { if len(fs) == 0 { return fs } sort.Float64s(fs) n := 1 for i := 1; i < len(fs); i++ { if fs[i] != fs[i-1] { fs[n] = fs[i] n++ } } return fs[:n] }
true
f4f1a683c5e522b27f43ea10cc2b878a6653fb1d
Go
shankernaik/forexample
/excercises/ninja1/bool-test.go
UTF-8
159
2.96875
3
[]
no_license
[]
no_license
package main import ("fmt") var x bool func main(){ fmt.Println(x) x=true fmt.Println(x) a:=2 b:=3 fmt.Println(a==b) a=b fmt.Println(a==b, a != b) }
true
2e08d79b5bae6dd3da36bdcde1069024079106e2
Go
negrel/debuggo
/code_gen/log/main/utils.go
UTF-8
221
3.03125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "path/filepath" ) func addSuffix(filename, suffix string) string { ext := filepath.Ext(filename) extLen := len(ext) nameLen := len(filename) return filename[:nameLen-extLen] + suffix + ext }
true
12cf44cfdab375c1fb33c15dd8efb314c99eff4a
Go
ilham-bintang/merlin
/api/pkg/transformer/feast/features_cache.go
UTF-8
1,915
2.859375
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package feast import ( "encoding/json" "fmt" "strings" "time" feast "github.com/feast-dev/feast/sdk/go" ) type CacheKey struct { Entity feast.Row Project string } func fetchFeaturesFromCache(cache Cache, entities []feast.Row, project string) (FeaturesData, []feast.Row) { var entityNotInCache []feast.Row var featuresFromCache FeaturesData for _, entity := range entities { key := CacheKey{Entity: entity, Project: project} keyByte, err := json.Marshal(key) if err != nil { entityNotInCache = append(entityNotInCache, entity) continue } feastCacheRetrievalCount.Inc() val, err := cache.Fetch(keyByte) if err != nil { entityNotInCache = append(entityNotInCache, entity) continue } feastCacheHitCount.Inc() var cacheData FeatureData if err := json.Unmarshal(val, &cacheData); err != nil { entityNotInCache = append(entityNotInCache, entity) continue } featuresFromCache = append(featuresFromCache, cacheData) } return featuresFromCache, entityNotInCache } func insertFeaturesToCache(cache Cache, data entityFeaturePair, project string, ttl time.Duration) error { key := CacheKey{ Entity: data.entity, Project: project, } keyByte, err := json.Marshal(key) if err != nil { return err } dataByte, err := json.Marshal(data.value) if err != nil { return err } return cache.Insert(keyByte, dataByte, ttl) } func insertMultipleFeaturesToCache(cache Cache, cacheData []entityFeaturePair, project string, ttl time.Duration) error { var errorMsgs []string for _, data := range cacheData { if err := insertFeaturesToCache(cache, data, project, ttl); err != nil { errorMsgs = append(errorMsgs, fmt.Sprintf("(value: %v, with message: %v)", data.value, err.Error())) } } if len(errorMsgs) > 0 { compiledErrorMsgs := strings.Join(errorMsgs, ",") return fmt.Errorf("error inserting to cached: %s", compiledErrorMsgs) } return nil }
true
0f31b332e257a9dcc8be0fde965a4fd41b723394
Go
adewoleadenigbagbe/Learning-go
/errors/learn-error.go
UTF-8
2,588
3.75
4
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "errors" "fmt" "os" ) func f1(arg int) (int, error) { if arg == 42 { return -1, errors.New("can't work with 42") } return arg + 3, nil } //using error.New() func sampError() { er := errors.New("error occured") fmt.Println(er) } //using fmt Errorf func formatError() { sampleErr := fmt.Errorf("Err is: %s", "database connection issue") fmt.Println(sampleErr) } //creating custom error type inputError struct { message string missingField string } //return message func (i *inputError) Error() string { return i.message } //return missingField func (i *inputError) getMissingField() string { return i.missingField } //note returned error is an interface func validate(name, gender string) error { if name == "" { return &inputError{message: "name is missing", missingField: "name"} } if gender == "" { return &inputError{message: "gender is missing", missingField: "gender"} } return nil } //ignore errors func openfile() { file, _ := os.Open("non-existing.txt") fmt.Println(file) } //wrapping errors type errorOne struct{} func (e errorOne) Error() string { return "Error One happended" } //wrap errors func wrapError() { e1 := errorOne{} e2 := fmt.Errorf("E2: %w", e1) e3 := fmt.Errorf("E3: %w", e2) fmt.Println(e2) fmt.Println(e3) } //unwrap errors func unwrapError() { e1 := errorOne{} e2 := fmt.Errorf("E2: %w", e1) e3 := fmt.Errorf("E3: %w", e2) fmt.Println(errors.Unwrap(e3)) fmt.Println(errors.Unwrap(e2)) fmt.Println(errors.Unwrap(e1)) } //check if two errors are equal func do() error { return errorOne{} } //why you should use errors.Is for comparison func do1() error { return fmt.Errorf("E2: %w", errorOne{}) } //wrapping error 2 type notPositive struct { num int } func (e notPositive) Error() string { return fmt.Sprintf("checkPositive: Given number %d is not a positive number", e.num) } type notEven struct { num int } func (e notEven) Error() string { return fmt.Sprintf("checkEven: Given number %d is not an even number", e.num) } func checkPositive(num int) error { if num < 0 { return notPositive{num: num} } return nil } func checkEven(num int) error { if num%2 == 1 { return notEven{num: num} } return nil } func checkPostiveAndEven(num int) error { if num > 100 { return fmt.Errorf("checkPostiveAndEven: Number %d is greater than 100", num) } err := checkPositive(num) if err != nil { return fmt.Errorf("checkPostiveAndEven: %w", err) } err = checkEven(num) if err != nil { return fmt.Errorf("checkPostiveAndEven: %w", err) } return nil }
true
02e12636948a56b4d0fec4e65819d87e4fac88be
Go
kicool/kicool.go
/dump/dump.go
UTF-8
3,921
3.015625
3
[]
no_license
[]
no_license
package dump import ( "fmt" "io" "os" r "reflect" "strconv" ) var emptyString = "" // Prints to the writer the value with indentation. func Fdump(out io.Writer, v_ interface{}) { // forward decl var dump0 func(r.Value, int) var dump func(r.Value, int, *string, *string) done := make(map[string]bool) dump = func(v r.Value, d int, prefix *string, suffix *string) { pad := func() { res := "" for i := 0; i < d; i++ { res += " " } fmt.Fprintf(out, res) } padprefix := func() { if prefix != nil { fmt.Fprintf(out, *prefix) } else { res := "" for i := 0; i < d; i++ { res += " " } fmt.Fprintf(out, res) } } vk := v.Kind() vt := v.Type() vts := vt.String() vks := vk.String() vl := 0 vc := 0 switch vk { case r.Map, r.String: vl = v.Len() case r.Array, r.Chan, r.Slice: vc = v.Cap() vl = v.Len() case r.Struct: vl = v.NumField() default: //panic } // prevent circular for composite types switch vk { case r.Array, r.Slice, r.Map, r.Ptr, r.Struct, r.Interface: if v.CanAddr() { addr := v.Addr() key := fmt.Sprintf("%x %s", addr, vts) if _, exists := done[key]; exists { padprefix() fmt.Fprintf(out, "<%s>", key) return } else { done[key] = true } } else { } default: // do nothing } switch vk { case r.Array: padprefix() fmt.Fprintf(out, "%s:%s (l=%d c=%d) {\n", vks, vts, vl, vc) for i := 0; i < vl; i++ { dump0(v.Index(i), d+1) if i != vl-1 { fmt.Fprintln(out, ",") } } fmt.Fprintln(out) pad() fmt.Fprint(out, "}") case r.Slice: padprefix() fmt.Fprintf(out, "%s:%s (l=%d c=%d) {\n", vks, vts, vl, vc) for i := 0; i < vl; i++ { dump0(v.Index(i), d+1) if i != vl-1 { fmt.Fprintln(out, ",") } } fmt.Fprintln(out) pad() fmt.Fprint(out, "}") case r.Map: padprefix() fmt.Fprintf(out, "%s:%s (l=%d) {\n", vks, vts, vl) for i, k := range v.MapKeys() { dump0(k, d+1) fmt.Fprint(out, ": ") dump(v.MapIndex(k), d+1, &emptyString, nil) if i != vl-1 { fmt.Fprintln(out, ",") } } fmt.Fprintln(out) pad() fmt.Fprint(out, "}") case r.Ptr: padprefix() if v.Elem() == r.ValueOf(nil) { //Zero Value fmt.Fprintf(out, "(*%s) nil", vts) } else { fmt.Fprintf(out, "ptr:*%s:&", r.Indirect(v).Type().String()) dump(v.Elem(), d, &emptyString, nil) } case r.Struct: padprefix() fmt.Fprintf(out, "%s {\n", vts) d += 1 for i := 0; i < vl; i++ { pad() fmt.Fprint(out, vt.Field(i).Name) fmt.Fprint(out, "/") fmt.Fprint(out, vt.Field(i).Type) fmt.Fprint(out, ": ") dump(v.Field(i), d, &emptyString, nil) if i != vl-1 { fmt.Fprintln(out, ",") } } d -= 1 fmt.Fprintln(out) pad() fmt.Fprint(out, "}") case r.Interface: padprefix() fmt.Fprintf(out, "(%s) ", vts) dump(v.Elem(), d, &emptyString, nil) case r.String: padprefix() fmt.Fprint(out, strconv.Quote(v.String())) case r.Bool, r.Int, r.Int8, r.Int16, r.Int32, r.Int64, r.Uint, r.Uint8, r.Uint16, r.Uint32, r.Uint64, r.Float32, r.Float64: padprefix() //printv(o.Interface()); ok := false var i interface{} if v.CanInterface() { i = v.Interface() stringer, ok := i.(interface { String() string }) if ok { fmt.Fprintf(out, "(%s) %s", vts, stringer.String()) } } if !ok { fmt.Fprint(out, i) } case r.Invalid: padprefix() fmt.Fprint(out, "<Invalid>") default: padprefix() fmt.Fprintf(out, "(%v)", vt) } } dump0 = func(v r.Value, d int) { dump(v, d, nil, nil) } v := r.ValueOf(v_) dump0(v, 0) fmt.Fprintf(out, "\n") } // Print to standard out the value that is passed as the argument with indentation. // Pointers are dereferenced. func Dump(v_ interface{}) { Fdump(os.Stdout, v_) }
true
b08422ea3561863f22921ca0762d1ff904325e58
Go
go-phorce/dolly
/cmd/dollypki/hsm/lskey.go
UTF-8
2,413
2.53125
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package hsm import ( "fmt" "time" "github.com/go-phorce/dolly/cmd/dollypki/cli" "github.com/go-phorce/dolly/ctl" "github.com/go-phorce/dolly/xpki/cryptoprov" "github.com/pkg/errors" ) // LsKeyFlags specifies flags for the Keys action type LsKeyFlags struct { // Token specifies slot token Token *string // Serial specifies slot serial Serial *string // Prefix specifies key label prefix Prefix *string } func ensureLsKeyFlags(f *LsKeyFlags) *LsKeyFlags { var ( emptyString = "" ) if f.Token == nil { f.Token = &emptyString } if f.Serial == nil { f.Serial = &emptyString } if f.Prefix == nil { f.Prefix = &emptyString } return f } // Keys shows keys func Keys(c ctl.Control, p interface{}) error { flags := ensureLsKeyFlags(p.(*LsKeyFlags)) keyProv, ok := c.(*cli.Cli).CryptoProv().Default().(cryptoprov.KeyManager) if !ok { return errors.Errorf("unsupported command for this crypto provider") } isDefaultSlot := *flags.Serial == "" && *flags.Token == "" filterSerial := *flags.Serial if filterSerial == "" { filterSerial = "--@--" } filterLabel := *flags.Token if filterLabel == "" { filterLabel = "--@--" } out := c.Writer() printSlot := func(slotID uint, description, label, manufacturer, model, serial string) error { if isDefaultSlot || serial == filterSerial || label == filterLabel { fmt.Fprintf(out, "Slot: %d\n", slotID) fmt.Fprintf(out, " Description: %s\n", description) fmt.Fprintf(out, " Token serial: %s\n", serial) fmt.Fprintf(out, " Token label: %s\n", label) count := 0 err := keyProv.EnumKeys(slotID, *flags.Prefix, func(id, label, typ, class, currentVersionID string, creationTime *time.Time) error { count++ fmt.Fprintf(out, "[%d]\n", count) fmt.Fprintf(out, " Id: %s\n", id) fmt.Fprintf(out, " Label: %s\n", label) fmt.Fprintf(out, " Type: %s\n", typ) fmt.Fprintf(out, " Class: %s\n", class) fmt.Fprintf(out, " Version: %s\n", currentVersionID) if creationTime != nil { fmt.Fprintf(out, " Created: %s\n", creationTime.Format(time.RFC3339)) } return nil }) if err != nil { return errors.WithMessagef(err, "failed to list keys on slot %d", slotID) } if *flags.Prefix != "" && count == 0 { fmt.Fprintf(out, "no keys found with prefix: %s\n", *flags.Prefix) } } return nil } return keyProv.EnumTokens(isDefaultSlot, printSlot) }
true
c8b7e517b0934571ae7fe3157c7451ba64284e58
Go
JakubGogola-IDENTT/mpa
/lab2/permutations/permutations.go
UTF-8
1,120
3.53125
4
[]
no_license
[]
no_license
package permutations // SetSize sets size of permutation func (p *Permutation) SetSize(size int) { p.Size = size } // Permute permutes permutation func (p *Permutation) Permute() { perm := make([]int, p.Size) for i := range perm { perm[i] = i } unpermuted := make([]int, p.Size) copy(unpermuted, perm) for i := range perm { idx := nextInt(len(unpermuted)) perm[i] = unpermuted[idx] unpermuted = remove(unpermuted, idx) } p.Perm = perm } // Properties returns numbers of cycles, records and fixed points func (p *Permutation) Properties() (cycles, records, fixedPoints int) { visited := make(map[int]bool) perm := p.Perm for i, value := range perm { slice := perm[:i] isRecord := true for _, v := range slice { if v >= value { isRecord = false break } } if isRecord { records++ } if _, ok := visited[i]; ok { continue } start := i next := perm[start] visited[start] = true if start == next { fixedPoints++ } for next != start { visited[next] = true next = perm[next] } cycles++ } return cycles, records, fixedPoints }
true
95ee124bb683512ec69b254c6a61f7fd8795b20d
Go
Azure/azure-container-networking
/npm/pkg/dataplane/iptables/iptable.go
UTF-8
1,948
3.078125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
package NPMIPtable import ( "fmt" "strings" ) // Table struct type Table struct { Name string Chains map[string]*Chain } // Chain struct type Chain struct { Name string Data []byte Rules []*Rule } // Rule struct type Rule struct { Protocol string Target *Target Modules []*Module } // Module struct type Module struct { Verb string OptionValueMap map[string][]string } // Target struct type Target struct { Name string OptionValueMap map[string][]string } // for debugging func (t *Table) String() string { return fmt.Sprintf("IPTABLE NAME - %v\n%s\n", t.Name, t.printIptableChains()) } func (t *Table) printIptableChains() string { var ret strings.Builder for k, v := range t.Chains { ret.WriteString(fmt.Sprintf("\tIPTABLE CHAIN NAME - %v\n%s\n", k, t.printIptableChainRules(v))) } return ret.String() } func (t *Table) printIptableChainRules(chain *Chain) string { var ret strings.Builder for k, v := range chain.Rules { ret.WriteString(fmt.Sprintf("\t\tRULE %v\n", k)) ret.WriteString(fmt.Sprintf("\t\t\tRULE'S PROTOCOL - %v\n", v.Protocol)) ret.WriteString(t.printIptableRuleModules(v.Modules)) ret.WriteString(t.printIptableRuleTarget(v.Target)) } return ret.String() } func (t *Table) printIptableRuleModules(mList []*Module) string { var ret strings.Builder ret.WriteString("\t\t\tRULE'S MODULES\n") for i, v := range mList { ret.WriteString(fmt.Sprintf("\t\t\t\tModule %v\n", i)) ret.WriteString(fmt.Sprintf("\t\t\t\t\tVerb - %v\n", v.Verb)) ret.WriteString(fmt.Sprintf("\t\t\t\t\tOptionValueMap - %+v\n", v.OptionValueMap)) } return ret.String() } func (t *Table) printIptableRuleTarget(target *Target) string { var ret strings.Builder ret.WriteString("\t\t\tRULE'S TARGET\n") ret.WriteString(fmt.Sprintf("\t\t\t\tNAME - %v\n", target.Name)) ret.WriteString(fmt.Sprintf("\t\t\t\tOptionValueMap - %+v\n", target.OptionValueMap)) return ret.String() }
true
ac796e8e1499d0f29cb6766d2ec2adbe33ba0c72
Go
Cloud-repos/epinio
/helpers/kubernetes/interactive_options_reader_test.go
UTF-8
5,812
2.984375
3
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
package kubernetes_test import ( "bytes" "io/ioutil" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/epinio/epinio/helpers/kubernetes" ) var _ = Describe("InteractiveOptionsReader", func() { stdin := &bytes.Buffer{} stdout := &bytes.Buffer{} reader := NewInteractiveOptionsReader(stdout, stdin) option := InstallationOption{ Name: "Option", Value: "", Description: "This is a very needed option", Type: StringType, } optionSpecified := InstallationOption{ Name: "Option", Value: "User Specified Dummy", Description: "This option got a user specified value", Type: StringType, UserSpecified: true, } optionDefault := InstallationOption{ Name: "Option", Value: "", Default: "Hello World", Description: "This is a very needed option", Type: StringType, } optionDefaultKeep := InstallationOption{ Name: "Option", Value: "", Default: "Hello World", Description: "This is a very needed option", Type: StringType, } Describe("Read", func() { It("ignores an option with a user-specified value", func() { err := reader.Read(&optionSpecified) Expect(err).ToNot(HaveOccurred()) // Verify that there was neither prompt nor other output prompt, err := ioutil.ReadAll(stdout) Expect(err).ToNot(HaveOccurred()) Expect(string(prompt)).To(Equal("")) // Verify that the option value was not touched resultStr, ok := optionSpecified.Value.(string) Expect(ok).To(BeTrue()) Expect(resultStr).To(Equal("User Specified Dummy")) Expect(optionSpecified.UserSpecified).To(BeTrue()) }) It("prompts the user for input on stdin", func() { stdin.Write([]byte("userDefinedValue\n")) err := reader.Read(&option) Expect(err).ToNot(HaveOccurred()) prompt, err := ioutil.ReadAll(stdout) Expect(err).ToNot(HaveOccurred()) Expect(string(prompt)).To(ContainSubstring("This is a very needed option")) resultStr, ok := option.Value.(string) Expect(ok).To(BeTrue()) Expect(resultStr).To(Equal("userDefinedValue")) Expect(option.UserSpecified).To(BeTrue()) }) It("shows the default in the prompt", func() { stdin.Write([]byte("userDefinedValue\n")) err := reader.Read(&optionDefault) Expect(err).ToNot(HaveOccurred()) prompt, err := ioutil.ReadAll(stdout) Expect(err).ToNot(HaveOccurred()) Expect(string(prompt)).To(ContainSubstring("Hello World")) resultStr, ok := optionDefault.Value.(string) Expect(ok).To(BeTrue()) Expect(resultStr).To(Equal("userDefinedValue")) Expect(optionDefault.UserSpecified).To(BeTrue()) }) It("keeps the default when no value is entered by the user", func() { stdin.Write([]byte("\n")) err := reader.Read(&optionDefaultKeep) Expect(err).ToNot(HaveOccurred()) prompt, err := ioutil.ReadAll(stdout) Expect(err).ToNot(HaveOccurred()) Expect(string(prompt)).To(ContainSubstring("Hello World")) resultStr, ok := optionDefaultKeep.Value.(string) Expect(ok).To(BeTrue()) Expect(resultStr).To(Equal("Hello World")) Expect(optionDefaultKeep.UserSpecified).To(BeTrue()) }) When("the option is BooleanType", func() { var option InstallationOption BeforeEach(func() { option = InstallationOption{ Name: "Option", Value: "", Description: "This is a boolean option", Type: BooleanType, } }) It("returns a boolean", func() { stdin.Write([]byte("y\n")) err := reader.Read(&option) Expect(err).ToNot(HaveOccurred()) resultBool, ok := option.Value.(bool) Expect(ok).To(BeTrue()) Expect(resultBool).To(BeTrue()) Expect(option.UserSpecified).To(BeTrue()) }) It("asks again if the answer is not 'y' or 'n'", func() { stdin.Write([]byte("other\ny\n")) err := reader.Read(&option) Expect(err).ToNot(HaveOccurred()) prompt, err := ioutil.ReadAll(stdout) Expect(err).ToNot(HaveOccurred()) Expect(string(prompt)).To( ContainSubstring("It's either 'y' or 'n', please try again")) resultBool, ok := option.Value.(bool) Expect(ok).To(BeTrue()) Expect(resultBool).To(BeTrue()) Expect(option.UserSpecified).To(BeTrue()) }) }) When("the option is IntType", func() { var option InstallationOption BeforeEach(func() { option = InstallationOption{ Name: "Option", Value: "", Description: "This is an integer option", Type: IntType, } }) It("returns an integer", func() { stdin.Write([]byte("55\n")) err := reader.Read(&option) Expect(err).ToNot(HaveOccurred()) resultInt, ok := option.Value.(int) Expect(ok).To(BeTrue()) Expect(resultInt).To(Equal(55)) Expect(option.UserSpecified).To(BeTrue()) }) It("asks again if the answer is not an integer", func() { stdin.Write([]byte("other\n66\n")) err := reader.Read(&option) Expect(err).ToNot(HaveOccurred()) prompt, err := ioutil.ReadAll(stdout) Expect(err).ToNot(HaveOccurred()) Expect(string(prompt)).To( ContainSubstring("Please provide an integer value")) resultInt, ok := option.Value.(int) Expect(ok).To(BeTrue()) Expect(resultInt).To(Equal(66)) Expect(option.UserSpecified).To(BeTrue()) }) }) When("the option is bogus", func() { var option InstallationOption BeforeEach(func() { option = InstallationOption{ Name: "Option", Value: "", Description: "This is a bogus option with a bogus type", Type: 22, } }) It("returns an error", func() { err := reader.Read(&option) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(Equal("Internal error: option Type not supported")) }) }) }) })
true
99ccc244ef2391d31e4ed0b799c5cdaa79d3d2da
Go
cttipton/iminshell.com
/main.go
UTF-8
3,354
2.59375
3
[]
no_license
[]
no_license
package main import ( "crypto/tls" "log" "net/http" //"io/ioutil" //"fmt" //"net/url" ) //set header for all handlers instead of configuring each one. Credit Adam Ng https://www.socketloop.com/tutorials/golang-set-or-add-headers-for-many-or-different-handlers func SetHeaders(w http.ResponseWriter) { w.Header().Set("X-Frame-Options", "SAMEORIGIN") w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload") w.Header().Set("Allow", "OPTIONS, GET, HEAD, POST") w.Header().Set("Content-Security-Policy", "default-src 'none'; font-src 'https://fonts.googleapis.com'; img-src 'self' https://i.imgur.com; object-src 'none'; script-src 'self'; style-src 'self'; frame-ancestors 'self'; base-uri 'self'; form-action 'self'; 'stric-dynamic'") w.Header().Set("Set-Cookie", "__Host-BMOSESSIONID=YnVnemlsbGE=; Max-Age=2592000; Path=/; Secure; HttpOnly; SameSite=Strict") w.Header().Set("Referrer-Policy", "no-referrer, strict-origin-when-cross-origin") w.Header().Set("X-Content-Type-Options","nosniff") w.Header().Set("X-XSS-Protection", "1; mode=block") } func redirectTLS(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "https://"+r.Host+":443"+r.RequestURI, http.StatusMovedPermanently) } func index(w http.ResponseWriter, req *http.Request) { SetHeaders(w) // w.Header().Add("Strict-Transport-Security", "max-age=63072000; includeSubDomains") // w.Write([]byte("This is an example server.\n")) if req.URL.Path != "/" { log.Printf("404: %s", req.URL.String()) http.NotFound(w, req) return } http.ServeFile(w, req, "index.html") } func faviconHandler(w http.ResponseWriter, r *http.Request) { SetHeaders(w) http.ServeFile(w, r, "favicon.png") } func art(w http.ResponseWriter, r *http.Request) { SetHeaders(w) http.ServeFile(w, r, "art.png") } func main() { //lets start an unencrypted http server, for the purposes of redirect go http.ListenAndServe(":80", http.HandlerFunc(redirectTLS)) //mux up a router mux := http.NewServeMux() mux.HandleFunc("/favicon.png", faviconHandler) mux.HandleFunc("/art.png", art) //make sure we can renew LetsEncrypt Certs. Below handle will allow LetsEncrypt and our webserver to verify one another. mux.Handle("/.well-known/acme-challenge/", http.StripPrefix("/.well-known/acme-challenge/", http.FileServer(http.FileSystem(http.Dir("/tmp/letsencrypt/"))))) //Point us home mux.HandleFunc("/", index) //func(w http.ResponseWriter, req *http.Request) { //webserver config, this gets A+ on Qualys scan if you're sure to bind to 443 with full cert chain--not just server.crt. cfg := &tls.Config{ MinVersion: tls.VersionTLS12, CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, PreferServerCipherSuites: true, CipherSuites: []uint16{ tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, }, } srv := &http.Server{ Addr: ":443", Handler: mux, TLSConfig: cfg, TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0), } log.Println(srv.ListenAndServeTLS("/etc/ssl/iminshell.com.pem", "/etc/ssl/iminshell.com.key")) }
true
8444e87625c8fdfbe5fe63ade2ac0c5d98f05ed8
Go
typeck/golib
/aws/s3.go
UTF-8
1,044
2.671875
3
[]
no_license
[]
no_license
package aws import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3/s3manager" ) //s3manager.UploadInput{ // Bucket: aws.String(bucket), // Key: aws.String(filePath), // Body: bytes.NewReader(file), // } //size: buffer size func UploadS3(region string,in *s3manager.UploadInput, size int)error{ // All clients require a Session. The Session provides the client with // shared configuration such as region, endpoint, and credentials. A // Session should be shared where possible to take advantage of // configuration and credential caching. See the session package for // more information. sess := session.Must(session.NewSession(&aws.Config{ Region: aws.String(region), })) uploader := s3manager.NewUploader(sess, func(u *s3manager.Uploader) { // Define a strategy that will buffer 25 MiB in memory u.BufferProvider = s3manager.NewBufferedReadSeekerWriteToPool(size) }) _, err := uploader.Upload(in) if err != nil { return err } return nil }
true
d9573fed80f8dd14e3257edfccee82a8a239ee56
Go
zeek0x/real-world-http
/src/06.02.04/client/main.go
UTF-8
1,192
2.734375
3
[]
no_license
[]
no_license
package main import ( "crypto/tls" "log" "net/http" "net/http/httputil" ) func main() { cert, err := tls.LoadX509KeyPair("ssl/client.crt", "ssl/client.key") if err != nil { panic(err) } client := &http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{ Certificates: []tls.Certificate{cert}, }, }, } resp, err := client.Get("https://localhost:18443") if err != nil { panic(err) } defer resp.Body.Close() dump, err := httputil.DumpResponse(resp, true) if err != nil { panic(err) } log.Println(string(dump)) } /* うまくいかない... 証明書作成手順は ./ssl/README.md に従う $ server.go $ go run main.go 2020/11/02 02:46:58 http: TLS handshake error from 127.0.0.1:59754: remote error: tls: bad certificate $ cd client $ go run main.go panic: Get "https://localhost:18443": x509: certificate signed by unknown authority (possibly because of "x509: invalid signature: parent certificate cannot sign this kind of certificate" while trying to verify candidate authority certificate "example.com") goroutine 1 [running]: main.main() /workspaces/real-world-http/src/06.02.04/client/main.go:26 +0x3a3 exit status 2 */
true
d48607c471fd161bfa2a82645707e3709cc08977
Go
searKing/golang
/go/database/sql/placeholder.go
UTF-8
4,394
2.90625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
// Copyright 2020 The searKing Author. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package sql import ( "fmt" "strings" strings_ "github.com/searKing/golang/go/strings" ) // Placeholders behaves like strings.Join([]string{"?",...,"?"}, ",") func Placeholders(n int) string { return strings_.JoinRepeat("?", ",", n) } // Pagination returns the "LIMIT %d, OFFSET %d" // query := Pagination(0, 0) // // "LIMIT 0, OFFSET 0" func Pagination(limit, offset int) string { if limit < 0 || offset < 0 { return "" } return fmt.Sprintf("LIMIT %d OFFSET %d", limit, offset) } // ExpandAsColumns expand columns with alias AS // query := ExpandAsColumns("table.foo", "bar") // // []string{"table.foo AS table_foo", "bar AS bar"} func ExpandAsColumns(cols ...string) []string { cols = strings_.SliceTrimEmpty(cols...) var params []string for _, col := range cols { params = append(params, fmt.Sprintf("%[1]s AS %[2]s", col, CompliantName(col))) } return params } // TableColumns returns the []string{table.value1, table.value2 ...} // query := Columns("table", "foo", "bar") // // []string{"table.foo", "table.bar"} func TableColumns(table string, cols ...string) []string { cols = strings_.SliceTrimEmpty(cols...) var namedCols []string for _, col := range cols { if table == "" { namedCols = append(namedCols, col) } else { namedCols = append(namedCols, fmt.Sprintf("%s.%s", table, col)) } } return namedCols } // TableValues returns the []string{:value1, :value2 ...} // query := TableValues("foo", "bar") // // []string{"?", "?"} func TableValues(cols ...string) []string { cols = strings_.SliceTrimEmpty(cols...) var namedCols []string for range cols { namedCols = append(namedCols, "?") } return namedCols } // TableColumnsValues returns the []string{table.value1=:value1, table.value2=:value2 ...} // query := ColumnsValues("table", "foo", "bar") // // []string{"table.foo=?", "table.bar=?"} func TableColumnsValues(cmp string, table string, cols ...string) []string { cols = strings_.SliceTrimEmpty(cols...) var namedCols []string for _, col := range cols { if table == "" { namedCols = append(namedCols, fmt.Sprintf("%[1]s %[2]s ?", col, cmp)) } else { namedCols = append(namedCols, fmt.Sprintf("%[1]s.%[2]s %[3]s ?", table, col, cmp)) } } return namedCols } // JoinTableColumns concatenates the elements of cols to column1, column2, ... // query := JoinTableColumns("table", "foo", "bar") // // "table.foo, table.bar" func JoinTableColumns(table string, cols ...string) string { //cols = strings_.SliceTrimEmpty(cols...) return strings.Join(TableColumns(table, cols...), ",") } // JoinTableColumnsWithAs concatenates the elements of cols to column1, column2, ... // query := JoinTableColumnsWithAs("table", "foo", "bar") // // "table.foo AS table.foo, table.bar AS table.bar" func JoinTableColumnsWithAs(table string, cols ...string) string { //cols = strings_.SliceTrimEmpty(cols...) return strings.Join(ExpandAsColumns(TableColumns(table, cols...)...), ",") } // JoinColumns concatenates the elements of cols to column1, column2, ... // query := JoinColumns("foo", "bar") // // "foo,bar" func JoinColumns(cols ...string) string { return JoinTableColumns("", cols...) } // JoinColumnsWithAs concatenates the elements of cols to column1, column2, ... // query := JoinColumnsWithAs("foo", "bar") // // "foo AS foo,bar AS bar" func JoinColumnsWithAs(cols ...string) string { return JoinTableColumnsWithAs("", cols...) } // JoinTableValues concatenates the elements of values to :value1, :value2, ... // query := JoinTableValues("foo", "bar") // // "?,?" // query := JoinTableValues() // // "" func JoinTableValues(cols ...string) string { cols = strings_.SliceTrimEmpty(cols...) if len(cols) == 0 { // https://dev.mysql.com/doc/refman/5.7/en/data-type-defaults.html // DEFAULT return "" } return strings.Join(TableValues(cols...), ",") } // JoinTableColumnsValues concatenates the elements of values to table.value1=:value1, table.value2=:value2 ... // query := JoinTableColumnsValues("table", "foo", "bar") // // "table.foo=?, table.bar=?" func JoinTableColumnsValues(cmp string, table string, cols ...string) string { //cols = strings_.SliceTrimEmpty(cols...) return strings.Join(TableColumnsValues(cmp, table, cols...), ",") }
true
0eff2c4c2dbeb227db0b3207d94b636b8a6bf3bb
Go
RyanBrushett/battlesnake2020
/pkg/structs/coordinate.go
UTF-8
317
3.796875
4
[]
no_license
[]
no_license
package structs // Coordinate refers to a square on a board type Coordinate struct { X int `json:"x"` Y int `json:"y"` } // Add the values of Coordinate other to Coordinate c func (c Coordinate) Add(other Coordinate) Coordinate { result := Coordinate{ X: c.X + other.X, Y: c.Y + other.Y, } return result }
true
6d5a80c94ecca0887847f8c32598bad14ac1af60
Go
atvoid/blackA
/user/user.go
UTF-8
2,570
2.921875
3
[]
no_license
[]
no_license
package user import ( "blackA/logging" "bufio" "encoding/json" "fmt" "net" ) var area string = "User" type User struct { Id int Name string conn *net.Conn stopSigConn chan bool stopSigMsg chan bool userInput chan Command UserInput chan Command ServerInput chan Command Disconnected bool RoomId int } func CreateUser(id int, name string, conn *net.Conn) *User { u := User{Id: id, Name: name, conn: conn} u.ServerInput = make(chan Command, 10) u.userInput = make(chan Command, 10) u.stopSigConn = make(chan bool, 1) u.stopSigMsg = make(chan bool, 1) return &u } func (this *User) ResetConnection(conn *net.Conn) { this.stopSigConn <- true this.conn = conn } func (this *User) clearChannel() { for i := len(this.stopSigConn); i > 0; i-- { <-this.stopSigConn } for i := len(this.stopSigMsg); i > 0; i-- { <-this.stopSigMsg } } func (this *User) HandleConnection() { this.clearChannel() go this.receiveMsg() logging.LogInfo_Normal(area, fmt.Sprintf("Starting to handle user %v\n", this.Id)) PollLoop: for { select { case cc := <-this.userInput: // logging.LogInfo(area, fmt.Sprintf("Got Msg from %v with %v\n", this.Id, cc.ToMessage())) if cc.CmdType == CMDTYPE_PING { continue } this.UserInput <- cc case c := <-this.ServerInput: c.UserId = this.Id this.sendMsg(c) case <-this.stopSigConn: logging.LogInfo_Detail(area, fmt.Sprintf("Terminate handling connection from %v\n", this.Id)) this.stopSigMsg <- true break PollLoop } } logging.LogInfo_Normal(area, fmt.Sprintf("End to handle user %v\n", this.Id)) } func (this *User) receiveMsg() { PollMsgLoop: for { select { case <-this.stopSigMsg: logging.LogInfo_Detail(area, fmt.Sprintf("Terminate receiving Msg from %v\n", this.Id)) break PollMsgLoop default: msg, err := bufio.NewReader(*this.conn).ReadBytes('\u0001') //fmt.Printf("Got Msg %v \n", string(msg)) if err == nil { msg = msg[:len(msg)-1] //fmt.Printf("Got Msg %v \n", string(msg)) var cmd Command err := json.Unmarshal(msg, &cmd) //fmt.Printf("%v", cmd.ToMessage()) //uInput <- cmd cmd.UserId = this.Id this.userInput <- cmd if err != nil { logging.LogError(area, err.Error()) } } else { logging.LogError(area, err.Error()) this.userInput <- Command{CmdType: CMDTYPE_DISCONNECT, UserId: this.Id} this.stopSigConn <- true break PollMsgLoop } } } } func (this *User) sendMsg(c Command) { (*this.conn).Write([]byte(c.ToMessage() + "\u0001")) }
true
9d8dd599691e4cb311cd9c6ff650e1b8639f2e7e
Go
yiippee/esim
/tool/new/domain_fc.go
UTF-8
1,677
2.921875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package new var ( domainfc1 = &FileContent{ FileName: "user.go", Dir: "internal/domain/user/entity", Content: `package entity type User struct { // ID ID int {{.SingleMark}}gorm:"column:id;primary_key"{{.SingleMark}} // username UserName string {{.SingleMark}}gorm:"column:user_name"{{.SingleMark}} // pwd PassWord string {{.SingleMark}}gorm:"column:pass_word"{{.SingleMark}} } func (u User) CheckPwd(pwd string) bool { if pwd == "" { return false } if u.PassWord == pwd { return true } return false } `, } domainfc2 = &FileContent{ FileName: "README.md", Dir: "internal/domain/user/service", Content: `domain service`, } domainfc3 = &FileContent{ FileName: "user_test.go", Dir: "internal/domain/user/entity", Content: `package entity import "testing" func TestUser_CheckPwd(t *testing.T) { type fields struct { ID int UserName string PassWord string } type args struct { pwd string } tests := []struct { name string fields fields args args want bool }{ {"check right", fields{1, "test1", "123456"}, args{"123456"}, true}, {"check error", fields{1, "test1", "123456"}, args{"111111"}, false}, {"empty pwd", fields{1, "test1", "123456"}, args{""}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { u := User{ ID: tt.fields.ID, UserName: tt.fields.UserName, PassWord: tt.fields.PassWord, } if got := u.CheckPwd(tt.args.pwd); got != tt.want { t.Errorf("User.CheckPwd() = %v, want %v", got, tt.want) } }) } } `, } ) func initDomainFiles() { Files = append(Files, domainfc1, domainfc2, domainfc3) }
true
b32c83625b3daeda79c74c6827f5e1777d6f56d7
Go
seaon/sept
/backend/utils/app/response.go
UTF-8
1,215
2.953125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package response import ( "github.com/gin-gonic/gin" "net/http" ) type Response struct { Code int `json:"code"` Msg string `json:"msg"` Data interface{} `json:"data"` } const ( SUCCESS = 0 ERROR = 10 AuthFailed = 20 AuthExpired = 21 InvalidArgument = 100 ) var empty map[string]string func Result(code int, data interface{}, msg string, c *gin.Context) { // 开始时间 c.JSON(http.StatusOK, Response{ code, msg, data, }) } func Ok(c *gin.Context) { Result(SUCCESS, empty, "操作成功", c) } func OkWithMessage(message string, c *gin.Context) { Result(SUCCESS, empty, message, c) } func OkWithData(data interface{}, c *gin.Context) { Result(SUCCESS, data, "操作成功", c) } func OkDetailed(data interface{}, message string, c *gin.Context) { Result(SUCCESS, data, message, c) } func Fail(c *gin.Context) { Result(ERROR, empty, "失败", c) } func FailWithMessage(message string, c *gin.Context) { Result(ERROR, empty, message, c) } func FailWithCode(code int, message string, c *gin.Context) { Result(code, empty, message, c) } func FailWithDetailed(code int, message string, c *gin.Context) { Result(code, empty, message, c) }
true
e7f173725d1b125514debdfb7e481305b10cd36f
Go
mjsir911/szip
/reader.go
UTF-8
3,679
2.8125
3
[]
no_license
[]
no_license
package szip import ( "io" "archive/zip" "encoding/binary" "compress/flate" "errors" "fmt" ) type Reader struct { r io.Reader cur io.ReadCloser // Central directory fields, unused mid-extraction n int centralDirectory bool } func NewReader(ri io.Reader) (ro Reader) { ro.r = ri ro.n = 0 ro.centralDirectory = false return } var decompressors map[uint16]zip.Decompressor func init() { decompressors = make(map[uint16]zip.Decompressor) decompressors[zip.Store] = io.NopCloser decompressors[zip.Deflate] = flate.NewReader } const ( LOCALRECORD uint32 = 0x04034b50 CENTRALRECORD uint32 = 0x2014b50 EOCD uint32 = 0x06054b50 ) func readHeader(signature uint32, r io.Reader) (h zip.FileHeader, err error) { if signature != LOCALRECORD && signature != CENTRALRECORD { // h is empty & should be unused here return h, errors.New(fmt.Sprintf("szip: Invalid signature: %x", signature)) } if signature == CENTRALRECORD { binary.Read(r, binary.LittleEndian, &h.CreatorVersion) } binary.Read(r, binary.LittleEndian, &h.ReaderVersion) binary.Read(r, binary.LittleEndian, &h.Flags) binary.Read(r, binary.LittleEndian, &h.Method) binary.Read(r, binary.LittleEndian, &h.ModifiedTime) binary.Read(r, binary.LittleEndian, &h.ModifiedDate) h.Modified = h.ModTime() binary.Read(r, binary.LittleEndian, &h.CRC32) binary.Read(r, binary.LittleEndian, &h.CompressedSize) h.CompressedSize64 = uint64(h.CompressedSize) binary.Read(r, binary.LittleEndian, &h.UncompressedSize) h.UncompressedSize64 = uint64(h.UncompressedSize) var namelen uint16 binary.Read(r, binary.LittleEndian, &namelen) name := make([]byte, namelen) var extralen uint16 binary.Read(r, binary.LittleEndian, &extralen) h.Extra = make([]byte, extralen) var comment []byte if signature == CENTRALRECORD { var commentlen uint16 binary.Read(r, binary.LittleEndian, &commentlen) comment = make([]byte, commentlen) var diskNbr uint16 binary.Read(r, binary.LittleEndian, &diskNbr) var internalAttrs uint16 binary.Read(r, binary.LittleEndian, &internalAttrs) binary.Read(r, binary.LittleEndian, &h.ExternalAttrs) var offset uint32 binary.Read(r, binary.LittleEndian, &offset) } binary.Read(r, binary.LittleEndian, &name) h.Name = string(name) binary.Read(r, binary.LittleEndian, &h.Extra) if signature == CENTRALRECORD { binary.Read(r, binary.LittleEndian, &comment) h.Comment = string(comment) } return } func (r *Reader) CentralDirectory() (files []zip.FileHeader, err error) { if !r.centralDirectory { return nil, errors.New("Not ready to read central directory") } r.centralDirectory = false files = make([]zip.FileHeader, 0, r.n) // r.n is just a suggestion for signature := CENTRALRECORD; signature != EOCD; binary.Read(r.r, binary.LittleEndian, &signature) { var chdr zip.FileHeader if chdr, err = readHeader(signature, r.r); err != nil { return } files = append(files, chdr) } return } func (r *Reader) Next() (h zip.FileHeader, err error) { if r.cur != nil { io.ReadAll(r.cur) } var signature uint32 binary.Read(r.r, binary.LittleEndian, &signature) if signature == CENTRALRECORD { r.centralDirectory = true // collection is punted to CentralDirectory() return h, io.EOF // h is empty here } if h, err = readHeader(signature, r.r); err != nil { return } r.n += 1 r.cur = decompressors[h.Method](io.LimitReader(r.r, int64(h.CompressedSize64))) return } func (r Reader) Read(b []byte) (n int, err error) { return r.cur.Read(b) } func (r Reader) WriteTo(w io.Writer) (n int64, err error) { return io.Copy(w, r.cur) } func (r Reader) Close() error { return r.cur.Close() }
true
9d871ec2283929c53d403ff16af6db92e01a3402
Go
stormforger/cli
/api/meta.go
UTF-8
3,594
2.59375
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package api import ( "encoding/json" "fmt" "io" "log" "github.com/stormforger/cli/internal/esbundle" ) // Meta holds meta data of a JSONApi response. Currently // only "links" are extracted. type Meta struct { Links *Links `json:"links"` } // Links holds JSONAPI links type Links struct { Self string `json:"self"` SelfWeb string `json:"self_web"` TestCase string `json:"test_case"` } // ErrorPayload holds the list of returned JSONAPI errors type ErrorPayload struct { Message string `json:"message"` Errors []ErrorDetail `json:"errors"` } // ErrorDetail holds data on a specific JSONAPI error type ErrorDetail struct { Code string `json:"code"` Title string `json:"title"` Detail string `json:"detail"` MetaRaw json.RawMessage `json:"meta"` FormattedError string } // EvaluationErrorMeta holds meta data on JS Evaluation errors type EvaluationErrorMeta struct { Message string `json:"message"` RawStack string `json:"raw_stack"` Name string `json:"name"` Stack []EvaluationStackFrame `json:"stack"` } // EvaluationStackFrame represents a stack frame returned by // evaluation errors type EvaluationStackFrame struct { Context string `json:"context"` File string `json:"file"` Line int `json:"line"` Column int `json:"column"` Eval bool `json:"eval"` Anonymous bool `json:"anonymous"` Internal bool `json:"internal"` } // UnmarshalMeta will take a io.Reader and try to parse // "meta" information from a JSONApi response. func UnmarshalMeta(input io.Reader) (Meta, error) { var data struct { Meta *Meta `json:"data"` } if err := json.NewDecoder(input).Decode(&data); err != nil { return Meta{}, err } return *data.Meta, nil } type ErrorDecoder struct { SourceMapper esbundle.SourceMapper } // UnmarshalErrorMeta will take the response (io.Reader) and // will extract JSONAPI errors. func (dec ErrorDecoder) UnmarshalErrorMeta(input io.Reader) (ErrorPayload, error) { var data ErrorPayload if err := json.NewDecoder(input).Decode(&data); err != nil { return ErrorPayload{}, err } for i, e := range data.Errors { switch e.Code { case "E0": data.Errors[i].FormattedError = e.Detail case "E23": errorMeta := new(EvaluationErrorMeta) err := json.Unmarshal(e.MetaRaw, errorMeta) if err != nil { log.Fatal(err) } if dec.SourceMapper != nil { errorMeta.Stack = updateStackFramesFromSourceMapper(errorMeta.Stack, dec.SourceMapper) } data.Errors[i].FormattedError = errorMeta.String() } } return data, nil } func (e EvaluationErrorMeta) String() string { backtrace := fmt.Sprintf("%s: %s\n", e.Name, e.Message) for _, frame := range e.Stack { location := "" if frame.Anonymous == false { location = fmt.Sprintf("%s:%d:%d", frame.File, frame.Line, frame.Column) } else { location = "<anonymous>" } if frame.Context != "" { backtrace += fmt.Sprintf(" at %s (%s)\n", frame.Context, location) } else { backtrace += fmt.Sprintf(" at %s\n", location) } } return backtrace } func updateStackFramesFromSourceMapper(frames []EvaluationStackFrame, mapper esbundle.SourceMapper) []EvaluationStackFrame { for idx, frame := range frames { if frame.Internal { continue } src, name, line, col, ok := mapper(frame.Line, frame.Column) if ok { frame.File = src frame.Line = line if name != "" { frame.Context = name } frame.Column = col frames[idx] = frame } } return frames }
true
0c2a90f0c0f5bfb672ca965481d75e0500edd8ee
Go
gospodinzerkalo/todo_app_golang
/endpoint/task/postgre.go
UTF-8
1,479
2.9375
3
[]
no_license
[]
no_license
package task import ( "github.com/go-pg/pg" "github.com/go-pg/pg/orm" ) //Config struct type PostgreConfig struct { User string Password string Port string Host string Database string } //Connection to postgre (for task) func NewPostgre(config PostgreConfig) (TaskTodo,error) { db := pg.Connect(&pg.Options{ Addr: config.Host + ":" + config.Port, User: config.User, Password: config.Password, Database:config.Database, }) err := db.CreateTable(&Task{},&orm.CreateTableOptions{ IfNotExists: true, }) if err!= nil { return nil,err } return &postgreStore{db: db},nil } //db func. type postgreStore struct { db *pg.DB } //DeleteTask ... func (p postgreStore) DeleteTask(id int) error { task := &Task{ID: id} err := p.db.Delete(task) if err != nil{ return err } return nil } //GetListTask ... func (p postgreStore) GetListTask() ([]*Task, error) { var tasks []*Task err := p.db.Model(&tasks).Select() if err != nil { return nil, err } return tasks, nil } //UpdateTask ... func (p postgreStore) UpdateTask(id int, task *Task) (*Task, error) { task.ID = id err := p.db.Update(task) return task, err } //GetTask ... func (p postgreStore) GetTask(id int) (*Task, error) { task := &Task{ID: id} err := p.db.Select(task) if err != nil { return nil, err } return task, nil } //CreateTask ... func (p postgreStore) CreateTask(task *Task) (*Task, error) { res := p.db.Insert(task) return task, res }
true
e6ed294ac235f1b7d07ce2fdf04cfe6ca7c3e077
Go
mathom/piepan
/plugins/lua/plugin.go
UTF-8
2,059
2.515625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package plugin import ( "fmt" "os" "strings" "sync" "github.com/aarzilli/golua/lua" "github.com/mathom/piepan" "github.com/stevedonovan/luar" ) func init() { piepan.Register("lua", &piepan.Plugin{ Name: "Lua (C)", New: func(in *piepan.Instance) piepan.Environment { s := luar.Init() p := &Plugin{ instance: in, state: s, listeners: make(map[string][]*luar.LuaObject), } luar.Register(s, "piepan", luar.Map{ "On": p.apiOn, "Disconnect": p.apiDisconnect, }) s.GetGlobal("piepan") s.NewTable() luar.Register(s, "*", luar.Map{ "Play": p.apiAudioPlay, "IsPlaying": p.apiAudioIsPlaying, "Stop": p.apiAudioStop, "NewTarget": p.apiAudioNewTarget, "SetTarget": p.apiAudioSetTarget, "Bitrate": p.apiAudioBitrate, "SetBitrate": p.apiAudioSetBitrate, "Volume": p.apiAudioVolume, "SetVolume": p.apiAudioSetVolume, }) s.SetField(-2, "Audio") s.NewTable() luar.Register(s, "*", luar.Map{ "New": p.apiTimerNew, }) s.SetField(-2, "Timer") s.NewTable() luar.Register(s, "*", luar.Map{ "New": p.apiProcessNew, }) s.SetField(-2, "Process") s.SetTop(0) return p }, }) } type Plugin struct { instance *piepan.Instance stateLock sync.Mutex state *lua.State listeners map[string][]*luar.LuaObject } func (p *Plugin) LoadScriptFile(filename string) error { return p.state.DoFile(filename) } func (p *Plugin) apiOn(l *lua.State) int { event := strings.ToLower(l.CheckString(1)) function := luar.NewLuaObject(l, 2) p.listeners[event] = append(p.listeners[event], function) return 0 } func (p *Plugin) apiDisconnect(l *lua.State) int { if client := p.instance.Client; client != nil { client.Disconnect() } return 0 } func (p *Plugin) error(err error) { fmt.Fprintf(os.Stderr, "%s\n", err) } func (p *Plugin) callValue(callback *luar.LuaObject, args ...interface{}) { p.stateLock.Lock() if _, err := callback.Call(args...); err != nil { p.error(err) } p.stateLock.Unlock() }
true
9abde4aa7761eeff8d66863e241b66af1b9dc85c
Go
nrkfeller/learn_go
/golangbasics/17maps/loopmap/loopmap.go
UTF-8
185
3.421875
3
[]
no_license
[]
no_license
package main import "fmt" func main() { ele := map[string]string{ "O": "oxygen", "N": "nitrogen", "C": "carbon", } for k, v := range ele { fmt.Println(k, "is for", v) } }
true
2940775a2106b50377078aaa1f1c71d2bc5720d6
Go
ivyhaswell/learn_golang
/methods/exercise-images.go
UTF-8
909
3.84375
4
[]
no_license
[]
no_license
/* 练习:图像 还记得之前编写的图片生成器 吗?我们再来编写另外一个,不过这次它将会返回一个 image.Image 的实现而非一个数据切片。 定义你自己的 Image 类型,实现必要的方法并调用 pic.ShowImage。 Bounds 应当返回一个 image.Rectangle ,例如 image.Rect(0, 0, w, h)。 ColorModel 应当返回 color.RGBAModel。 At 应当返回一个颜色。上一个图片生成器的值 v 对应于此次的 color.RGBA{v, v, 255, 255}。 */ package main import ( "golang.org/x/tour/pic" "image" "image/color" ) type Image struct { w, h int v uint8 } func (i Image) Bounds() image.Rectangle { return image.Rect(0, 0, i.w, i.h) } func (i Image) ColorModal() color.Model { return color.RGBAModel } func (i Image) At() color.RGBA { return color.RGBA{i.v, i.v, 255, 255} } func main() { m := Image{100, 100, 100} pic.ShowImage(m) }
true
bb5cda0dc519c66967789cd5fa0b7ab1fa600f4d
Go
GuilhermeVendramini/golang-web
/02-server/04-dial-read/main.go
UTF-8
325
2.71875
3
[]
no_license
[]
no_license
/* Edit your "/etc/hots" and add: 127.0.1.1 go */ package main import ( "fmt" "io/ioutil" "log" "net" ) func main() { conn, err := net.Dial("tcp", "go:80") if err != nil { panic(err) } defer conn.Close() bs, err := ioutil.ReadAll(conn) if err != nil { log.Println(err) } fmt.Println(string(bs)) }
true
375390031b3d6a481d78e4619ccc871680f890c7
Go
hjnnewton/POI
/src/api/gerSurround.go
UTF-8
1,433
2.890625
3
[]
no_license
[]
no_license
package location import ( "go-simplejson" //"github.com/bitly/go-simplejson" "encoding/json" ) // According to the latitude and longitude, return the surrounding places information func GetSurrounding(latitude string, longitude string, ak string)[]interface {}{ body:=GeoCoder(latitude, longitude, ak) js, err := simplejson.NewJson([]byte(body)) if err != nil { panic(err.Error()) } surroundings, _ := json.Marshal(js.Get("result")) var mapTmp []interface{} var dat map[string]interface{} if err := json.Unmarshal([]byte(string(surroundings)), &dat); err == nil { // Transfer json str into map type mapTmp = dat["pois"].([]interface {}) //fmt.Println(GetNames(mapTmp)) //fmt.Println(GetInfo(mapTmp, 2)) return mapTmp } // Return value is a list of maps of information of surrounding places return mapTmp } // Return the names of the surrounding places func GetNames(result []interface{})[]string{ var names []string for _, poi := range result { //fmt.Println(poi.(map[string]interface{})["name"]) names = append(names, poi.(map[string]interface{})["name"].(string)) } return names } // Return the information of specific place, index is the ith place returned func GetInfo(result []interface{}, index int)map[string]interface{}{ var info map[string]interface{} if index < len(result){ info = result[index].(map[string]interface{}) // point := info["point"] return info } return info }
true
b0291852e4a8427aa32650f613be4dbcae243668
Go
Foxcapades/Argonaut
/v0/internal/render/flag-group.go
UTF-8
2,146
2.78125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package render import ( A "github.com/Foxcapades/Argonaut/v0/pkg/argo" "strings" ) const ( fgDefaultName = "Flag Group" fgShortPrefix = '-' fgLongPrefix = "--" fgShortAssign = sngSpace fgLongAssign = '=' fgDivider = " | " fgEmptyDiv = " " fgPadding = " " ) func flagGroup(fg A.FlagGroup, out *strings.Builder) { if !fg.HasFlags() { return } if fg.HasName() { out.WriteString(fg.Name()) } else { out.WriteString(fgDefaultName) } out.WriteByte(sngLineBreak) result := flagNames(fg.Flags()) pad := result.sLen + result.lLen + len(fgDivider) + (len(fgPadding) * 2) for i, flag := range fg.Flags() { hasShort := result.shorts[i] != "" hasLong := result.longs[i] != "" out.WriteString(fgPadding) WritePadded(result.shorts[i], result.sLen, out) if hasLong && hasShort { out.WriteString(fgDivider) } else { out.WriteString(fgEmptyDiv) } WritePadded(result.longs[i], result.lLen, out) if flag.HasDescription() { out.WriteString(fgPadding) BreakFmt(flag.Description(), pad, maxWidth, out) } out.WriteByte(sngLineBreak) } } type flagResult struct { shorts []string longs []string sLen int lLen int } func flagNames(flags []af) (out flagResult) { ln := len(flags) bld := strings.Builder{} out.shorts = make([]string, ln) out.longs = make([]string, ln) bld.Grow(10) bld.Reset() for i, flag := range flags { var arg string if flag.HasArgument() { FormattedArgName(flag.Argument(), &bld) arg = bld.String() bld.Reset() } if flag.HasShort() { bld.WriteByte(fgShortPrefix) bld.WriteByte(flag.Short()) if len(arg) > 0 { bld.WriteByte(fgShortAssign) bld.WriteString(arg) } out.shorts[i] = bld.String() bld.Reset() if len(out.shorts[i]) > out.sLen { out.sLen = len(out.shorts[i]) } } if flag.HasLong() { bld.WriteString(fgLongPrefix) bld.WriteString(flag.Long()) if len(arg) > 0 { bld.WriteByte(fgLongAssign) bld.WriteString(arg) } out.longs[i] = bld.String() bld.Reset() if len(out.longs[i]) > out.lLen { out.lLen = len(out.longs[i]) } } } return }
true
5984e199a85eb0d9a44cde077e323dbb2264b9a8
Go
shreyanshchordia/Binary-Trees
/Go/binary_tree_traversals.go
UTF-8
1,723
4.34375
4
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "fmt" ) /* * Problem :: Print the binary tree using following traversal * 1) InOrder * 2) PreOrder * 3) PostOrder */ /** * Definition for a binary tree node. */ type TreeNode struct { Val int Left *TreeNode Right *TreeNode } /** * functions to print various traversal for binary tree * each functions returns array containing preferred order */ func inOrder(root *TreeNode) []int { if root == nil { return []int{} } array := make([]int, 0) array = append(array, inOrder(root.Left)...) array = append(array, root.Val) array = append(array, inOrder(root.Right)...) return array } func preOrder(root *TreeNode) []int{ array := make([]int, 0) if root == nil { return array } array = append(array, root.Val) array = append(array, preOrder(root.Left)...) array = append(array, preOrder(root.Right)...) return array } func postOrder(root *TreeNode) []int { array := make([]int, 0) if root == nil { return array } array = append(array, postOrder(root.Left)...) array = append(array, postOrder(root.Right)...) array = append(array, root.Val) return array } func main() { /** * Test-case to check correctness * 1 * / \ * 2 3 * / * 4 * Longest Path from root to leaf is [1-2-4] i.e length 3 */ node4 := TreeNode{Val: 4, Left: nil, Right: nil} node3 := TreeNode{Val: 3, Left: nil, Right: nil} node2 := TreeNode{Val: 2, Left: &node4, Right: nil} root := &TreeNode{Val: 1, Left: &node2, Right: &node3} fmt.Printf("InOrder: %v\n", inOrder(root)) fmt.Printf("PreOrder: %v\n", preOrder(root)) fmt.Printf("PostOrder: %v\n", postOrder(root)) }
true
12bb7e09add8ffed64a311b6cbd75e0e0ebb86a7
Go
lutepluto/leetcode
/problem70/climb_stairs.go
UTF-8
223
2.734375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package problem70 func climbStairs(n int) int { if n <= 2 { return n } ways := make([]int, n+1) ways[0] = 0 ways[1] = 1 ways[2] = 2 for i := 3; i <= n; i++ { ways[i] = ways[i-1] + ways[i-2] } return ways[n] }
true
2d05e612fa5c1b9a5c8d9109b399d4b220a62013
Go
mdigger/passbook
/beacon.go
UTF-8
843
2.734375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package passbook import ( "encoding/json" "errors" ) // Beacon Dictionary: Information about a location beacon. Available in iOS 7.0. type Beacon struct { ProximityUUID string `json:"proximityUUID"` // Unique identifier of a Bluetooth Low Energy location beacon. Major uint16 `json:"major,omitempty"` // Major identifier of a Bluetooth Low Energy location beacon. Minor uint16 `json:"minor,omitempty"` // Minor identifier of a Bluetooth Low Energy location beacon. RelevantText string `json:"relevantText,omitempty"` // Text displayed on the lock screen when the pass is currently relevant. } func (b Beacon) Marshal() ([]byte, error) { if b.ProximityUUID == "" { return nil, errors.New("Unique identifier of a Bluetooth Low Energy location beacon must be set") } return json.Marshal(b) }
true
14dad71e9f0e6815de3e0fde2f2746f1ebe8f63c
Go
whefter/rotating-rsync-backup
/constants.go
UTF-8
820
2.640625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import "regexp" // DailyFolderName is a helper constant holding the name of the daily backup grouping folder const DailyFolderName string = "_daily" // WeeklyFolderName is a helper constant holding the name of the weekly backup grouping folder const WeeklyFolderName string = "_weekly" // MonthlyFolderName is a helper constant holding the name of the monthly backup grouping folder const MonthlyFolderName string = "_monthly" // BackupFolderTimeFormat is the time format used to format backup folder names and parse // them back into a time instance const BackupFolderTimeFormat string = "2006-01-02_15-04-05" // BackupFolderNameRegex will match a correct backup folder name (with no suffixes) var BackupFolderNameRegex = regexp.MustCompile("^(\\d{4})-(\\d{2})-(\\d{2})_(\\d{2})-(\\d{2})-(\\d{2})$")
true
fd2c71f3d622eb1d2337d7cd789a29c401546f9d
Go
facuellarg/design_patterns
/singleton/singleton/manager.go
UTF-8
414
3.53125
4
[]
no_license
[]
no_license
package singleton import "sync" type manager struct { value int } var managerSingleton *manager var mutext sync.Mutex func GetManager() *manager { mutext.Lock() defer mutext.Unlock() if managerSingleton == nil { managerSingleton = &manager{} } return managerSingleton } func (m *manager) Add() { mutext.Lock() defer mutext.Unlock() m.value++ } func (m *manager) GetValue() int { return m.value }
true
a503865375833c66b94057cf96b063ebd4910107
Go
svetlana-rezvaya/go-dice-cli
/parse_dice_notation.go
UTF-8
699
3.265625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package dice import ( "errors" "fmt" "strconv" "strings" ) // ParseDiceNotation ... // Example of input data: "2d20", "d20" (it means "1d20"). func ParseDiceNotation(text string) (throwCount int, faceCount int, err error) { parts := strings.Split(text, "d") if len(parts) != 2 { return 0, 0, errors.New("invalid count of parts") } if parts[0] == "" { throwCount = 1 } else { throwCount, err = strconv.Atoi(parts[0]) if err != nil { return 0, 0, fmt.Errorf("unable to parse the throw count: %s", err) } } faceCount, err = strconv.Atoi(parts[1]) if err != nil { return 0, 0, fmt.Errorf("unable to parse the face count: %s", err) } return throwCount, faceCount, nil }
true
fad65a74fd7834a95c403826d0b26ede7242b20f
Go
zeppel13/pygoas
/code.go
UTF-8
19,545
3.375
3
[]
no_license
[]
no_license
/* code.go * This file is part of pygoas * * This is probably going to be a simple Mini-Python to NASM-assembly compiler * written by Sebastian Kind 2nd Janury -- 20th May 2016 */ package main import ( "fmt" "strconv" ) // programCode is the essential struct (comparable to a class in // python) which contains the logic necessary to compile code for // example variables, labels, indents and espacially the assembly // source code, which was written by the compiler. // A Struct is similar to a class in Python. Variables and other // Valueholding are declared inside of a struct. // Go -- Python // struct -- class // slice -- list // map -- dictionary type programCode struct { intMap map[string]int64 stringMap map[string]string strCounter int64 // 64 because pygoas is a 64bit compiler :P commentFlag bool labelFlag bool labelCounter int64 forLoopFlag bool loopVarCounter int64 funcSlice []string lastLabel []string indentLevel int code string funcCode []string } // constructor of programCode // Go wants contructors look the following function. func newProgramCode() programCode { var code programCode code.intMap = make(map[string]int64) code.stringMap = make(map[string]string) code.strCounter = 0 code.funcSlice = make([]string, 100) // TODO: Make this more dynamic e.g.: zero-length slice with dynamic append() code.lastLabel = make([]string, 100) // TODO: Make this more dynamic e.g.: zero-length slice with dynamic append() code.labelCounter = 0 code.indentLevel = 0 code.labelFlag = false code.forLoopFlag = false code.code = "" code.funcCode = make([]string, 100) // TODO: Make this more dynamic e.g.: zero-length slice with dynamic append() return code } // This method appends the raw nasm assmebly code to the output // program. func (pc *programCode) appendCode(code string) { pc.funcCode[pc.indentLevel] += code // Append Code to processed indent level } // This method adds new Variables to the compiler logic and to the // output program. Variables are unsigned 64 Bit wide integers // 0...2**64 (python-power) func (pc *programCode) addVar(name string, val int64) { // the following line checks if an element exists inside the map element. if _, ok := pc.intMap[name]; ok { pc.setVar(name, val) } else { pc.intMap[name] = val } } // This method sets a Variable to a known value while the compiled binary is running. func (pc *programCode) setVar(name string, val int64) { code := "" strVal := strconv.FormatInt(val, 10) code += "\tmov rax, " + strVal + "\t;set " + name + " to " + strVal + "\n" code += "\tmov [" + name + "], rax \n" pc.appendCode(code) } // The builtin print code will be created by the compiler everytime // print is called inside the (mini)python program. It accepts somehow // variadic parameters. // usage of print: print ("text", variable, variable, "text", ...) /* ;print: mov rax, 1 ;syscall: write print value mov rdi, 1 ; stdout is the 'output file' mov rsi, value ; ptr mov rdx, 1 ; len syscall ;ret */ // createPrint only prints one letter/char/byte at the time. The // stringlength in |rdx| has the value 1. // FIXME: Is this funtion in use? func (pc *programCode) createPrint(s string) { print := "\tmov rax, 1\t;print " + s + "\n\tmov rdi, 1\n\tmov rdx, 1\n\tmov rsi, " + s + "\n\tsyscall\n" pc.appendCode(print) } // createPrintString is able to print a whole string. func (pc *programCode) createPrintString(sname string) { len := (int64)(len(pc.stringMap[sname])) - 2 // FIXME: WTF int64. Why not use int and strconv.Atoi(var string) // and stringcon.Itoa(var int) strlen := strconv.FormatInt(len, 10) code := "\tmov rax, 1\t;print String" + sname + "\n\tmov rdi, 1\n\tmov rdx, " + strlen + "\n\tmov rsi, " + sname + "\n\tsyscall\n" pc.appendCode(code) } /* mov eax, [var1] add eax, [var2] mov [var3], eax */ // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+// // Mathsnippets The following code templates are appended to the // output program to do ugly numbercrunshing work The following // functions' parameters are names of variables inside the output // program // createAdd("AnzahlMurmeln", "MurmelSack3000", "AnzahlMurmeln") ? // Addition func (pc *programCode) createAdd(a, b, sum string) { code := "\n\t\t\t; Add " + b + " to " + a + " and save sum in " + sum + "\n" if _, err := strconv.Atoi(a); err == nil { code += "\tmov rax, " + a + "\n" } else { code += "\tmov rax, [" + a + "]\n" } if _, err := strconv.Atoi(b); err == nil { code += "\tadd rax, " + b + "\n" } else { code += "\tadd rax, [" + b + "]\n" } code += "\tmov [" + sum + "], rax\n" pc.appendCode(code) } // Subtraction func (pc *programCode) createSub(m, s, dif string) { code := "\n\t\t\t; Substract " + s + " from " + m + " and save difference in " + dif + "\n" if _, err := strconv.Atoi(m); err == nil { code += "\tmov rax, " + m + "\n" } else { code += "\tmov rax, [" + m + "]\n" } if _, err := strconv.Atoi(s); err == nil { code += "\tsub rax, " + s + "\n" } else { code += "\tsub rax, [" + s + "]\n" } code += "\tmov [" + dif + "], rax\n" pc.appendCode(code) } // Multiplication func (pc *programCode) createMul(a, b, prod string) { code := "\n\t\t\t; Multiply " + a + " with " + b + " and store product in " + prod + "\n" if _, err := strconv.Atoi(a); err == nil { code += "\tmov rax, " + a + "\n" } else { code += "\tmov rax, [" + a + "]\n" } if _, err := strconv.Atoi(b); err == nil { code += "\timul rax, " + b + "\n" } else { code += "\timul rax, [" + b + "]\n" } code += "\tmov [" + prod + "], rax\n" pc.appendCode(code) } // Division /* mov rax, [divisor] ;divides rax by rbx remainder is stored in rdx quotient is stored in rax mov rbx, [dividend] div rbx mov [q], rax ;; quotient mov [r], rdx ;; remainder */ // Make shure to not divide by zero. It'll cause a floting point error // and program will crash. This feature is still buggy. func (pc *programCode) createDiv(divisor, dividend, quotient, remainder string) { divcode := "\n\t\t\t; Divide " + divisor + " by " + dividend + " and safe quotient in " + quotient + "\n" divcode += "\t\t\t; Safe remainder in " + remainder + "\n" if _, err := strconv.Atoi(divisor); err == nil { divcode += "\tmov rax, " + divisor + "\n" } else { divcode += "\tmov rax, [" + divisor + "]\n" } if _, err := strconv.Atoi(dividend); err == nil { divcode += "\tmov rbx, " + dividend + "\n" } else { divcode += "\tmov rbx, [" + dividend + "]\n" } divcode += "\tdiv rbx\n" if quotient != "" { divcode += "\tmov [" + quotient + "], rax\n" } if remainder != "" { divcode += "\tmov [" + remainder + "], rdx\n" } pc.appendCode(divcode) } // End of Math //*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*//*// // createParams the code to copy values into argument registers // as defined in the *amd64 System V calling convention* // Marginal Note: MiniPython functions can'take any arguments still not a supported feature* // FIXME: Is this in use? // As long as argSlice delivers a value, it'll be thrown in one of the // following registers as ordered in registerSlice. On this way six // 64bit numbers may be passed over to the called function, which can // easily read from the registers. func (pc *programCode) createParams(argSlice []string) { code := "" registerSlice := []string{"rdi", "rsi", "rdx", "rcx", "r8", "r9"} // SysV ABI calling register for parameters for i := 0; i < len(argSlice) && i < 6; i++ { if _, err := strconv.Atoi(argSlice[i]); err == nil { code += "\tmov " + registerSlice[i] + argSlice[i] + "\n" } else { code += "\tmov " + registerSlice[i] + "[" + argSlice[i] + "]\n" } } pc.appendCode(code) } // createCall allows the label passed as string argument to be // called. //"call" executes a function inside assembly. It cleanes used // registers before and after the function did its job. -> amd64 Sys V // abi // FIXME: 'jmp vs. call'? func (pc *programCode) createCall(name string) { code := "" code += "\n\tcall " + name + "\t; call label " + name + "\n" pc.appendCode(code) } // crateLabel marks a label inside the assembly source code. It also // increments the indentLevel counter, in order to write the following // code block into a separated buffer. Labels can be called or jumped // to. createLabel accepts the label's name as a argument func (pc *programCode) createLabel(name string) { code := "" code += "\n" + name + ":\n" pc.funcSlice = append(pc.funcSlice, name) pc.indentLevel += 1 // dive deeper -> next buffer. // Please have a look to FIXME: Where can I find what? pc.appendCode(code) } // createReturn leaves the innermost function/indent buffer by // decrementing the pc.indentLevel. It is the last function appending // information to a asm-Code block. func (pc *programCode) createReturn() { code := "\tret\n" pc.appendCode(code) pc.indentLevel-- // get back -> buffer before } // createJump allows the final program to jump to a label. This is // used for functions. FIXME: Rest(for, if)? func (pc *programCode) createJump(label string) { code := "" code += "\tjmp " + label + "\t; jmp to " + label + "\n" pc.appendCode(code) } // createJumpBackLabel writes a label to the main code to which the // final program can jump back after a functions, if-clause or // for-loop was finished // Interesting function call: // pc.pushLastLabel(label) places the label (func, if, for, etc) onto // a stack memory, in order to remind the program where it should jump // next func (pc *programCode) createJumpBackLabel(category string) { code := "" strlabelCounter := strconv.FormatInt(pc.labelCounter, 10) label := category + strlabelCounter pc.pushLastLabel(label) code += "\t" + label + ":\t; return point\n" pc.appendCode(code) } func (pc *programCode) createJumpBack() { code := "" label := pc.popLastLabel() code += "\tjmp " + label + "\t; return to last place\n" pc.appendCode(code) pc.indentLevel-- } // createResetLoopVar appends a code snippet to pc.code which resets a // loopVarN to a given value. // Is this funtions necessary? Why not use programCode.SetVar(int64, string)? func (pc *programCode) createResetLoopVar(name string, val int) { valStr := strconv.Itoa(val) code := "" code += "\tmov rax, " + valStr + "\t;reset LoopVar to" + valStr + "\n" code += "\t mov [" + name + "], rax;\t done\n" pc.appendCode(code) } // The compiler has a stack to manage nested functions, conditions and // loops. It is still a so called Brechstangen-Methode due to the // inflexibility of Go's slices compared to Python's lists. Slices // refer to an underlying array of something. They are basically a pointer // to the real chunk of date used, which has some dynamic aspects. // pc.LastLabel[n] represents the postion of a label in the hierarchy // of a running program. // A generic funtion to let the stack grow and shrink is indispensable // for a MiniPython program which consists of a lot branching for example // conditions, loops, functions. The sad trueth is that a limited // brechstangen-code sets the borders of a MiniPython system. // Branching should work good enough within eight stack layers. func (pc *programCode) pushLastLabel(name string) { // errors happend often enough to place some debug logic here. The // really ugly and terminal filling printed debug messages should // mainly show the changes made to the stack. if debug == 2 { fmt.Println("Lastlabel stack before push") for i, v := range pc.lastLabel { // iterate over the stack'n'print it. fmt.Println("Number", i, ":", v) } } // FIXME: Fix this! // #Brechstangen Methode pc.lastLabel[8] = pc.lastLabel[7] pc.lastLabel[7] = pc.lastLabel[6] pc.lastLabel[6] = pc.lastLabel[5] pc.lastLabel[5] = pc.lastLabel[4] pc.lastLabel[4] = pc.lastLabel[3] pc.lastLabel[3] = pc.lastLabel[2] pc.lastLabel[2] = pc.lastLabel[1] pc.lastLabel[1] = pc.lastLabel[0] pc.lastLabel[0] = name if debug == 2 { fmt.Println("Lastlabel stack after push:") for i, v := range pc.lastLabel { fmt.Println("Number", i, ":", v) } } } // popLastLabel() pops a lable from the stack. The label is returned as a string. func (pc *programCode) popLastLabel() string { // These debug messags show how the stack was changed. See // pushLastLabel(name string) for more information if debug == 2 { fmt.Println("Lastlabel stack before pop:") for i, v := range pc.lastLabel { fmt.Println("Number", i, ":", v) } } // Popping labels off the stack just works fine. No one fears a // Brechstangen-Methode to appear here anytime soon. label := "" if len(pc.lastLabel) != 0 { label = pc.lastLabel[0] } if len(pc.lastLabel)-1 > 1 { pc.lastLabel = pc.lastLabel[1 : len(pc.lastLabel)-1] } // These debug messags show how the stack was changed if debug == 2 { fmt.Println("Lastlabel stack after pop:") for i, v := range pc.lastLabel { fmt.Println("Number", i, ":", v) } } return label } // FIXME: DONE // <s> The BAUSTELLE! : Solved on Monday July 27th // For loops are working but still strange to use. The loopvariable // can('t) be accessed by their predefined name and appended counter // number e.g. loopVar0, loopVar1, loopVar3 counting is still // necessarry. Todo: Change loopVar32 to something more general like </s> // // for loops just work fine // This is the code snipped checking the condition inside an assembly loop. func (pc *programCode) createForCheck(loopVar string) { code := "\n\tmov rax, [" + loopVar + "] \t; for-loop\n" code += "\tdec rax\n\tmov [" + loopVar + "], rax\n" forJmpBackLabel := pc.popLastLabel() code += "\tcmp rax, 0\n\tjle " + forJmpBackLabel + "\t; if zero close loop\n\t \n" // Fixed this line pc.appendCode(code) } // createCmp(a, b string) initialises a comparison of two values in // the assembly code. The funtion tries to read a variable identifier, // but it'll interpret the token as a numeric value if this is // possible. /* ;; Assembly for n00bs. mov rax, [a] mov rbx, [b] cmp rax ;; check camparison with conditional jump (|j**|) after |cmp|. */ // necessary for conditionss in assembly // a, b are variable identifier; or may be numbers stored in strings func (pc *programCode) createCmp(a, b string) { code := "\t\t\t; compare " + a + " with " + b + "\n" if _, err := strconv.Atoi(a); err == nil { code += "\tmov rax, " + a + "\n" } else { code += "\tmov rax, [" + a + "]\n" } if _, err := strconv.Atoi(b); err == nil { code += "\tmov rbx, " + b + "\n" } else { code += "\tmov rbx, [" + b + "]\n" } code += "\tcmp rax, rbx\n" pc.appendCode(code) } // The following methods are responible for the boolean logic of the // compiled program. They create a jump to the If-Satementsbody code, // when their condition is true. No Expression handling is // involved. Everything is hard coded. func (pc *programCode) isEqual(label string) { code := "" code += "\tmov rax, 1\t; check equality\n" if label != "" { code += "\tje " + label + "\t; if so jump to " + label + "\n" } // Why if var != "" { ... }. What was the reason for this? What // error should it prevent? pc.appendCode(code) } func (pc *programCode) isGreater(label string) { code := "" code += "\tmov rax, 1\t; check equality\n" if label != "" { code += "\tjg " + label + "\t; if so jump to " + label + "\n" } pc.appendCode(code) // Ideas of handling boolean expressions // jge call true ?? // mov rax, 1 // true // mov rax, 0 // false } func (pc *programCode) isSmaller(label string) { code := "" code += "\tmov rax, 1\t; check equality\n" if label != "" { code += "\tjl " + label + "\t; if so jump to " + label + "\n" } pc.appendCode(code) // mov rax, 1 // true // mov rax, 0 // false } func (pc *programCode) isGreaterEqual(label string) { code := "" code += "\tmov rax, 1\t; check equality\n" if label != "" { code += "\tjge " + label + "\t; if so jump to " + label + "\n" } pc.appendCode(code) // mov rax, 1 // true // mov rax, 0 // false } func (pc *programCode) isSmallerEqual(label string) { code := "" code += "\tmov rax, 1\t; check equality\n" if label != "" { code += "\tjle " + label + "\t; if so jump to " + label + "\n" } pc.appendCode(code) // mov rax, 1 // true // mov rax, 0 // false } // --------- END OF COMPARISON OPERATOR CODE ------------ // createStart() writes an assembly template to the code. An official header, a start label func (pc *programCode) createStart() { start := "section .text\nglobal _start\n_start:\n" pc.code += start } // createExit(val srting) writes a exit statement to the code. The // return status is transmitted as argument string. // assembly for n00bs: // mov rax, 60 ;; close me // mov rdi, 0 ;; no error // syscall ;; linux please! func (pc *programCode) createExit(val string) { code := "" code += "\tmov rax, 60\t; exit program\n\tmov rdi, " + val + "\n\tsyscall\n" pc.funcCode[0] += code // Appends this code snippet to the first // level of indentation e.g. main-function } // createAllFunctions() adds all the functions' buffers to the final // sourced code at the end of the compiling process. func (pc *programCode) createAllFunctions() { for _, v := range pc.funcCode { pc.code += v // Finally chunk everything to a string! } } /* mov eax, var1Value mov [var1], eax */ // The BSS-Segmet allows to reserve n-byte sized space in the main memory. // Those space chunks are tagged with a name which represents their address in the source code. // [someVar] -- get the value of the memory chunk behind the someName like *someVar // someVar -- gets the address of the memory chunk like &someVar // initBssVars() fills the reserverd space with variables' values. func (pc *programCode) initBssVars() { code := "\t\t\t;; fill .bss variables with their values\n" for k, v := range pc.intMap { s := strconv.FormatInt((int64)(v), 10) code += "\tmov rax, " + s + "\n\tmov [" + k + "], rax\n" } pc.code += code } // initVars gives every memory chunk, its value it is supposed to // hold. The final compiles MiniPython program runs the prodruced code // of initVar(...) at the beginning of its main function. func (pc *programCode) initVar(s, k string) { pc.code += "\tmov rax, " + k + "\t; newVar \n\tmov [" + s + "], rax\n" // start with these instructions } // Inline assembly can be written with the asm method its arguments // are directly appended to the active function buffer. THIS IS REALLY // HELPFULL to urgently change some internal code without // rewriting/rereading the whole compiler code especially when bugs // appear. func (pc *programCode) asm(code string) { pc.appendCode("\t" + code + "\n") } // createBss() creates a code snipped which reserves space for the // variables. This creates the .bss Segment at the end of the // assembly output code. The BSS-segment contains mutable memory // space. Which is ideal for storing all my variables there func (pc *programCode) createBss() { bssString := "\nsection .bss\n" for v := range pc.intMap { bssString += "\t" + v + ": resb 8" + "\n" } pc.code += bssString // appends this Assembly code to the end after creating all the functions } // createData() creates a code snippet which creates all the string // constants func (pc *programCode) createData() { dataString := "\nsection .data\n" for k, v := range pc.stringMap { dataString += "\t" + k + ": db " + v + "\n" } pc.code += dataString }
true
b1461f643a29242521c8552a1a401a088668a160
Go
extensible-cms/ecms-go-inputfilter
/TestFixtures.go
UTF-8
1,860
2.578125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package ecms_go_inputfilter import ( ecms_validator "github.com/extensible-cms/ecms-go-validator" "regexp" ) var ( ContactFormInputFilter InputFilter NameInput *Input EmailInput *Input SubjInput *Input MessageInput *Input ) func init() { nameValidatorOps := ecms_validator.NewRegexValidatorOptions() nameValidatorOps.Pattern = regexp.MustCompile("^[a-zA-Z][a-zA-Z\\s'\"]{4,54}$") NameValidator := ecms_validator.RegexValidator(nameValidatorOps) NameInput = NewInput("name") NameInput.Required = true NameInput.RequiredMessage = "Name is required." NameInput.AddValidator(NameValidator) EmailInput = NewInput("email") EmailInput.Required = true EmailInput.RequiredMessage = "Email is required." fakeEmailValidatorOps := ecms_validator.NewRegexValidatorOptions() fakeEmailValidatorOps.Pattern = regexp.MustCompile("^[^@]{1,55}@[^@]{1,55}$") fakeEmailValidator := ecms_validator.RegexValidator(fakeEmailValidatorOps) EmailInput.AddValidator(fakeEmailValidator) DescrLenValidatorOps := ecms_validator.NewLengthValidatorOptions() DescrLenValidatorOps.Min = 1 DescrLenValidatorOps.Max = 2048 DescrLenValidator := ecms_validator.LengthValidator(DescrLenValidatorOps) SubjInput = NewInput("subject") SubjInput.AddValidator(func() ecms_validator.Validator { lenOps := ecms_validator.NewLengthValidatorOptions() lenOps.Min = 3 lenOps.Max = 55 return ecms_validator.LengthValidator(lenOps) }()) MessageInput = NewInput("message") MessageInput.Required = true MessageInput.RequiredMessage = "Message is required." MessageInput.AddValidator(DescrLenValidator) ContactFormInputFilter = InputFilter{ Inputs: map[string]*Input{ NameInput.Name: NameInput, EmailInput.Name: EmailInput, SubjInput.Name: SubjInput, MessageInput.Name: MessageInput, }, BreakOnFailure: false, // validate all inputs } }
true
4b5f3d57019c66b7d9f31782b5ac477941dbf643
Go
sgnl19/icinga-checks-library
/ssh-session_test.go
UTF-8
531
2.6875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package icinga import "testing" func TestNewSshSessionError(t *testing.T) { tests := []struct { host string port int ssh_user string msg string }{ {"", 22, "ssh-user", "missing host"}, {"host", 0, "ssh-user", "missing port"}, {"host", 22, "", "missing ssh user"}, {"host", 22, "ssh-user", "missing ssh directory"}, } for _, test := range tests { _, err := NewSshSession(test.host, test.port, test.ssh_user) if err == nil { t.Fatalf("Failed to test missing mandatory parameter: %v", test.msg) } } }
true
6f4bcdd28ebc31e4d20cd9ae98838c791d3c0fd9
Go
wllenyj/wtime
/example/sample.go
UTF-8
1,084
2.765625
3
[]
no_license
[]
no_license
package main import ( "fmt" "github.com/wllenyj/wtime" "math" "math/rand" "os" "os/signal" "syscall" "time" ) func main() { rand.Seed(time.Now().UnixNano()) w := wtime.NewWheel(500 * time.Millisecond) f := func(d int) { dura := time.Duration(d) * 500 * time.Millisecond //fmt.Printf("start dura: %s\n", dura) ticker := w.NewTicker(dura) var cnt uint for { cnt++ start := time.Now() select { case t := <-ticker.C: end := time.Now() //if math.Abs(float64(end.Sub(start)-dura)) > float64(5000*time.Microsecond) { if math.Abs(float64(end.Sub(start)-dura)) > float64(500*time.Millisecond) && cnt > 1 { fmt.Printf("[%s] %d execout %s %s - %s sub:%s\n", dura, cnt, t, end, start, end.Sub(start)-dura) } } } } for i := 0; i < 1000000; i++ { n := rand.Int31n(30) for ; n == 0; { n = rand.Int31n(30) } n += 20 go f(int(n)) } c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGINT, ) for { s := <-c switch s { case syscall.SIGINT: goto END_FOR } } END_FOR: w.Stop() fmt.Println("quit") }
true
cc518b45d18488a951404a6a48286b95443fc022
Go
Kashiwara0205/monkey
/ast/ast.go
UTF-8
8,980
3.546875
4
[]
no_license
[]
no_license
package ast import ( "../token" "bytes" "strings" ) // 全intercace型のトップ // ここに書かれたメソッドは継承しているインターフェースで必ず実現しなければいけない type Node interface{ TokenLiteral() string String() string } // Statementノードには、どんなStatementでも入る(LetとかReturnとか) type Statement interface{ Node statementNode() } // 特徴:hoge = 5の5を保持する // 値の保持に何かと使用する。  type Expression interface{ Node expressionNode() } // 全てのStatementの親ノードに値するノード // LetやReturnなどのStatementを管理 // 抽象構文木の一番上にいる type Program struct{ // Statmentインターフェース型配列 // この中には構造体のアドレスが入る Statements []Statement } func (p *Program) TokenLiteral() string{ if len(p.Statements) > 0{ return p.Statements[0].TokenLiteral() }else{ return "" } } func (p *Program) String() string{ var out bytes.Buffer // 1階層下のノードをぽこぽこ吐き出す for _, s := range p.Statements{ out.WriteString(s.String()) } return out.String() } // Letという定義文を解析するためのノード // let x = 5などの解析に使用 // Name → hoge // Value → 5 type LetStatement struct{ Token token.Token // Nameのほうが*Identifierで固定なのは、変数名が絶対くるから Name *Identifier // Valueの方は*Identifierがくることもあれば、別の何かが来ることもある // そして、別の何かはString()を持っている Value Expression } // Statementインターフェース func (ls *LetStatement) statementNode() {} // LetStatementのTokenLiteral func (ls *LetStatement) TokenLiteral() string {return ls.Token.Literal} // String型 func (ls *LetStatement) String() string{ var out bytes.Buffer // let out.WriteString(ls.TokenLiteral() + " ") // 変数名 NameはIdenfifiter型なので、別のstring型を呼び出してる out.WriteString(ls.Name.String()) // = out.WriteString(" = ") // 代入されるべき数字 if ls.Value != nil{ out.WriteString(ls.Value.String()) } // ; out.WriteString(";") return out.String() } // LetStatementの子ノード // let x = 5のxの部分を記憶するために使用 type Identifier struct{ Token token.Token Value string } func (i *Identifier) expressionNode() {} // IdentfierのTokenLiteral func (i *Identifier) TokenLiteral() string { return i.Token.Literal } // 変数名が帰ってくる func (i *Identifier) String() string {return i.Value} // rerutn 1 などのreturn文を解析するために使用するノード type ReturnStatement struct{ Token token.Token ReturnValue Expression } func (rs *ReturnStatement) statementNode(){} func (rs *ReturnStatement) TokenLiteral() string{ return rs.Token.Literal } func(rs *ReturnStatement) String() string{ var out bytes.Buffer out.WriteString(rs.TokenLiteral() + " ") if rs.ReturnValue != nil{ out.WriteString(rs.ReturnValue.String()) } out.WriteString(";") return out.String() } // myvalue;のような式文解析に使用 type ExpressionStatement struct{ Token token.Token Expression Expression } func (es *ExpressionStatement) statementNode() {} func (es *ExpressionStatement) TokenLiteral() string { return es.Token.Literal } func (es *ExpressionStatement) String() string{ if es.Expression != nil{ return es.Expression.String() } return "" } // 5;のような式解析に使用する構文ノード type IntegerLiteral struct{ Token token.Token Value int64 } func (il *IntegerLiteral) expressionNode() {} func (il *IntegerLiteral) TokenLiteral() string {return il.Token.Literal} func (il *IntegerLiteral) String() string {return il.Token.Literal} // - や ! の解析に使う構文ノード type PrefixExpression struct{ Token token.Token Operator string Right Expression } func (pe *PrefixExpression) expressionNode() {} func (pe *PrefixExpression) TokenLiteral() string {return pe.Token.Literal} func (pe *PrefixExpression) String() string{ var out bytes.Buffer out.WriteString("(") out.WriteString(pe.Operator) out.WriteString(pe.Right.String()) out.WriteString(")") return out.String() } // <Left: 前置型で解析してできたノード> <Operator: 演算子> <Right: 前置型で解析してできたノード> // で構成された中置型のノード。 1 + 1など 1 < 1などを管理する。 type InfixExpression struct{ Token token.Token Left Expression Operator string Right Expression } func (oe *InfixExpression) expressionNode() {} func (oe *InfixExpression) TokenLiteral() string {return oe.Token.Literal} func (oe *InfixExpression) String() string{ var out bytes.Buffer out.WriteString("(") out.WriteString(oe.Left.String()) out.WriteString(" " + oe.Operator + " ") out.WriteString(oe.Right.String()) out.WriteString(")") return out.String() } type Boolean struct{ Token token.Token Value bool } func(b *Boolean) expressionNode() {} func(b *Boolean) TokenLiteral() string {return b.Token.Literal} func(b *Boolean) String() string {return b.Token.Literal} // if文構文ノード type IfExpression struct{ Token token.Token Condition Expression Consequence *BlockStatement Alternative *BlockStatement } func (ie *IfExpression) expressionNode() {} func (ie *IfExpression) TokenLiteral() string { return ie.Token.Literal } func (ie *IfExpression) String() string{ var out bytes.Buffer out.WriteString("if") out.WriteString(ie.Condition.String()) out.WriteString(" ") out.WriteString(ie.Consequence.String()) if ie.Alternative != nil{ out.WriteString("else ") out.WriteString(ie.Alternative.String()) } return out.String() } // if文の' { } 'の部分の構文ノード type BlockStatement struct{ Token token.Token Statements []Statement } func (bs *BlockStatement) StatementNode() {} func (bs *BlockStatement) TokenLiteral() string {return bs.Token.Literal} func (bs *BlockStatement) String() string{ var out bytes.Buffer for _, s := range bs.Statements{ out.WriteString(s.String()) } return out.String() } type FunctionLiteral struct{ Token token.Token Parameters []*Identifier Body *BlockStatement } func(fl *FunctionLiteral) expressionNode() {} func(fl *FunctionLiteral) TokenLiteral() string { return fl.Token.Literal} func(fl *FunctionLiteral) String() string{ var out bytes.Buffer params := []string{} for _, p := range fl.Parameters{ params = append(params, p.String()) } out.WriteString(fl.TokenLiteral()) out.WriteString("(") out.WriteString(strings.Join(params, ", ")) out.WriteString(") ") out.WriteString(fl.Body.String()) return out.String() } // add(1, 2)のようなメソッドを呼び出すための構文ノード type CallExpression struct{ Token token.Token Function Expression Arguments []Expression } func (ce *CallExpression) expressionNode() {} func (ce *CallExpression) TokenLiteral() string { return ce.Token.Literal } func (ce *CallExpression) String() string{ var out bytes.Buffer args := []string{} for _, a := range ce.Arguments{ args = append(args, a.String()) } out.WriteString(ce.Function.String()) out.WriteString("(") out.WriteString(strings.Join(args, ", ")) out.WriteString(")") return out.String() } type StringLiteral struct{ Token token.Token Value string } func (sl *StringLiteral) expressionNode() {} func (sl *StringLiteral) TokenLiteral() string { return sl.Token.Literal} func (sl *StringLiteral) String() string {return sl.Token.Literal} type ArrayLiteral struct{ Token token.Token Elements []Expression } func (al *ArrayLiteral) expressionNode() {} func (al *ArrayLiteral) TokenLiteral() string { return al.Token.Literal} func (al *ArrayLiteral) String() string{ var out bytes.Buffer elements := []string{} for _, el := range al.Elements{ elements = append(elements, el.String()) } out.WriteString("[") out.WriteString(strings.Join(elements, ",")) out.WriteString("]") return out.String() } type IndexExpression struct{ Token token.Token Left Expression Index Expression } func (ie *IndexExpression) expressionNode() {} func (ie *IndexExpression) TokenLiteral() string {return ie.Token.Literal} func (ie *IndexExpression) String() string{ var out bytes.Buffer out.WriteString("(") out.WriteString(ie.Left.String()) out.WriteString("[") out.WriteString(ie.Index.String()) out.WriteString("]") return out.String() } type HashLiteral struct{ Token token.Token Pairs map[Expression]Expression } func (hl *HashLiteral) expressionNode() {} func (hl *HashLiteral) TokenLiteral() string { return hl.Token.Literal } func (hl *HashLiteral) String() string{ var out bytes.Buffer pairs := []string{} for key, value := range hl.Pairs{ pairs = append(pairs, key.String() + ":" + value.String()) } out.WriteString("{") out.WriteString(strings.Join(pairs, ", ")) out.WriteString("}") return out.String() }
true
21ca4285d0548fd14e87cba5ade7ff7ce9e58637
Go
bketelsen/learnonline
/actions/course.go
UTF-8
2,395
2.578125
3
[]
no_license
[]
no_license
package actions import ( "errors" "fmt" "github.com/bketelsen/learnonline/models" "github.com/gobuffalo/buffalo" "github.com/markbates/pop" ) // CoursesIndex default implementation. func CoursesIndex(c buffalo.Context) error { // courses automatically loaded in the // middleware c.Set("title", "Available Classes") cl, err := models.GetCourseList() if err != nil { fmt.Println("Error getting models frm cms") } c.Set("courselist", cl) return c.Render(200, r.HTML(sitePath(c, "courses.html"))) } // CoursesShow default implementation. func CoursesShow(c buffalo.Context) error { tx := c.Value("tx").(*pop.Connection) course, err := models.GetFullCourseBySlug(c.Param("slug")) if err != nil { return err } fmt.Println("Got course") if c.Value("current_user") != nil { course.MarkAsPurchased(tx, c.Value("current_user").(*models.User)) } fmt.Println("Marked Purchased") c.Set("cour", course) c.Set("title", course.Course.Title) return c.Render(200, r.HTML(sitePath(c, "course.html"))) } // CoursesShow default implementation. func ClassroomShow(c buffalo.Context) error { tx := c.Value("tx").(*pop.Connection) course, err := models.GetFullCourseBySlug(c.Param("slug")) if err != nil { return err } if c.Value("current_user") != nil { course.MarkAsPurchased(tx, c.Value("current_user").(*models.User)) } c.Set("cour", course) c.Set("title", course.Course.Title) if !course.Course.Purchased { fmt.Println("redirecting because course isn't purchased") return c.Redirect(302, "/courses/"+c.Param("slug")) } c.Set("modules", course.Modules) return c.Render(200, r.HTML(sitePath(c, "classroom.html"))) } // CoursesShow default implementation. func ClassroomModuleShow(c buffalo.Context) error { tx := c.Value("tx").(*pop.Connection) course, err := models.GetFullCourseBySlug(c.Param("slug")) if err != nil { return err } if c.Value("current_user") != nil { course.MarkAsPurchased(tx, c.Value("current_user").(*models.User)) } c.Set("cour", course) if !course.Course.Purchased { return c.Redirect(302, "/courses/"+c.Param("slug")) } var found bool for _, m := range course.Modules { if m.ModuleSlug == c.Param("module") { c.Set("module", m) c.Set("title", m.Title) found = true } } if !found { return c.Error(400, errors.New("Module Not Found")) } return c.Render(200, r.HTML(sitePath(c, "module.html"))) }
true
58bc5082048a12de5b83a1721fba3b404aabd617
Go
ivanmeca/timedQueue
/config/sample_config.go
UTF-8
715
2.828125
3
[]
no_license
[]
no_license
package config import ( "encoding/json" "os" ) func configSample() *ConfigData { var config ConfigData config.DataBase.DbName = "time-queue" config.DataBase.ServerHost = "timeQueue.DB.ivanmeca.com.br" config.DataBase.ServerPort = "9003" config.DataBase.ServerUser = "" config.DataBase.ServerPassword = "" return &config } func generateConfigFile(filename string, data *ConfigData) error { file, err := os.Create(filename) if err != nil { return err } jsondata, err := json.Marshal(data) if err != nil { return err } _, err = file.Write(jsondata) if err != nil { return err } return nil } func ConfigSample() error { return generateConfigFile("./config-sample.json", configSample()) }
true
f783382acd4e017311437f4e118cd2abcf4b258f
Go
ksambaiah/Programming
/go/modules/http/httpExample1.go
UTF-8
347
3.109375
3
[]
no_license
[]
no_license
package main import ( "fmt" "net/http" ) const portNumber = ":8080" func HomePageHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("We're live !!!")) } func main() { http.HandleFunc("/", HomePageHandler) fmt.Printf("Starting application on port %v\n", portNumber) http.ListenAndServe(portNumber, nil) }
true
e669c35f9e72b70116da65258f79ec3190a63e20
Go
dingkegithub/golanguage
/funcinter/deferfunc/main.go
UTF-8
210
3.171875
3
[]
no_license
[]
no_license
package main import "fmt" func main() { for i := 0; i < 3; i++ { defer func() { fmt.Println("error: ", i) }() } for i := 0; i < 3; i++ { defer func(v int) { fmt.Println("ok: ", v) }(i) } }
true
97d496d79a7ef78bf8ac83a92e163fbbce543672
Go
arnodel/golua
/runtime/value_noscalar.go
UTF-8
5,704
3.03125
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
// +build noscalar // // This implementation of Value disables special casing of ints, floats and // bools. It causes more memory allocations. package runtime // A Value is a runtime value. type Value struct { iface interface{} } // AsValue returns a Value for the passed interface. func AsValue(i interface{}) Value { return Value{iface: i} } // Interface turns the Value into an interface. func (v Value) Interface() interface{} { return v.iface } // IntValue returns a Value holding the given arg. func IntValue(n int64) Value { return Value{iface: n} } // FloatValue returns a Value holding the given arg. func FloatValue(f float64) Value { return Value{iface: f} } // BoolValue returns a Value holding the given arg. func BoolValue(b bool) Value { return Value{iface: b} } // StringValue returns a Value holding the given arg. func StringValue(s string) Value { return Value{iface: s} } // TableValue returns a Value holding the given arg. func TableValue(t *Table) Value { return Value{iface: t} } // FunctionValue returns a Value holding the given arg. func FunctionValue(c Callable) Value { return Value{iface: c} } // ContValue returns a Value holding the given arg. func ContValue(c Cont) Value { return Value{iface: c} } // ArrayValue returns a Value holding the given arg. func ArrayValue(a []Value) Value { return Value{iface: a} } // CodeValue returns a Value holding the given arg. func CodeValue(c *Code) Value { return Value{iface: c} } // ThreadValue returns a Value holding the given arg. func ThreadValue(t *Thread) Value { return Value{iface: t} } // LightUserDataValue returns a Value holding the given arg. func LightUserDataValue(d LightUserData) Value { return Value{iface: d} } // UserDataValue returns a Value holding the given arg. func UserDataValue(u *UserData) Value { return Value{iface: u} } // NilValue is a value holding Nil. var NilValue = Value{} // Type returns the ValueType of v. func (v Value) Type() ValueType { if v.iface == nil { return NilType } switch v.iface.(type) { case int64: return IntType case float64: return FloatType case bool: return BoolType case string: return StringType case *Table: return TableType case *Code: return CodeType case Callable: return FunctionType case *Thread: return ThreadType case *UserData: return UserDataType default: return UnknownType } } // NumberType return the ValueType of v if it is a number, otherwise // UnknownType. func (v Value) NumberType() ValueType { switch v.iface.(type) { case int64: return IntType case float64: return FloatType } return UnknownType } // AsInt returns v as a int64 (or panics). func (v Value) AsInt() int64 { return v.iface.(int64) } // AsFloat returns v as a float64 (or panics). func (v Value) AsFloat() float64 { return v.iface.(float64) } // AsBool returns v as a bool (or panics). func (v Value) AsBool() bool { return v.iface.(bool) } // AsString returns v as a string (or panics). func (v Value) AsString() string { return v.iface.(string) } // AsTable returns v as a *Table (or panics). func (v Value) AsTable() *Table { return v.iface.(*Table) } // AsCont returns v as a Cont (or panics). func (v Value) AsCont() Cont { return v.iface.(Cont) } // AsArray returns v as a [] (or panics). func (v Value) AsArray() []Value { return v.iface.([]Value) } // AsClosure returns v as a *Closure (or panics). func (v Value) AsClosure() *Closure { return v.iface.(*Closure) } // AsCode returns v as a *Code (or panics). func (v Value) AsCode() *Code { return v.iface.(*Code) } // AsUserData returns v as a *UserData (or panics). func (v Value) AsUserData() *UserData { return v.iface.(*UserData) } // AsFunction returns v as a Callable (or panics). func (v Value) AsFunction() Callable { return v.iface.(Callable) } // TryInt converts v to type int64 if possible (ok is false otherwise). func (v Value) TryInt() (n int64, ok bool) { n, ok = v.iface.(int64) return } // TryFloat converts v to type float64 if possible (ok is false otherwise). func (v Value) TryFloat() (n float64, ok bool) { n, ok = v.iface.(float64) return } // TryString converts v to type string if possible (ok is false otherwise). func (v Value) TryString() (s string, ok bool) { s, ok = v.iface.(string) return } // TryCallable converts v to type Callable if possible (ok is false otherwise). func (v Value) TryCallable() (c Callable, ok bool) { c, ok = v.iface.(Callable) return } // TryClosure converts v to type *Closure if possible (ok is false otherwise). func (v Value) TryClosure() (c *Closure, ok bool) { c, ok = v.iface.(*Closure) return } // TryThread converts v to type *Thread if possible (ok is false otherwise). func (v Value) TryThread() (t *Thread, ok bool) { t, ok = v.iface.(*Thread) return } // TryTable converts v to type *Table if possible (ok is false otherwise). func (v Value) TryTable() (t *Table, ok bool) { t, ok = v.iface.(*Table) return } // TryUserData converts v to type *UserData if possible (ok is false otherwise). func (v Value) TryUserData() (u *UserData, ok bool) { u, ok = v.iface.(*UserData) return } // TryBool converts v to type bool if possible (ok is false otherwise). func (v Value) TryBool() (b bool, ok bool) { b, ok = v.iface.(bool) return } // TryCont converts v to type Cont if possible (ok is false otherwise). func (v Value) TryCont() (c Cont, ok bool) { c, ok = v.iface.(Cont) return } // TryCode converts v to type *Code if possible (ok is false otherwise). func (v Value) TryCode() (c *Code, ok bool) { c, ok = v.iface.(*Code) return } // IsNil returns true if v is nil. func (v Value) IsNil() bool { return v.iface == nil }
true
3ab88d1e44ead060c876318c92d607bf4a0a21e3
Go
Okumi/o-editor
/build_test.go
UTF-8
1,692
2.75
3
[ "BSD-3-Clause" ]
permissive
[ "BSD-3-Clause" ]
permissive
package main import ( "fmt" "os" "testing" ) func ExampleEditor_BuildOrExport_goError() { e := NewSimpleEditor(80) e.mode, _ = detectEditorMode("err.go") os.Chdir("test") // The rename is so that "err.go" is not picked up by the CI tests os.Rename("err_go", "err.go") s, performedAction, compiledOK := e.BuildOrExport(nil, nil, "err.go") os.Rename("err.go", "err_go") os.Chdir("..") fmt.Printf("%s [performed action: %v] [compiled OK: %v]\n", s, performedAction, compiledOK) // Output: // undefined: asdfasdf [performed action: true] [compiled OK: false] } func TestBuildOrExport(t *testing.T) { e := NewSimpleEditor(80) e.mode, _ = detectEditorMode("err.rs") os.Chdir("test") _, performedAction, compiledOK := e.BuildOrExport(nil, nil, "err.rs") os.Chdir("..") // fmt.Printf("%s [performed action: %v] [compiled OK: %v]\n", s, performedAction, compiledOK) if which("rustc") != "" { //fmt.Println(s) if !performedAction { t.Fail() } if compiledOK { t.Fail() } } else { //fmt.Println(s) // silent compiler if performedAction { t.Fail() } if compiledOK { t.Fail() } } } func ExampleEditor_BuildOrExport_goTest() { e := NewSimpleEditor(80) e.mode, _ = detectEditorMode("err.go") os.Chdir("test") // The rename is so that "err.go" is not picked up by the CI tests os.Rename("err_test_go", "err_test.go") s, performedAction, compiledOK := e.BuildOrExport(nil, nil, "err_test.go") os.Rename("err_test.go", "err_test_go") os.Chdir("..") fmt.Printf("%s [performed action: %v] [compiled OK: %v]\n", s, performedAction, compiledOK) // Output: // Test failed: TestTest (0.00s) [performed action: true] [compiled OK: false] }
true
6f3ca4cd94ec27ec56ef13932a17a5fb895230a9
Go
ferjmc/cms
/functions/user-put/main.go
UTF-8
1,691
2.78125
3
[]
no_license
[]
no_license
package main import ( "encoding/json" "github.com/aws/aws-lambda-go/events" "github.com/ferjmc/cms/entities" "github.com/ferjmc/cms/functions" "github.com/ferjmc/cms/pkg/auth" "github.com/ferjmc/cms/pkg/user" ) type Request struct { User UserRequest `json:"user"` } type UserRequest struct { Username string `json:"username"` Email string `json:"email"` Password string `json:"password"` Image string `json:"image"` Bio string `json:"bio"` } type Response struct { User UserResponse `json:"user"` } type UserResponse struct { Username string `json:"username"` Email string `json:"email"` Image string `json:"image"` Bio string `json:"bio"` Token string `json:"token"` } func Handle(input events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { var request Request err := json.Unmarshal([]byte(input.Body), &request) if err != nil { return functions.NewErrorResponse(err) } auth := auth.New() passwordHash, err := auth.Scrypt(request.User.Password) if err != nil { return functions.NewErrorResponse(err) } newUser := entities.User{ Username: request.User.Username, Email: request.User.Email, PasswordHash: passwordHash, Image: request.User.Image, Bio: request.User.Bio, } userService := user.New() user, token, err := userService.UpdateUser(input.Headers["Authorization"], newUser) if err != nil { return functions.NewErrorResponse(err) } response := Response{ User: UserResponse{ Username: user.Username, Email: user.Email, Image: user.Image, Bio: user.Bio, Token: token, }, } return functions.NewSuccessResponse(200, response) }
true
4e18559170f55839554bb0bedd7b5d81564817f2
Go
wkym461a/gphotos
/uploadingMedia.go
UTF-8
3,564
2.65625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package gphotos import ( "bytes" "io/ioutil" "net/http" "os" "strconv" ) // UploadingMedia is the only instance of UploadingMediaRequests(https://godoc.org/github.com/Q-Brains/gphotos#UploadMediaRequests). var UploadingMedia UploadingMediaRequests = uploadingMediaRequests{} // UploadingMediaRequests is a collection of request methods belonging to `UploadingMedia`. // The only instance of UploadMediaRequests is UploadMedia(https://godoc.org/github.com/Q-Brains/gphotos#UploadMedia). // Source: https://developers.google.com/photos/library/guides/overview type UploadingMediaRequests interface { baseURL() string // UploadMedia is a method that uploads media items to a user’s library or album. // Source: https://developers.google.com/photos/library/guides/upload-media UploadMedia(client *http.Client, filePath string, filename string) (uploadToken string, err error) // ResumableUploads is a method. // Source: https://developers.google.com/photos/library/guides/resumable-uploads ResumableUploads(client *http.Client, filePath string, filename string) (uploadToken string, err error) } type uploadingMediaRequests struct{} func (upload uploadingMediaRequests) baseURL() string { return "https://photoslibrary.googleapis.com/v1/uploads" } func (upload uploadingMediaRequests) UploadMedia(client *http.Client, filePath string, filename string) (uploadToken string, err error) { file, err := os.Open(filePath) if err != nil { return "", err } req, err := http.NewRequest("POST", upload.baseURL(), file) if err != nil { return "", err } req.Header.Set("Content-Type", "application/octet-stream") req.Header.Set("X-Goog-Upload-File-Name", filename) req.Header.Set("X-Goog-Upload-Protocol", "raw") resp, err := client.Do(req) if err != nil { return "", err } defer resp.Body.Close() b, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } return bytes.NewBuffer(b).String(), nil } func (upload uploadingMediaRequests) ResumableUploads(client *http.Client, filePath string, filename string) (uploadToken string, err error) { file, err := os.Open(filePath) if err != nil { return "", err } req, err := http.NewRequest("POST", upload.baseURL(), nil) if err != nil { return "", err } contentType, err := detectContentType(file) if err != nil { return "", err } length, err := byteLength(file) if err != nil { return "", err } req.Header.Set("Content-Length", strconv.Itoa(0)) req.Header.Set("X-Goog-Upload-Command", "start") req.Header.Set("X-Goog-Upload-Content-Type", contentType) req.Header.Set("X-Goog-Upload-File-Name", filename) req.Header.Set("X-Goog-Upload-Protocol", "resumable") req.Header.Set("X-Goog-Upload-Raw-Size", strconv.FormatInt(length, 10)) resp, err := client.Do(req) if err != nil { return "", err } defer resp.Body.Close() uploadURL := resp.Header.Get("X-Goog-Upload-URL") req, err = http.NewRequest("POST", uploadURL, file) req.Header.Set("Content-Length", strconv.FormatInt(length, 10)) req.Header.Set("X-Goog-Upload-Command", "upload, finalize") req.Header.Set("X-Goog-Upload-Offset", strconv.Itoa(0)) resp, err = client.Do(req) if err != nil { return "", err } defer resp.Body.Close() return "", nil } func detectContentType(file *os.File) (string, error) { buffer := make([]byte, 512) _, err := file.Read(buffer) if err != nil { return "", err } return http.DetectContentType(buffer), nil } func byteLength(file *os.File) (int64, error) { fi, err := file.Stat() if err != nil { return 0, err } return fi.Size(), nil }
true
21ba3c32f39089a184d7ef4c8cd0da9a9c08a190
Go
agungsetiawan/bwastartup
/user/repository.go
UTF-8
1,182
3.421875
3
[]
no_license
[]
no_license
package user import "gorm.io/gorm" type Repository interface { Save(user User) (User, error) FindByEmail(email string) (User, error) FindByID(ID int) (User, error) Update(user User) (User, error) FindAll() ([]User, error) } type repository struct { db *gorm.DB } func NewRepository(db *gorm.DB) *repository { return &repository{db} } func (r *repository) Save(user User) (User, error) { err := r.db.Create(&user).Error if err != nil { return user, err } return user, nil } func (r *repository) FindByEmail(email string) (User, error) { var user User err := r.db.Where("email = ?", email).Find(&user).Error if err != nil { return user, err } return user, nil } func (r *repository) FindByID(ID int) (User, error) { var user User err := r.db.Where("id = ?", ID).Find(&user).Error if err != nil { return user, err } return user, nil } func (r *repository) Update(user User) (User, error) { err := r.db.Save(&user).Error if err != nil { return user, err } return user, nil } func (r *repository) FindAll() ([]User, error) { var users []User err := r.db.Find(&users).Error if err != nil { return users, err } return users, nil }
true
f1242edaf630e18b618bcfc6499db5b190c4e240
Go
stream2000/gom4db
/network/reactor/gnet.go
UTF-8
2,328
2.65625
3
[]
no_license
[]
no_license
package reactor import ( "container/heap" "fmt" "github.com/golang/protobuf/proto" "github.com/panjf2000/gnet" "github.com/panjf2000/gnet/pool/goroutine" "gom4db/cache" "gom4db/pbmessages" "log" ) type cacheServer struct { *gnet.EventServer addr string multiCore bool async bool codec gnet.ICodec workerPool *goroutine.Pool cache cache.KeyValueCache } type cacheContext struct { order int responses chan response } func (cs *cacheServer) OnInitComplete(srv gnet.Server) (action gnet.Action) { log.Printf("Test codec server is listening on %s (multi-cores: %t, loops: %d)\n", srv.Addr.String(), srv.Multicore, srv.NumLoops) return } func (cs *cacheServer) OnOpened(c gnet.Conn) (out []byte, action gnet.Action) { newContext := cacheContext{ order: 0, responses: make(chan response, 100), } c.SetContext(&newContext) err := cs.workerPool.Submit(func() { var responseHeap = new(ResponseHeap) heap.Init(responseHeap) ctx := c.Context().(*cacheContext) currentOrder := 0 for newResponse := range ctx.responses{ if newResponse.order == currentOrder { c.AsyncWrite(newResponse.body) currentOrder++ } else { heap.Push(responseHeap, newResponse) continue } for { if responseHeap.IsEmpty() { break } if responseHeap.Top() == currentOrder { popResp := heap.Pop(responseHeap).(response) c.AsyncWrite(popResp.body) currentOrder++ } else { break } } } }) if err != nil { panic(err) } return } func (cs *cacheServer)OnClosed(c gnet.Conn,err error)(action gnet.Action){ ctx := c.Context().(*cacheContext) close(ctx.responses) return } func (cs *cacheServer) React(c gnet.Conn) (out []byte, action gnet.Action) { ctx := c.Context().(*cacheContext) for { data := c.ReadFrame() if len(data) == 0 { return } order := ctx.order ctx.order++ err := cs.workerPool.Submit(func() { frameData := append([]byte{}, data...) request := &pbmessages.Request{} err := proto.Unmarshal(frameData, request) sniffError(err) responseBuffer := cs.processRequest(request) ctx.responses <- response{ body: responseBuffer, order: order, } }) if err != nil { panic(err) } } return } func sniffError(err error) { if err != nil { fmt.Println(err) } }
true
8e001113cc0ae2610492e1c73f7cad71a2e7e664
Go
nurali-techie/play-go
/gob-encoding/recv/recv.go
UTF-8
739
3.296875
3
[]
no_license
[]
no_license
package main import ( "encoding/gob" "log" "net" ) type Emp struct { Name string Age *int } func main() { log.SetFlags(log.Lmicroseconds) log.Printf("starting ..\n") addr, err := net.ResolveTCPAddr("tcp4", ":8050") if err != nil { log.Fatalf("Resolve failed, %v", err) } lisntener, err := net.ListenTCP("tcp", addr) if err != nil { log.Fatalf("Listen failed, %v", err) } log.Printf("listening ..\n") conn, err := lisntener.Accept() if err != nil { log.Fatalf("Conn failed, %v", err) } dec := gob.NewDecoder(conn) var e1 Emp log.Printf("receving ..\n") err = dec.Decode(&e1) if err != nil { log.Fatalf("decode failed, %v", err) } log.Printf("Got data, Emp:%v, name:%s, age:%d", e1, e1.Name, *e1.Age) }
true
b6b3df472da74bec56da5d7c5100a9acc21ee562
Go
EqCScO9nTa/v2ray-core
/common/buf/multi_buffer_test.go
UTF-8
3,785
2.734375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package buf_test import ( "bytes" "crypto/rand" "io" "testing" "github.com/google/go-cmp/cmp" "io/ioutil" "os" "v2ray.com/core/common" . "v2ray.com/core/common/buf" ) func TestMultiBufferRead(t *testing.T) { b1 := New() common.Must2(b1.WriteString("ab")) b2 := New() common.Must2(b2.WriteString("cd")) mb := MultiBuffer{b1, b2} bs := make([]byte, 32) _, nBytes := SplitBytes(mb, bs) if nBytes != 4 { t.Error("expect 4 bytes split, but got ", nBytes) } if r := cmp.Diff(bs[:nBytes], []byte("abcd")); r != "" { t.Error(r) } } func TestMultiBufferAppend(t *testing.T) { var mb MultiBuffer b := New() common.Must2(b.WriteString("ab")) mb = append(mb, b) if mb.Len() != 2 { t.Error("expected length 2, but got ", mb.Len()) } } func TestMultiBufferSliceBySizeLarge(t *testing.T) { lb := make([]byte, 8*1024) common.Must2(io.ReadFull(rand.Reader, lb)) mb := MergeBytes(nil, lb) mb, mb2 := SplitSize(mb, 1024) if mb2.Len() != 1024 { t.Error("expect length 1024, but got ", mb2.Len()) } if mb.Len() != 7*1024 { t.Error("expect length 7*1024, but got ", mb.Len()) } mb, mb3 := SplitSize(mb, 7*1024) if mb3.Len() != 7*1024 { t.Error("expect length 7*1024, but got", mb.Len()) } if !mb.IsEmpty() { t.Error("expect empty buffer, but got ", mb.Len()) } } func TestMultiBufferSplitFirst(t *testing.T) { b1 := New() b1.WriteString("b1") b2 := New() b2.WriteString("b2") b3 := New() b3.WriteString("b3") var mb MultiBuffer mb = append(mb, b1, b2, b3) mb, c1 := SplitFirst(mb) if diff := cmp.Diff(b1.String(), c1.String()); diff != "" { t.Error(diff) } mb, c2 := SplitFirst(mb) if diff := cmp.Diff(b2.String(), c2.String()); diff != "" { t.Error(diff) } mb, c3 := SplitFirst(mb) if diff := cmp.Diff(b3.String(), c3.String()); diff != "" { t.Error(diff) } if !mb.IsEmpty() { t.Error("expect empty buffer, but got ", mb.String()) } } func TestMultiBufferReadAllToByte(t *testing.T) { { lb := make([]byte, 8*1024) common.Must2(io.ReadFull(rand.Reader, lb)) rd := bytes.NewBuffer(lb) b, err := ReadAllToBytes(rd) common.Must(err) if l := len(b); l != 8*1024 { t.Error("unexpceted length from ReadAllToBytes", l) } } { const dat = "data/test_MultiBufferReadAllToByte.dat" f, err := os.Open(dat) common.Must(err) buf2, err := ReadAllToBytes(f) common.Must(err) f.Close() cnt, err := ioutil.ReadFile(dat) common.Must(err) if d := cmp.Diff(buf2, cnt); d != "" { t.Error("fail to read from file: ", d) } } } func TestMultiBufferCopy(t *testing.T) { lb := make([]byte, 8*1024) common.Must2(io.ReadFull(rand.Reader, lb)) reader := bytes.NewBuffer(lb) mb, err := ReadFrom(reader) common.Must(err) lbdst := make([]byte, 8*1024) mb.Copy(lbdst) if d := cmp.Diff(lb, lbdst); d != "" { t.Error("unexpceted different from MultiBufferCopy ", d) } } func TestSplitFirstBytes(t *testing.T) { a := New() common.Must2(a.WriteString("ab")) b := New() common.Must2(b.WriteString("bc")) mb := MultiBuffer{a, b} o := make([]byte, 2) _, cnt := SplitFirstBytes(mb, o) if cnt != 2 { t.Error("unexpected cnt from SplitFirstBytes ", cnt) } if d := cmp.Diff(string(o), "ab"); d != "" { t.Error("unexpected splited result from SplitFirstBytes ", d) } } func TestCompact(t *testing.T) { a := New() common.Must2(a.WriteString("ab")) b := New() common.Must2(b.WriteString("bc")) mb := MultiBuffer{a, b} cmb := Compact(mb) if w := cmb.String(); w != "abbc" { t.Error("unexpected Compact result ", w) } } func BenchmarkSplitBytes(b *testing.B) { var mb MultiBuffer raw := make([]byte, Size) b.ResetTimer() for i := 0; i < b.N; i++ { buffer := StackNew() buffer.Extend(Size) mb = append(mb, &buffer) mb, _ = SplitBytes(mb, raw) } }
true
5e3a8eed11f778bf59c235904f78e21526e76a70
Go
sguzwf/wsh2s
/flush_writer.go
UTF-8
372
2.796875
3
[]
no_license
[]
no_license
package wsh2s import "net/http" type flushWriter struct { http.ResponseWriter } func (w *flushWriter) FlushHeader(code int) { w.ResponseWriter.WriteHeader(code) w.ResponseWriter.(http.Flusher).Flush() } func (w *flushWriter) Write(p []byte) (n int, err error) { n, err = w.ResponseWriter.Write(p) if n > 0 { w.ResponseWriter.(http.Flusher).Flush() } return }
true
fe490da86d4b55c3c10427c57ecd0ac7f0e4fde7
Go
qewetfty/leetcodeProblem
/treeNode/problem938.go
UTF-8
603
3.1875
3
[]
no_license
[]
no_license
package treeNode import "github.com/leetcodeProblem/data" //Given the root node of a binary search tree, // return the sum of values of all nodes with value between L and R (inclusive). // //The binary search tree is guaranteed to have unique values. //Note: //The number of nodes in the tree is at most 10000. //The final answer is guaranteed to be less than 2^31. func rangeSumBST(root *data.TreeNode, L int, R int) int { if root == nil { return 0 } res := make([]int, 0) searchTreeNode(root, &res) sum := 0 for _, i := range res { if L <= i && i <= R { sum += i } } return sum }
true
08259708e32a91953c284ec426f368ee855a86cc
Go
simukti/sqldb-logger
/rows.go
UTF-8
3,557
2.765625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package sqldblogger import ( "context" "database/sql/driver" "io" "reflect" "time" ) // rows is a wrapper which implements: // - driver.Rows // - driver.RowsNextResultSet // - driver.RowsColumnTypeScanType // - driver.RowsColumnTypeDatabaseTypeName // - driver.RowsColumnTypeLength // - driver.RowsColumnTypeNullable // - driver.RowsColumnTypePrecisionScale type rows struct { driver.Rows logger *logger connID string stmtID string query string args []driver.Value } // Columns implement driver.Rows func (r *rows) Columns() []string { return r.Rows.Columns() } // Close implement driver.Rows func (r *rows) Close() error { lvl, start := LevelTrace, time.Now() err := r.Rows.Close() if err != nil { lvl = LevelError } r.logger.log(context.Background(), lvl, "RowsClose", start, err, r.logData()...) return err } // Next implement driver.Rows func (r *rows) Next(dest []driver.Value) error { logs := r.logData() // dest contain value from database. // If query arg not logged, dest arg here will also not logged. if r.logger.opt.logArgs { logs = append(logs, r.logger.withKeyArgs("rows_dest", dest)) } lvl, start := LevelTrace, time.Now() err := r.Rows.Next(dest) if err != nil && err != io.EOF { lvl = LevelError } r.logger.log(context.Background(), lvl, "RowsNext", start, err, logs...) return err } // HasNextResultSet implement driver.RowsNextResultSet func (r *rows) HasNextResultSet() bool { if rs, ok := r.Rows.(driver.RowsNextResultSet); ok { return rs.HasNextResultSet() } return false } // NextResultSet implement driver.RowsNextResultSet func (r *rows) NextResultSet() error { rs, ok := r.Rows.(driver.RowsNextResultSet) if !ok { return io.EOF } lvl, start := LevelTrace, time.Now() err := rs.NextResultSet() if err != nil && err != io.EOF { lvl = LevelError } r.logger.log(context.Background(), lvl, "RowsNextResultSet", start, err, r.logData()...) return err } // ColumnTypeScanType implement driver.RowsColumnTypeScanType func (r *rows) ColumnTypeScanType(index int) reflect.Type { if rs, ok := r.Rows.(driver.RowsColumnTypeScanType); ok { return rs.ColumnTypeScanType(index) } return reflect.SliceOf(reflect.TypeOf("")) } // ColumnTypeDatabaseTypeName driver.RowsColumnTypeDatabaseTypeName func (r *rows) ColumnTypeDatabaseTypeName(index int) string { if rs, ok := r.Rows.(driver.RowsColumnTypeDatabaseTypeName); ok { return rs.ColumnTypeDatabaseTypeName(index) } return "" } // ColumnTypeLength implement driver.RowsColumnTypeLength func (r *rows) ColumnTypeLength(index int) (length int64, ok bool) { if rs, ok := r.Rows.(driver.RowsColumnTypeLength); ok { return rs.ColumnTypeLength(index) } return 0, false } // ColumnTypeNullable implement driver.RowsColumnTypeNullable func (r *rows) ColumnTypeNullable(index int) (nullable, ok bool) { if rs, ok := r.Rows.(driver.RowsColumnTypeNullable); ok { return rs.ColumnTypeNullable(index) } return false, false } // ColumnTypePrecisionScale implement driver.RowsColumnTypePrecisionScale func (r *rows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool) { if rs, ok := r.Rows.(driver.RowsColumnTypePrecisionScale); ok { return rs.ColumnTypePrecisionScale(index) } return 0, 0, false } // logData default log data for rows. func (r *rows) logData() []dataFunc { return []dataFunc{ r.logger.withUID(r.logger.opt.connIDFieldname, r.connID), r.logger.withUID(r.logger.opt.stmtIDFieldname, r.stmtID), r.logger.withQuery(r.query), r.logger.withArgs(r.args), } }
true
afae8ae506b269235a90b370c97d8214fac39a39
Go
softonic/homing-pigeon
/pkg/messages/message.go
UTF-8
543
3.171875
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package messages import "errors" type Message struct { Id interface{} Body []byte acked bool } func (m Message) Nack() (Ack, error) { err := m.setAsAcked() if err != nil { return Ack{}, err } return Ack{ Id: m.Id, Ack: false, }, nil } func (m Message) Ack() (Ack, error) { err := m.setAsAcked() if err != nil { return Ack{}, err } return Ack{ Id: m.Id, Ack: true, }, nil } func (m Message) setAsAcked() error { if m.acked { return errors.New("Message already acked") } m.acked = true return nil }
true
af65c374621d7fdc3cd29b5096781301f3d8cc54
Go
YoungFox/Lets-go
/src/build-web-application-with-golang/struct/main.go
UTF-8
7,244
4.15625
4
[]
no_license
[]
no_license
// package main // import "fmt" // type person struct { // name string // age int // } // func main() { // var P person // P现在就是person类型的变量了 // P.name = "Astaxie" // 赋值"Astaxie"给P的name属性. // P.age = 25 // 赋值"25"给变量P的age属性 // fmt.Printf("The person's name is %s", P.name) // 访问P的name属性. // } // package main // import "fmt" // // 声明一个新的类型 // type person struct { // name string // age int // } // // 比较两个人的年龄,返回年龄大的那个人,并且返回年龄差 // // struct也是传值的 // func Older(p1, p2 person) (person, int) { // if p1.age > p2.age { // 比较p1和p2这两个人的年龄 // return p1, p1.age - p2.age // } // return p2, p2.age - p1.age // } // func main() { // var tom person // // 赋值初始化 // tom.name, tom.age = "Tom", 18 // // 两个字段都写清楚的初始化 // bob := person{age: 25, name: "Bob"} // // 按照struct定义顺序初始化值 // paul := person{"Paul", 43} // tb_Older, tb_diff := Older(tom, bob) // tp_Older, tp_diff := Older(tom, paul) // bp_Older, bp_diff := Older(bob, paul) // fmt.Printf("Of %s and %s, %s is older by %d years\n", // tom.name, bob.name, tb_Older.name, tb_diff) // fmt.Printf("Of %s and %s, %s is older by %d years\n", // tom.name, paul.name, tp_Older.name, tp_diff) // fmt.Printf("Of %s and %s, %s is older by %d years\n", // bob.name, paul.name, bp_Older.name, bp_diff) // } // package main // import "fmt" // type Human struct { // name string // age int // weight int // } // type Student struct { // Human // 匿名字段,那么默认Student就包含了Human的所有字段 // speciality string // } // func main() { // // 我们初始化一个学生 // mark := Student{Human{"Mark", 25, 120}, "Computer Science"} // // 我们访问相应的字段 // fmt.Println("His name is ", mark.name) // fmt.Println("His age is ", mark.age) // fmt.Println("His weight is ", mark.weight) // fmt.Println("His speciality is ", mark.speciality) // // 修改对应的备注信息 // mark.speciality = "AI" // fmt.Println("Mark changed his speciality") // fmt.Println("His speciality is ", mark.speciality) // // 修改他的年龄信息 // fmt.Println("Mark become old") // mark.age = 46 // fmt.Println("His age is", mark.age) // // 修改他的体重信息 // fmt.Println("Mark is not an athlet anymore") // mark.weight += 60 // fmt.Println("His weight is", mark.weight) // } // package main // import "fmt" // type Skills []string // type Human struct { // name string // age int // weight int // } // type Student struct { // Human // 匿名字段,struct // Skills // 匿名字段,自定义的类型string slice // int // 内置类型作为匿名字段 // speciality string // } // func main() { // // 初始化学生Jane // jane := Student{Human: Human{"Jane", 35, 100}, speciality: "Biology"} // // 现在我们来访问相应的字段 // fmt.Println("Her name is ", jane.name) // fmt.Println("Her age is ", jane.age) // fmt.Println("Her weight is ", jane.weight) // fmt.Println("Her speciality is ", jane.speciality) // // 我们来修改他的skill技能字段 // jane.Skills = []string{"anatomy"} // fmt.Println("Her skills are ", jane.Skills) // fmt.Println("She acquired two new ones ") // jane.Skills = append(jane.Skills, "physics", "golang") // fmt.Println("Her skills now are ", jane.Skills) // // 修改匿名内置类型字段 // jane.int = 3 // fmt.Println("Her preferred number is", jane.int) // } // package main // import "fmt" // type Skills []string // type Human struct { // name string // age int // weight int // } // type Student struct { // Human // 匿名字段,struct // Skills // 匿名字段,自定义的类型string slice // int // 内置类型作为匿名字段 // speciality string // } // func main() { // // 初始化学生Jane // jane := Student{Human: Human{"Jane", 35, 100}, speciality: "Biology"} // // 现在我们来访问相应的字段 // fmt.Println("Her name is ", jane.name) // fmt.Println("Her age is ", jane.age) // fmt.Println("Her weight is ", jane.weight) // fmt.Println("Her speciality is ", jane.speciality) // // 我们来修改他的skill技能字段 // jane.Skills = []string{"anatomy"} // fmt.Println("Her skills are ", jane.Skills) // fmt.Println("She acquired two new ones ") // jane.Skills = append(jane.Skills, "physics", "golang") // fmt.Println("Her skills now are ", jane.Skills) // // 修改匿名内置类型字段 // jane.int = 3 // fmt.Println("Her preferred number is", jane.int) // } // package main // import "fmt" // type Human struct { // name string // age int // phone string // Human类型拥有的字段 // } // type Employee struct { // Human // 匿名字段Human // speciality string // phone string // 雇员的phone字段 // } // func main() { // Bob := Employee{Human{"Bob", 34, "777-444-XXXX"}, "Designer", "333-222"} // fmt.Println("Bob's work phone is:", Bob.phone) // // 如果我们要访问Human的phone字段 // fmt.Println("Bob's personal phone is:", Bob.Human.phone) // fmt.Println(Bob.age) // fmt.Println(Bob.Human.age) // fmt.Println(Bob.age == Bob.Human.age) // } // package main // import "fmt" // const ( // WHITE = iota // BLACK // BLUE // RED // YELLOW // ) // type Color byte // type Box struct { // width, height, depth float64 // color Color // } // type BoxList []Box //a slice of boxes // func (b Box) Volume() float64 { // return b.width * b.height * b.depth // } // func (b *Box) SetColor(c Color) { // b.color = c // } // func (bl BoxList) BiggestColor() Color { // v := 0.00 // k := Color(WHITE) // for _, b := range bl { // if bv := b.Volume(); bv > v { // v = bv // k = b.color // } // } // return k // } // func (bl BoxList) PaintItBlack() { // for i := range bl { // bl[i].SetColor(BLACK) // } // } // func (c Color) String() string { // strings := []string{"WHITE", "BLACK", "BLUE", "RED", "YELLOW"} // return strings[c] // } // func main() { // fmt.Println(YELLOW) // boxes := BoxList{ // Box{4, 4, 4, RED}, // Box{10, 10, 1, YELLOW}, // Box{1, 1, 20, BLACK}, // Box{10, 10, 1, BLUE}, // Box{10, 30, 1, WHITE}, // Box{20, 20, 20, YELLOW}, // } // fmt.Printf("We have %d boxes in our set\n", len(boxes)) // fmt.Println("The volume of the first one is", boxes[0].Volume(), "cm³") // fmt.Println("The color of the last one is", boxes[len(boxes)-1].color.String()) // fmt.Println("The biggest one is", boxes.BiggestColor().String()) // fmt.Println("Let's paint them all black") // boxes.PaintItBlack() // fmt.Println("The color of the second one is", boxes[1].color.String()) // fmt.Println("Obviously, now, the biggest one is", boxes.BiggestColor().String()) // } package main import ( "fmt" "reflect" ) func main() { var x float64 = 3.4 v := reflect.ValueOf(x) fmt.Println("type:", v.Type()) fmt.Println("kind is float64:", v.Kind() == reflect.Float64) fmt.Println("value:", v.Float()) }
true
c54bb83522a5472ab96c0ad902ce50acb86f75ae
Go
sanae10001/graphql-go-extension-scalars
/datetime.go
UTF-8
1,637
3.421875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package scalars import ( "errors" "time" ) var ( DateTimeWrongInputFormat = errors.New("Scalar.DateTime: wrong input format, expected RFC3339") DateTimeWrongInputType = errors.New("Scalar.DateTime: wrong input type") ) func NewDateTime(t time.Time) *DateTime { if t.IsZero() { return nil } d := DateTime{Time: t} return &d } // An ISO-8601 encoded UTC date string. // Format: RFC3339, Location: UTC, No nanosecond // see also: https://en.wikipedia.org/wiki/ISO_8601 type DateTime struct { time.Time } func (DateTime) ImplementsGraphQLType(name string) bool { return name == "DateTime" } func (dt *DateTime) UnmarshalGraphQL(input interface{}) error { switch input := input.(type) { case string: t, err := time.Parse(time.RFC3339, input) if err != nil { return DateTimeWrongInputFormat } dt.Time = convertToNoNanoUTC(t) return nil default: return DateTimeWrongInputType } } func (dt DateTime) MarshalJSON() ([]byte, error) { if dt.Location() != time.UTC { dt.Time = dt.UTC() } if y := dt.Year(); y < 0 || y >= 10000 { // RFC 3339 is clear that years are 4 digits exactly. // See golang.org/issue/4556#c15 for more discussion. return nil, errors.New("DateTime.MarshalJSON: year outside of range [0,9999]") } b := make([]byte, 0, len(time.RFC3339)+2) b = append(b, '"') b = dt.AppendFormat(b, time.RFC3339) b = append(b, '"') return b, nil } func convertToNoNanoUTC(t time.Time) time.Time { ut := t.UTC() if ut.Nanosecond() == 0 { return ut } else { return time.Date( ut.Year(), ut.Month(), ut.Day(), ut.Hour(), ut.Minute(), ut.Second(), 0, ut.Location(), ) } }
true
188a98ed6ae7148711e4c25ea43e272513f701a6
Go
fibbery/leetcode
/783.二叉搜索树节点最小距离.go
UTF-8
634
2.96875
3
[]
no_license
[]
no_license
/* * @lc app=leetcode.cn id=783 lang=golang * * [783] 二叉搜索树节点最小距离 */ package main import "math" // @lc code=start /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func minDiffInBST(root *TreeNode) int { result, pre := math.MaxInt64, -1 var inorder func(*TreeNode) inorder = func(node *TreeNode) { if node == nil { return } inorder(node.Left) if pre != -1 && node.Val-pre < result { result = node.Val - pre } pre = node.Val inorder(node.Right) } inorder(root) return result } // @lc code=end
true
e870127f1b31aa721d5dd3421056cbcc1e4c95e1
Go
fossabot/api-14
/pkg/github/roundtrip.go
UTF-8
981
2.90625
3
[]
no_license
[]
no_license
package github import ( "net/http" "net/textproto" funk "github.com/thoas/go-funk" ) func newAcceptFilteringTripper( underlying http.RoundTripper, valuesToFilter ...string, ) http.RoundTripper { if underlying == nil { underlying = http.DefaultTransport } return acceptFilteringTripper{ Tripper: underlying, Values: valuesToFilter, } } type acceptFilteringTripper struct { Tripper http.RoundTripper Values []string // headers to strip } var _ http.RoundTripper = (*acceptFilteringTripper)(nil) var acceptMIMEHeaderKey = textproto.CanonicalMIMEHeaderKey("Accept") func (aft acceptFilteringTripper) RoundTrip(r *http.Request) (*http.Response, error) { accept := r.Header[acceptMIMEHeaderKey] if len(accept) > 0 { filtered := make([]string, 0, len(accept)) for _, v := range accept { if !funk.ContainsString(aft.Values, v) { filtered = append(filtered, v) } } r.Header[acceptMIMEHeaderKey] = filtered } return aft.Tripper.RoundTrip(r) }
true
4cf25c206bcbe92bd3ce842349e21b168ce35113
Go
relax-space/ping-kafka-mysql
/main.go
UTF-8
1,377
2.609375
3
[]
no_license
[]
no_license
package main import ( "fmt" "os" "os/signal" "syscall" "time" _ "github.com/go-sql-driver/mysql" "github.com/go-xorm/xorm" ) func main() { if err := pingKafka(); err != nil { fmt.Println(err) return } fmt.Println("consumer is ready!") if err := pingMysql(); err != nil { fmt.Println(err) return } fmt.Println("ping mysql is ok") time.Sleep(100 * time.Hour) } func pingMysql() error { connect := fmt.Sprintf("%v:%v@tcp(%v:%v)/mysql?charset=utf8", os.Getenv("MYSQL_USER_NAME"), os.Getenv("MYSQL_PASSWORD"), os.Getenv("MYSQL_HOST"), os.Getenv("MYSQL_PORT")) fmt.Println(connect) _, err := xorm.NewEngine("mysql", connect) if err != nil { return err } return nil } func pingKafka() error { notifyKill() fmt.Printf(">> env addr:%v,port:%v,topic:%v \n", os.Getenv("KAFKA_HOST"), os.Getenv("KAFKA_PORT"), os.Getenv("KAFKA_TOPIC")) config := Config{ Brokers: []string{os.Getenv("KAFKA_HOST") + ":" + os.Getenv("KAFKA_PORT")}, Topic: os.Getenv("KAFKA_TOPIC"), } if err := Consume("consumer-kafka", config, EventFruit, ); err != nil { return err } return nil } func notifyKill() { signals := make(chan os.Signal, 1) signal.Notify(signals, os.Kill, os.Interrupt) go func() { for s := range signals { switch s { case syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT: os.Exit(0) } } }() }
true
162bbfc9f9a8cc18a0f72400733d4852262d738e
Go
trumae/evolvegamelib
/evolvegamelib_test.go
UTF-8
555
2.625
3
[]
no_license
[]
no_license
package evolvegamelib import "testing" func TestAngle(t *testing.T) { n := angle([8]int{2, 2, 2, 2, 2, 2, 2, 2}, 1) if n != 0 { t.Error("Erro na funcao angle") } n = angle([8]int{2, 2, 2, 2, 2, 2, 2, 2}, 3) if n != 1 { t.Error("Erro na funcao angle") } n = angle([8]int{2, 2, 2, 2, 2, 2, 2, 2}, 5) if n != 2 { t.Error("Erro na funcao angle") } n = angle([8]int{2, 2, 2, 2, 2, 2, 2, 2}, 7) if n != 3 { t.Error("Erro na funcao angle") } n = angle([8]int{2, 2, 2, 2, 2, 2, 2, 2}, 9) if n != 4 { t.Error("Erro na funcao angle") } }
true
f79eef2940b13dfd434e5ab86b0189c79b4d778d
Go
TedForV/goutil
/algorithm/heapsort.go
UTF-8
2,211
3.265625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package algorithm // UpAdjust upajust the last node (inserted new node situation) func UpAdjust(arr []int) { if len(arr) == 0 || len(arr) == 1 { return } childIndex := len(arr) - 1 parentIndx := getParentIndex(childIndex) for { if childIndex == 0 && arr[childIndex] >= arr[parentIndx] { break } arr[childIndex], arr[parentIndx] = arr[parentIndx], arr[childIndex] childIndex = parentIndx parentIndx = getParentIndex(childIndex) } } // DownAdjust downadjust the node (replace the root node with last node) // func DownAdjust(arr []int, parentIndex int) { // length := len(arr) // if length <= parentIndex+1 { // return // } // childIndex := parentIndex*2 + 1 // if length < childIndex+1 { // return // } // for { // if length < childIndex+1 { // break // } // if childIndex+2 <= length && arr[childIndex] > arr[childIndex+1] { // childIndex++ // } // if arr[parentIndex] <= arr[childIndex] { // break // } // arr[childIndex], arr[parentIndex] = arr[parentIndex], arr[childIndex] // parentIndex = childIndex // childIndex = parentIndex*2 + 1 // } // } // DownAdjust downadjust the node (replace the root node with last node) func DownAdjust(arr []int, parentIndex int, validLength int) { if validLength <= parentIndex+1 { return } childIndex := parentIndex*2 + 1 if validLength < childIndex+1 { return } for { if validLength < childIndex+1 { break } if childIndex+2 <= validLength && arr[childIndex] > arr[childIndex+1] { childIndex++ } if arr[parentIndex] <= arr[childIndex] { break } arr[childIndex], arr[parentIndex] = arr[parentIndex], arr[childIndex] parentIndex = childIndex childIndex = parentIndex*2 + 1 } } // BuildHeap build a heap for array func BuildHeap(arr []int) { if len(arr) == 0 { return } for i := len(arr) / 2; i >= 0; i-- { DownAdjust(arr, i, len(arr)) } } // HeapSort is heap sort func HeapSort(arr []int) { BuildHeap(arr) for i := len(arr) - 1; i > 0; i-- { arr[i], arr[0] = arr[0], arr[i] DownAdjust(arr, 0, i) } } func getParentIndex(childIndex int) int { if childIndex == 0 { return 0 } if childIndex%2 == 0 { return childIndex/2 - 1 } return childIndex / 2 }
true
5c18df4bcc37d451846cd73c6e86b13bbd38cda0
Go
Hussainzz/mySpaceB
/models/models.go
UTF-8
2,840
2.75
3
[]
no_license
[]
no_license
package models import ( "errors" "github.com/astaxie/beego" "github.com/astaxie/beego/orm" "fmt" "time" "github.com/gogather/com" ) type Users struct{ Id string `orm:"pk" json:"id"` Username string `json:"username"` Password string `json:"pwd"` Salt string `json:"salt"` Email string `orm:"unique" json:"email"` } func (this *Users) TableName() string{ return "users" } type Post struct{ Id int `orm:"pk;auto" json:"pid"` Users *Users `orm:"rel(fk)" json:"users"` Author string `json:"author"` Title string `form:"title,text,Title:" valid:"MinSize(5); MaxSize(20)" json:"title"` Description string `orm:"size(12000)" json:"desc" ` Date time.Time `orm:"auto_now_add;type(datetime)" json:"date"` Ispresent bool `json:"isprsnt"` } func (post *Post) Display(){ fmt.Printf("Post Id : %s\n", post.Id) fmt.Printf("User Id(foreignKey) : %s\n", post.Users) fmt.Printf("Author : %s\n", post.Author) fmt.Printf("Title : %s\n", post.Title) fmt.Printf("Description : %s\n", post.Description) fmt.Printf("Date : %s\n",post.Date) fmt.Printf("Ispresent: %s\n", post.Ispresent) } func init(){ orm.RegisterModel(new(Users), new(Post)) } func AddUser(uid string,username string, password string, email string)(error){ o := orm.NewOrm() o.Using("default") user := new(Users) user.Id = uid user.Username = username user.Salt = com.RandString(10) user.Password = com.Md5(password + user.Salt) user.Email = email o.Insert(user) return nil } func FindUser(username string, id string) (Users ,error, error){ o := orm.NewOrm() o.Using("default") user := Users{Username:username, Id:id} err := o.Read(&user,"username") errr := o.Read(&user, "id") return user, err, errr } func ValidateUser(user Users, password string) error{ flash := beego.NewFlash() u, _ , _ := FindUser(user.Username, user.Id) if u.Username == "" { flash.Error("wrong user name or password!") return errors.New("wrong user name or password!") } fmt.Println(u.Id) fmt.Println(u.Password) fmt.Println(com.Md5(password + u.Salt)) if u.Password != com.Md5(password + u.Salt) { flash.Error("Wrong Password TryAgain") return errors.New("wrong password!") } return nil } func (post *Post) ReadDB() (err error) { o := orm.NewOrm() if err = o.Read(post); err != nil { beego.Info(err) } return } func (users *Users)Read() (err error) { o := orm.NewOrm() err = o.Read(users) return } func (post Post) GetAll() (ret []Post) { o := orm.NewOrm() o.QueryTable("post").OrderBy("-date").Filter("ispresent", 0).All(&ret) return } func (post Post) Gets() (ret []Post) { o := orm.NewOrm() o.QueryTable("post").Filter("Users", post.Users).Filter("ispresent", 0).All(&ret) return } func (post Post) Update() (err error) { o := orm.NewOrm() if _, err = o.Update(&post); err != nil { beego.Info(err) } return }
true
aeb0d529e30101252fef636bc4121b2e5c531d90
Go
markfisher/rokn
/pkg/reconciler/broker/resources/exchange_test.go
UTF-8
2,804
2.578125
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package resources_test import ( "context" "fmt" "github.com/markfisher/rokn/pkg/reconciler/broker/resources" "github.com/markfisher/rokn/pkg/reconciler/internal/testrabbit" "gotest.tools/assert" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" eventingv1beta1 "knative.dev/eventing/pkg/apis/eventing/v1beta1" "testing" ) const namespace = "foobar" func TestExchangeDeclaration(t *testing.T) { ctx := context.Background() rabbitContainer := testrabbit.AutoStartRabbit(t, ctx) defer testrabbit.TerminateContainer(t, ctx, rabbitContainer) brokerName := "x-change" err := resources.DeclareExchange(&resources.ExchangeArgs{ Broker: &eventingv1beta1.Broker{ ObjectMeta: metav1.ObjectMeta{ Name: brokerName, Namespace: namespace, }, }, RabbitmqURL: testrabbit.BrokerUrl(t, ctx, rabbitContainer), }) assert.NilError(t, err) exchanges := testrabbit.FindOwnedExchanges(t, ctx, rabbitContainer) assert.Equal(t, len(exchanges), 1) createdExchange := exchanges[0] assert.Equal(t, createdExchange["durable"], true) assert.Equal(t, createdExchange["auto_delete"], false) assert.Equal(t, createdExchange["internal"], false) assert.Equal(t, createdExchange["type"], "headers") assert.Equal(t, createdExchange["name"], fmt.Sprintf("%s/knative-%s", namespace, brokerName)) } func TestIncompatibleExchangeDeclarationFailure(t *testing.T) { ctx := context.Background() rabbitContainer := testrabbit.AutoStartRabbit(t, ctx) defer testrabbit.TerminateContainer(t, ctx, rabbitContainer) brokerName := "x-change" exchangeName := fmt.Sprintf("%s/knative-%s", namespace, brokerName) testrabbit.CreateExchange(t, ctx, rabbitContainer, exchangeName, "direct") err := resources.DeclareExchange(&resources.ExchangeArgs{ Broker: &eventingv1beta1.Broker{ ObjectMeta: metav1.ObjectMeta{ Name: brokerName, Namespace: namespace, }, }, RabbitmqURL: testrabbit.BrokerUrl(t, ctx, rabbitContainer), }) assert.ErrorContains(t, err, fmt.Sprintf("inequivalent arg 'type' for exchange '%s'", exchangeName)) } func TestExchangeDeletion(t *testing.T) { ctx := context.Background() rabbitContainer := testrabbit.AutoStartRabbit(t, ctx) defer testrabbit.TerminateContainer(t, ctx, rabbitContainer) brokerName := "x-change" exchangeName := fmt.Sprintf("%s/knative-%s", namespace, brokerName) testrabbit.CreateExchange(t, ctx, rabbitContainer, exchangeName, "headers") err := resources.DeleteExchange(&resources.ExchangeArgs{ Broker: &eventingv1beta1.Broker{ ObjectMeta: metav1.ObjectMeta{ Name: brokerName, Namespace: namespace, }, }, RabbitmqURL: testrabbit.BrokerUrl(t, ctx, rabbitContainer), }) assert.NilError(t, err) exchanges := testrabbit.FindOwnedExchanges(t, ctx, rabbitContainer) assert.Equal(t, len(exchanges), 0) }
true
e738c783c5ab20d36c0e17fc7e84c6635cf2ce66
Go
timdadd/simpleMS
/services/frontend/lib/common/web.go
UTF-8
5,492
3.03125
3
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
package common import ( "errors" "fmt" "html/template" "io" "io/ioutil" "net/http" "os" "path/filepath" "runtime/debug" "strings" "time" ) // https://blog.golang.org/error-handling-and-go type appHandler func(http.ResponseWriter, *http.Request) *appError type appError struct { err error message string code int req *http.Request c *AppConfig stack []byte } // parseTemplate applies a given file to the body of the base template. func parseTemplate(filename string) *appTemplate { tmpl := template.Must(template.ParseFiles("templates/base.html")) // Put the named file into a template called "body" path := filepath.Join("templates", filename) b, err := ioutil.ReadFile(path) if err != nil { App.Log.Errorf("could not read template: %v", err) panic(fmt.Errorf("could not read template: %v", err)) } template.Must(tmpl.New("body").Parse(string(b))) return &appTemplate{tmpl.Lookup("base.html")} } // appTemplate is an appError-aware wrapper for a html/template. type appTemplate struct { t *template.Template } // Execute writes the template using the provided data. func (tmpl *appTemplate) Execute(c *AppConfig, w http.ResponseWriter, r *http.Request, data interface{}) *appError { d := struct { Data interface{} }{ Data: data, } if err := tmpl.t.Execute(w, d); err != nil { return c.appErrorf(r, err, "could not write template: %v", err) } return nil } func (c *AppConfig) appErrorf(r *http.Request, err error, format string, v ...interface{}) *appError { return &appError{ err: err, message: fmt.Sprintf(format, v...), code: 500, req: r, c: c, stack: debug.Stack(), } } // // Based on version from Konstanin Ivanov <[email protected]> // Basically this loads templates and uses the directory structure to provide // prefix. // So if you you load all templates in templates and there is an edit.gohtml in subdir then // the name is subdir_edit // A Tmpl implements keeper, loader and reloader for HTML templates type Tmpl struct { *template.Template // root template dir string // root directory ext string // extension devel bool // reload every time funcs template.FuncMap // functions loadedAt time.Time // loaded at (last loading time) } // NewTmpl creates new Tmpl and loads templates. The dir argument is // directory to load templates from. The ext argument is extension of // templates. The devel (if true) turns the Tmpl to reload templates // every Render if there is a change in the dir. func NewTmpl(dir, ext string, devel bool) (tmpl *Tmpl, err error) { // get absolute path if dir, err = filepath.Abs(dir); err != nil { return } tmpl = new(Tmpl) tmpl.dir = dir tmpl.ext = ext tmpl.devel = devel if err = tmpl.Load(); err != nil { tmpl = nil // drop for GC } return } // Dir returns absolute path to directory with views func (t *Tmpl) Dir() string { return t.dir } // Ext returns extension of views func (t *Tmpl) Ext() string { return t.ext } // Devel returns development pin func (t *Tmpl) Devel() bool { return t.devel } // Funcs sets template functions func (t *Tmpl) Funcs(funcMap template.FuncMap) { t.Template = t.Template.Funcs(funcMap) t.funcs = funcMap } // Load or reload templates func (t *Tmpl) Load() (err error) { // time point t.loadedAt = time.Now() // unnamed root template var root = template.New("") var walkFunc = func(path string, info os.FileInfo, err error) (_ error) { // handle walking error if any if err != nil { return err } // skip all except regular files if !info.Mode().IsRegular() { return } // filter by extension if filepath.Ext(path) != t.ext { return } // get relative path var rel string if rel, err = filepath.Rel(t.dir, path); err != nil { return err } // name of a template is its relative path // without extension rel = strings.TrimSuffix(rel, t.ext) // load or reload var ( nt = root.New(rel) b []byte ) if b, err = ioutil.ReadFile(path); err != nil { return err } _, err = nt.Parse(string(b)) return err } if err = filepath.Walk(t.dir, walkFunc); err != nil { return } // necessary for reloading if t.funcs != nil { root = root.Funcs(t.funcs) } t.Template = root // set or replace return } // IsModified lookups directory for changes to // reload (or not to reload) templates if development // pin is true. func (t *Tmpl) IsModified() (yep bool, err error) { var errStop = errors.New("stop") var walkFunc = func(path string, info os.FileInfo, err error) (_ error) { // handle walking error if any if err != nil { return err } // skip all except regular files if !info.Mode().IsRegular() { return } // filter by extension if filepath.Ext(path) != t.ext { return } if yep = info.ModTime().After(t.loadedAt); yep == true { return errStop } return } // clear the errStop if err = filepath.Walk(t.dir, walkFunc); err == errStop { err = nil } return } func (t *Tmpl) Render(w io.Writer, name string, data interface{}) (err error) { // if devlopment if t.devel == true { // lookup directory for changes var modified bool if modified, err = t.IsModified(); err != nil { return } // reload if modified == true { if err = t.Load(); err != nil { return } } } err = t.ExecuteTemplate(w, name, data) return }
true
806a0340b8f810dc4020f63bbd7a7b7bf68c3f78
Go
wenchaopeng/go-qlc
/common/event/event_bus_test.go
UTF-8
4,508
3.0625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
/* * Copyright (c) 2019 QLC Chain Team * * This software is released under the MIT License. * https://opensource.org/licenses/MIT */ package event import ( "sync" "testing" "time" ) func TestNew(t *testing.T) { bus := New() if bus == nil { t.Log("New EventBus not created!") t.Fail() } } func TestHasCallback(t *testing.T) { bus := New() err := bus.Subscribe("topic", func() {}) if err != nil { t.Fatal(err) } if bus.HasCallback("topic_topic") { t.Fail() } if !bus.HasCallback("topic") { t.Fail() } } func TestSubscribe(t *testing.T) { bus := New() if bus.Subscribe("topic", func() {}) != nil { t.Fail() } if bus.Subscribe("topic", "String") == nil { t.Fail() } } func TestSubscribeOnce(t *testing.T) { bus := New() if bus.SubscribeOnce("topic", func() {}) != nil { t.Fail() } if bus.SubscribeOnce("topic", "String") == nil { t.Fail() } } func TestSubscribeOnceAndManySubscribe(t *testing.T) { bus := New() event := "topic" flag := 0 fn := func(f int) { flag += 1 t.Log(f, flag) } _ = bus.SubscribeOnce(event, fn) _ = bus.Subscribe(event, fn) _ = bus.Subscribe(event, fn) bus.Publish(event, flag) if flag != 3 { t.Fail() } } func TestUnsubscribe(t *testing.T) { bus := New() handler := func() {} err := bus.Subscribe("topic", handler) if err != nil { t.Fatal(err) } if bus.Unsubscribe("topic", handler) != nil { t.Fail() } if bus.Unsubscribe("topic", handler) == nil { t.Fail() } } func TestPublish(t *testing.T) { bus := New() err := bus.Subscribe("topic", func(a int, b int) { if a != b { t.Fail() } }) if err != nil { t.Fatal(err) } bus.Publish("topic", 10, 10) } func TestSubscribeOnceAsync(t *testing.T) { results := make([]int, 0) bus := New() err := bus.SubscribeOnceAsync("topic", func(a int, out *[]int) { *out = append(*out, a) }) if err != nil { t.Fatal(err) } bus.Publish("topic", 10, &results) bus.Publish("topic", 10, &results) bus.WaitAsync() if len(results) != 1 { t.Fail() } if bus.HasCallback("topic") { t.Fail() } } func TestSubscribeAsyncTransactional(t *testing.T) { results := make([]int, 0) bus := New() err := bus.SubscribeAsync("topic", func(a int, out *[]int, dur string) { sleep, _ := time.ParseDuration(dur) time.Sleep(sleep) *out = append(*out, a) }, true) if err != nil { t.Fatal(err) } bus.Publish("topic", 1, &results, "1s") bus.Publish("topic", 2, &results, "0s") bus.WaitAsync() if len(results) != 2 { t.Fail() } if results[0] != 1 || results[1] != 2 { t.Fail() } } func TestSubscribeAsyncTopic(t *testing.T) { results := make([]int, 0) type result struct { A int } bus := New() fn := func(a *result, out *[]int, dur string) { sleep, _ := time.ParseDuration(dur) time.Sleep(sleep) *out = append(*out, a.A) t.Log(&a, a.A) } err := bus.SubscribeAsync("topic:*", fn, true) if err != nil { t.Fatal(err) } bus.Publish("topic:", &result{3}, &results, "1s") bus.Publish("topic:1st", &result{1}, &results, "1s") bus.Publish("topic:2nd", &result{2}, &results, "0s") bus.WaitAsync() if len(results) != 3 { t.Fail() } if results[0] != 3 || results[1] != 1 || results[2] != 2 { t.Fail() } } func TestSubscribeAsync(t *testing.T) { results := make(chan int) bus := New() err := bus.SubscribeAsync("topic", func(a int, out chan<- int) { out <- a }, false) if err != nil { t.Fatal(err) } bus.Publish("topic", 1, results) bus.Publish("topic", 2, results) numResults := 0 go func() { for range results { numResults++ } }() bus.WaitAsync() time.Sleep(10 * time.Millisecond) if numResults != 2 { t.Fail() } } func TestSimpleEventBus(t *testing.T) { eb1 := SimpleEventBus() eb2 := SimpleEventBus() if eb1 != eb2 { t.Fatal("eb1!=eb2") } } func TestGetEventBus(t *testing.T) { eb0 := SimpleEventBus() eb1 := GetEventBus("") if eb0 != eb1 { t.Fatal("invalid default eb") } id1 := "111111" eb2 := GetEventBus(id1) eb3 := GetEventBus(id1) if eb2 != eb3 { t.Fatal("invalid eb of same id") } id2 := "222222" eb4 := GetEventBus(id2) if eb3 == eb4 { t.Fatal("invalid eb of diff ids") } } func TestAsyncGetEvent(t *testing.T) { var eb0 EventBus var eb1 EventBus id1 := "sssdfasdfasd" eb0 = GetEventBus(id1) wg := sync.WaitGroup{} wg.Add(1) go func(id string) { defer wg.Done() eb1 = GetEventBus(id) }(id1) wg.Wait() if eb0 == nil || eb1 == nil || eb0 != eb1 { t.Fatalf("invalid eb0 %p, eb1 %p", eb0, eb1) } }
true
3552e0202026ee6fb858d9c64754c787875f52eb
Go
fd0/drainchecker
/drainchecker.go
UTF-8
1,226
3.28125
3
[ "BSD-2-Clause" ]
permissive
[ "BSD-2-Clause" ]
permissive
package drainchecker import ( "fmt" "io" "io/ioutil" "net/http" "os" ) type eofDetectRoundTripper struct { http.RoundTripper } // RoundTripper returns a new http.RoundTripper which prints a message to // stderr when the HTTP response body is not properly drained. func RoundTripper(upstream http.RoundTripper) http.RoundTripper { return eofDetectRoundTripper{upstream} } type eofDetectReader struct { eofSeen bool rd io.ReadCloser } func (rd *eofDetectReader) Read(p []byte) (n int, err error) { n, err = rd.rd.Read(p) if err == io.EOF { rd.eofSeen = true } return n, err } func (rd *eofDetectReader) Close() error { if !rd.eofSeen { buf, err := ioutil.ReadAll(rd) msg := fmt.Sprintf("body not drained, %d bytes not read", len(buf)) if err != nil { msg += fmt.Sprintf(", error: %v", err) } if len(buf) > 0 { if len(buf) > 20 { buf = append(buf[:20], []byte("...")...) } msg += fmt.Sprintf(", body: %q", buf) } fmt.Fprintln(os.Stderr, msg) } return rd.rd.Close() } func (tr eofDetectRoundTripper) RoundTrip(req *http.Request) (res *http.Response, err error) { res, err = tr.RoundTripper.RoundTrip(req) res.Body = &eofDetectReader{rd: res.Body} return res, err }
true
ca68ac3878894ab731fd25192140b37d577ddf4f
Go
wanghaoxi3000/go-algo
/sort/shell.go
UTF-8
1,040
3.53125
4
[]
no_license
[]
no_license
package sort import "math" /** * @Time : 2020/7/20 17:00 * @Author : wanghaoxi3000 * @Email : [email protected] * @Description : 希尔排序算法 * @Revise : --- */ /* 希尔排序 1. 选择一个增量序列 t1,t2,……,tk,其中 ti > tj, tk = 1 2. 按增量序列个数 k,对序列进行 k 趟排序 3. 每趟排序,根据对应的增量 ti,将待排序列分割成若干长度为 m 的子序列,分别对各子表进行直接插入排序。仅增量因子为 1 时,整个序列作为一个表来处理,表长度即为整个序列的长度。 平均复杂度: O(n log n) 最好情况: O(n log^2 n) 最坏情况: O(n log^2 n) 空间复杂度: O(1) 排序方式: In-place 稳定性: 不稳定 */ func ShellSort(data []int) { gap := 1 for gap < len(data) { gap = gap*3 + 1 } for gap > 0 { for i := gap; i < len(data); i++ { tmp := data[i] j := i - gap for j >= 0 && data[j] > tmp { data[j+gap] = data[j] j -= gap } data[j+gap] = tmp } gap = int(math.Floor(float64(gap) / 3)) } }
true
556a3d289ed0f7eb891367bd3863450beb064b05
Go
Johnson-jjy/Go-AC
/greedy/LC_1005_largestSumAfterKNegations.go
UTF-8
728
3.40625
3
[]
no_license
[]
no_license
package greedy import "sort" // K次取反后最大化的数组和 // 1. 要先排序,想办法把大的负数翻转过来 2.没必要取纠结k和负数的关系,直接先翻转大的负数即可 // 3. 对于index定位,初始值应该考量的是不走else的情况 func largestSumAfterKNegations(nums []int, k int) int { sort.Ints(nums) index := len(nums) - 1 for i := 0; i < len(nums); i++ { if k > 0 && nums[i] < 0 { nums[i] = -nums[i] k-- } else { index = i break } } if k > 0 { if k % 2 == 1 { m := index if index > 0 && nums[index - 1] < nums[index] { m = index - 1 } nums[m] = -nums[m] } } res := 0 for i := 0; i < len(nums); i++ { res += nums[i] } return res }
true
6a99892896589875bce2c1dc22f548ea576e7fd3
Go
AndrewVos/statistic.li
/application_test.go
UTF-8
3,096
2.9375
3
[]
no_license
[]
no_license
package main import ( "encoding/json" "io/ioutil" "net/http" "net/http/httptest" "net/url" "testing" ) var server *httptest.Server func setup() { DeleteAllClientHits() if server != nil { server.Close() } server = httptest.NewServer(http.HandlerFunc(clientHandler)) } func get(url string, cookies []*http.Cookie) (*http.Response, string) { client := &http.Client{} request, _ := http.NewRequest("GET", url, nil) if cookies != nil { for _, cookie := range cookies { request.AddCookie(cookie) } } response, _ := client.Do(request) body, _ := ioutil.ReadAll(response.Body) response.Body.Close() return response, string(body) } func expectContentType(t *testing.T, path string, contentType string) { response, _ := get(server.URL+path, nil) if response.Header["Content-Type"][0] != contentType { t.Errorf("Expected %q to return a Content-Type of %q, not %q\n", path, contentType, response.Header["Content-Type"][0]) } } func TestContentTypes(t *testing.T) { setup() expectContentType(t, "/client/CLIENT_ID/uniques", "application/json") expectContentType(t, "/client/CLIENT_ID/referers", "application/json") expectContentType(t, "/client/CLIENT_ID/pages", "application/json") expectContentType(t, "/client/CLIENT_ID/tracker.gif", "image/gif") } func TestTrackerRespondsWithGif(t *testing.T) { setup() _, gif := get(server.URL+"/client/MY_CLIENT_ID/tracker.gif", nil) if gif != string(tracker_gif()) { t.Errorf("Expected:\n%q\nGot:\n%q\n", string(tracker_gif()), gif) } } func TestTopPagesRoute(t *testing.T) { setup() get(server.URL+"/client/site.com/tracker.gif?page=page1&referer=referer1", nil) _, body := get(server.URL+"/client/site.com/pages", nil) expected, _ := json.Marshal(GetTopPages("site.com")) if body != string(expected) { t.Errorf("Expected:\n%q\nGot:\n%q\n", string(expected), body) t.Fail() } } func TestTopReferersRoute(t *testing.T) { setup() get(server.URL+"/client/site.com/tracker.gif?page=page1&referer=referer1", nil) _, body := get(server.URL+"/client/site.com/referers", nil) expected, _ := json.Marshal(GetTopReferers("site.com")) if body != string(expected) { t.Errorf("Expected:\n%q\nGot:\n%q\n", string(expected), body) t.Fail() } } func TestStoresClientHit(t *testing.T) { setup() cookies := []*http.Cookie{ {Name: "sts", Value: "theUserID1213"}, } get(server.URL+"/client/site.com/tracker.gif?page=page1&referer=referer1", cookies) hits := LatestClientHits("site.com") if len(hits) != 1 { t.Errorf("Expected there to be %v hits, but there was %v", 2, len(hits)) } if hits[0].Referer != "referer1" { t.Errorf("Expected referer to be set") } if hits[0].ClientID != "site.com" { t.Errorf("Expected client id to be set") } if hits[0].UserID != "theUserID1213" { t.Errorf("Expected user id to be set") } } func BenchmarkStoreClientHit(b *testing.B) { for i := 0; i < b.N; i++ { referer := "referer.com" page := "http://www.client.com/page1.html" get(server.URL+"/client/CLIENT_ID/tracker.gif?referer="+url.QueryEscape(referer)+"&page="+url.QueryEscape(page), nil) } }
true
2619289233f6e51d44c900d4f683b6394e648ff3
Go
jaskiratvig/golang-restapi-dynamodb-serverless
/aws-golang-http-get-post/routers/crud/editArtist/editArtist.go
UTF-8
2,252
2.78125
3
[]
no_license
[]
no_license
package main import ( "aws-golang-http-get-post/dynamoDB" "aws-golang-http-get-post/models" "aws-golang-http-get-post/ses" "encoding/json" "fmt" "os" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" ) // Handler function Using AWS Lambda Proxy Request func Handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { svc := dynamoDB.CreateDynamoDBClient() item, err := dynamoDB.GetArtist(request) if err != nil { return events.APIGatewayProxyResponse{Body: err.Error(), StatusCode: 404}, err } // BodyRequest will be used to take the json response from client and build it bodyRequest := models.Artist{ ArtistID: item.ArtistID, Name: item.Name, Songs: item.Songs, Subcategory: item.Subcategory, Domestic: item.Domestic, } // Unmarshal the json, return 404 if error err = json.Unmarshal([]byte(request.Body), &bodyRequest) if err != nil { return events.APIGatewayProxyResponse{Body: err.Error(), StatusCode: 404}, err } av, err := dynamodbattribute.MarshalMap(bodyRequest) if err != nil { fmt.Println("Got error marshalling new movie item:") fmt.Println(err.Error()) os.Exit(1) } input := &dynamodb.PutItemInput{ Item: av, TableName: aws.String("Artists"), } _, err = svc.PutItem(input) if err != nil { fmt.Println("Got error calling PutItem:") fmt.Println(err.Error()) os.Exit(1) } // Marshal the response into json bytes, if error return 404 response, err := json.Marshal(&bodyRequest) if err != nil { return events.APIGatewayProxyResponse{Body: err.Error(), StatusCode: 404}, err } message := "An artist has been editted to have the following attributes: " + string(response) HTMLBody := "<h1>Success</h1><p>An artist has been editted to have the following attributes: " + string(response) + "</p>" err = ses.SendEmail(HTMLBody) if err != nil { return events.APIGatewayProxyResponse{Body: err.Error(), StatusCode: 404}, err } return events.APIGatewayProxyResponse{Body: message, StatusCode: 200}, nil } func main() { lambda.Start(Handler) }
true
32fb8f0df8163cbe9f0e23b236c2682df3948f8b
Go
Global-localhost/cloudfoundry-cli-archived
/src/cf/commands/routes_test.go
UTF-8
1,518
2.875
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package commands_test import ( "cf" . "cf/commands" "github.com/stretchr/testify/assert" "testhelpers" "testing" ) func TestListingRoutes(t *testing.T) { routes := []cf.Route{ cf.Route{ Host: "hostname-1", Domain: cf.Domain{Name: "example.com"}, }, cf.Route{ Host: "hostname-2", Domain: cf.Domain{Name: "cfapps.com"}, }, } routeRepo := &testhelpers.FakeRouteRepository{FindAllRoutes: routes} ui := &testhelpers.FakeUI{} cmd := NewRoutes(ui, routeRepo) cmd.Run(testhelpers.NewContext("routes", []string{})) assert.Contains(t, ui.Outputs[0], "Getting routes") assert.Contains(t, ui.Outputs[1], "OK") assert.Contains(t, ui.Outputs[2], "hostname-1.example.com") assert.Contains(t, ui.Outputs[3], "hostname-2.cfapps.com") } func TestListingRoutesWhenNoneExist(t *testing.T) { routes := []cf.Route{} routeRepo := &testhelpers.FakeRouteRepository{FindAllRoutes: routes} ui := &testhelpers.FakeUI{} cmd := NewRoutes(ui, routeRepo) cmd.Run(testhelpers.NewContext("routes", []string{})) assert.Contains(t, ui.Outputs[0], "Getting routes") assert.Contains(t, ui.Outputs[1], "OK") assert.Contains(t, ui.Outputs[2], "No routes found") } func TestListingRoutesWhenFindFails(t *testing.T) { routeRepo := &testhelpers.FakeRouteRepository{FindAllErr: true} ui := &testhelpers.FakeUI{} cmd := NewRoutes(ui, routeRepo) cmd.Run(testhelpers.NewContext("routes", []string{})) assert.Contains(t, ui.Outputs[0], "Getting routes") assert.Contains(t, ui.Outputs[1], "FAILED") }
true
5721561a8bd093a972e02af6cece494bbae7c619
Go
zaker/go-qr-term
/mask.go
UTF-8
594
3.171875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import "math" type maskFunc func(x, y int) bool var masks map[int]maskFunc = map[int]maskFunc{ 0: func(x, y int) bool { return (x+y)%2 == 0 }, 1: func(x, y int) bool { return (x)%2 == 0 }, 2: func(x, y int) bool { return (y)%3 == 0 }, 3: func(x, y int) bool { return (x+y)%3 == 0 }, 4: func(x, y int) bool { return int(math.Floor(float64(x)/2)+math.Floor(float64(y)/3))%2 == 0 }, 5: func(x, y int) bool { return ((x*y)%2)+((x*y)%3) == 0 }, 6: func(x, y int) bool { return (((x*y)%2)+((x*y)%3))%2 == 0 }, 7: func(x, y int) bool { return (((x+y)%2)+((x*y)%3))%2 == 0 }, }
true
63ea74c153634fe068fc1df8931c4ceb26ce308b
Go
alexon1234/golang-api
/pkg/post/domain/post.go
UTF-8
342
2.734375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package domain // Post - Domain of the post type Post struct { ID string `json:"id"` Title string `json:"title"` Body string `json:"body"` } // Repository - interface of the Post Repository type Repository interface { RunMigrations() FetchPosts() (*[]Post, error) GetPost(id string) (*Post, error) CreatePost(post *Post) error }
true
912e84ef2b63e275859f9225ce281a8f95f9aa59
Go
dna2zodiac/codehub
/google/golang/1.14.2/index.suffixarray.go
UTF-8
2,235
3.40625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package suffixarray implements substring search in logarithmic time using // an in-memory suffix array. // // Example use: // // // create index for some data // index := suffixarray.New(data) // // // lookup byte slice s // offsets1 := index.Lookup(s, -1) // the list of all indices where s occurs in data // offsets2 := index.Lookup(s, 3) // the list of at most 3 indices where s occurs in data // package suffixarray import ( "errors" "io" ) // Index implements a suffix array for fast substring search. type Index struct { data []byte sa ints // suffix array for data; sa.len() == len(data) } // New creates a new Index for data. // Index creation time is O(N) for N = len(data). func New(data []byte) *Index {} // Read reads the index from r into x; x must not be nil. func (x *Index) Read(r io.Reader) error {} // Write writes the index x to w. func (x *Index) Write(w io.Writer) error {} // Bytes returns the data over which the index was created. // It must not be modified. // func (x *Index) Bytes() []byte {} // Lookup returns an unsorted list of at most n indices where the byte string s // occurs in the indexed data. If n < 0, all occurrences are returned. // The result is nil if s is empty, s is not found, or n == 0. // Lookup time is O(log(N)*len(s) + len(result)) where N is the // size of the indexed data. // func (x *Index) Lookup(s []byte, n int) (result []int) {} /* package main import ( "fmt" "index/suffixarray" ) func main() { index := suffixarray.New([]byte("banana")) offsets := index.Lookup([]byte("ana"), -1) for _, off := range offsets { fmt.Println(off) } } */ // FindAllIndex returns a sorted list of non-overlapping matches of the // regular expression r, where a match is a pair of indices specifying // the matched slice of x.Bytes(). If n < 0, all matches are returned // in successive order. Otherwise, at most n matches are returned and // they may not be successive. The result is nil if there are no matches, // or if n == 0. // func (x *Index) FindAllIndex(r *regexp.Regexp, n int) (result [][]int) {}
true
6e1cdae6cb0997b42070b13dd8d4e21012e84890
Go
keep94/gofunctional2
/examples/power2/power2.go
UTF-8
1,905
3.46875
3
[ "BSD-3-Clause" ]
permissive
[ "BSD-3-Clause" ]
permissive
// Copyright 2013 Travis Keep. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or // at http://opensource.org/licenses/BSD-3-Clause. // This example is just like power, but does not make recursive calls to // functional.NewGenerator. functional.NewGenerator uses channels to simulate // the behavior of python generators. While channels are cheap in go, they // are not free. As a result, this example runs 10X faster than the power // example. package main import ( "fmt" "github.com/keep94/gofunctional2/functional" ) var ess = emptySetStream{} // Power returns a Stream that emits the power set of items. Next of // returned Stream emits to an []int that has same length as items. func Power(items []int) functional.Stream { len := len(items) if len == 0 { return functional.Slice(ess, 0, 1) } return functional.Concat( Power(items[:len-1]), functional.Deferred(func() functional.Stream { return functional.Filter( appendFilterer(items[len-1]), Power(items[:len-1])) })) } type emptySetStream struct { } func (s emptySetStream) Next(ptr interface{}) error { p := ptr.(*[]int) *p = (*p)[:0] return nil } func (s emptySetStream) Close() error { return nil } // appendFilterer adds a particular int to an existing set. type appendFilterer int func (a appendFilterer) Filter(ptr interface{}) error { p := ptr.(*[]int) *p = append(*p, int(a)) return nil } func main() { orig := make([]int, 100) for i := range orig { orig[i] = i } // Return the 10000th up to the 10010th element of the power set of // {0, 1, .. 99}. // This entire power set would have 2^100 elements in it! s := functional.Slice(Power(orig), 10000, 10010) result := make([]int, len(orig)) for s.Next(&result) == nil { fmt.Println(result) } }
true
79f03a71718e04f95e231cd1d0fe6ec4ec6d4dd9
Go
0x7b1/algorithms
/leetcode/0079.go
UTF-8
1,037
3.5625
4
[]
no_license
[]
no_license
package main import "fmt" func searchWord(board [][]byte, height, width int, word string, x, y, i int) bool { if len(word) == i { return true } if y < 0 || y >= height || x < 0 || x >= width { return false } if board[y][x] != word[i] { return false } board[y][x] ^= 0xFF exist := searchWord(board, height, width, word, x-1, y, i+1) || searchWord(board, height, width, word, x+1, y, i+1) || searchWord(board, height, width, word, x, y-1, i+1) || searchWord(board, height, width, word, x, y+1, i+1) board[y][x] ^= 0xFF return exist } func exist(board [][]byte, word string) bool { height, width := len(board), len(board[0]) for y := 0; y < height; y++ { for x := 0; x < width; x++ { if searchWord(board, height, width, word, x, y, 0) { return true } } } return false } func main() { board := [][]byte{ {'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}, } fmt.Println(exist(board, "ABCCED")) fmt.Println(exist(board, "SEE")) fmt.Println(exist(board, "ABCB")) }
true
1a4cebef389369e2e7afabb30d609c660b26c5db
Go
ljfuyuan/practice
/Algorithms/InsertSort_test.go
UTF-8
1,042
3.15625
3
[]
no_license
[]
no_license
/*============================================================================= # FileName: InsertSort_test.go # Desc: # Author: ljfuyuan # Email: [email protected] # Create: 2016-06-20 18:19:27 # LastChange: 2016-06-22 19:55:42 # History: =============================================================================*/ package algorithm import ( "testing" ) func insertSort_IsEqual(data []int) (status bool) { status = true var correctData = []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} for k, v := range data { if v != correctData[k] { status = false break } } return status } func Test_InsertSort_1(t *testing.T) { var data = []int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1} data = InsertSort_1(data) if !insertSort_IsEqual(data) { t.Error("InsertSort_1 is not equal to correct answer", data) } } func Test_InsertSort_2(t *testing.T) { var data = []int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1} InsertSort_2(data) if !insertSort_IsEqual(data) { t.Error("InsertSort_2 is not equal to correct answer", data) } }
true
8820f226b619ce4ffc8ebeaa0ffec6e5c334696e
Go
nkoblai/goexercises
/go-tour/stringer.go
UTF-8
786
3.5
4
[]
no_license
[]
no_license
package stringer import ( "fmt" "strconv" "strings" ) // IPAddr type represents ip-adress. type IPAddr [4]byte var hosts = map[string]IPAddr{ "loopback": {127, 0, 0, 1}, "googleDNS": {8, 8, 8, 8}, } // String returns address as a dotted quad. func (ip IPAddr) String() string { str := fmt.Sprintf("%v", ip[0]) for _, b := range ip[1:] { str += fmt.Sprintf(".%v", b) } return str } // Convert returns address as a dotted quad. func (ip IPAddr) Convert() string { s := make([]string, len(ip)) for i := range ip { s[i] = strconv.Itoa(int(ip[i])) } return strings.Join(s, ".") } // TODO: Add a "String() string" method to IPAddr. func main() { for name, ip := range hosts { fmt.Printf("%v: %v\n", name, ip) fmt.Printf("%v: %v\n", name, IPAddr.Convert(ip)) } }
true
ab13d209094f547f3d364ce8c366030e4af43b8f
Go
mfhholmes/Orbital
/src/github.com/mfhholmes/Orbital/actionList.go
UTF-8
2,190
3.390625
3
[]
no_license
[]
no_license
package main import ( "sort" ) import ( "time" ) import ( "fmt" ) var isRunning bool type processFunc func() type controlInstruction struct { runLoop bool delay time.Duration } type actionItem struct { execTime time.Time process processFunc } //ActionList is a list of Action Items, which is then type ActionList struct { items []*actionItem } func (al *ActionList) Pop() *actionItem { if len(al.items) == 0 { // return an item that does nothing and is set to run an hour from now return &actionItem{execTime: time.Now().Add(time.Hour), process: func() {}} } var result = al.items[0] al.items = al.items[1:] return result } func (al ActionList) Peek(index int) *actionItem { if index < 0 { index = 0 } if len(al.items) == 0 { // return an item that does nothing and is set to run a year from now return &actionItem{execTime: time.Now().Add(time.Hour), process: func() {}} } if index > len(al.items) { index = len(al.items) - 1 } return al.items[index] } func (al *ActionList) Push(newItem *actionItem) { al.items = append(al.items, newItem) sort.Sort(al) } func (al ActionList) Len() int { return len(al.items) } func (al ActionList) Less(i, j int) bool { return al.items[i].execTime.Before(al.items[j].execTime) } func (al ActionList) Swap(i, j int) { al.items[i], al.items[j] = al.items[j], al.items[i] } func (al ActionList) listStatus() string { if len(al.items) > 0 { return fmt.Sprintf("items: %d earliest: %s", len(al.items), al.items[0].execTime.String()) } return "no items in queue" } func (al *ActionList) mainLoop(controlChannel chan controlInstruction) { timeout := make(chan bool, 1) runLoop := true delay := (100 * time.Millisecond) for runLoop { isRunning = true if al.Len() > 0 { for al.Peek(0).execTime.Before(time.Now()) { go al.Pop().process() } } // kicks off a 100ms delay, which is used to check the control channel for control instructions go func() { time.Sleep(delay) timeout <- true }() select { case command := <-controlChannel: runLoop = command.runLoop delay = command.delay case <-timeout: // timeout, so continue around the loop } } isRunning = false }
true
f78f9e1a61ac91ba52e6e8e3c44ecd8997a5e43f
Go
shieldproject/misfit-toys
/dedsocket/main.go
UTF-8
2,752
2.671875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "crypto/tls" "fmt" "net" "net/http" "net/url" "os" "github.com/gorilla/websocket" "github.com/jhunt/go-ansi" "github.com/shieldproject/shield/client/v2/shield" "golang.org/x/crypto/ssh/terminal" ) // This program connects to the SHIELD websocket and then just doesn't read the // buffer func main() { if len(os.Args) < 2 { bailWith("positional argument <URL> is required") } targetURLStr := os.Args[1] targetURL, err := url.Parse(targetURLStr) if err != nil { bailWith("Could not parse URL: %s", err) } if targetURL.Scheme == "" { targetURL.Scheme = "http" } else if targetURL.Scheme != "http" && targetURL.Scheme != "https" { bailWith("Unknown scheme: %s", targetURL.Scheme) } if targetURL.Port() == "" { switch targetURL.Scheme { case "http": targetURL.Host = targetURL.Host + ":80" case "https": targetURL.Host = targetURL.Host + ":443" default: bailWith("Cannot determine URL port") } } shieldClient := shield.Client{ URL: targetURLStr, InsecureSkipVerify: true, } var username, password string fmt.Fprint(os.Stderr, "SHIELD Username: ") fmt.Scanln(&username) fmt.Fprint(os.Stderr, "SHIELD Password: ") passBytes, err := terminal.ReadPassword(int(os.Stdout.Fd())) fmt.Println("") if err != nil { bailWith("could not read password: %s", err) } password = string(passBytes) err = shieldClient.Authenticate(&shield.LocalAuth{ Username: username, Password: password, }) if err != nil { bailWith("failed to authenticate: %s", err) } websocketDialer := websocket.Dialer{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } headers := http.Header{} headers.Add("X-Shield-Session", shieldClient.Session) if targetURL.Scheme == "http" { targetURL.Scheme = "ws" } else { targetURL.Scheme = "wss" } targetURL.Path = "/v2/events" conn, _, err := websocketDialer.Dial(targetURL.String(), headers) if err != nil { bailWith("error when dialing: %s", err.Error()) } netConn := conn.UnderlyingConn() tcpConn := netConn.(*net.TCPConn) fmt.Fprintf(os.Stderr, "Setting read buffer size\n") err = tcpConn.SetReadBuffer(4096) if err != nil { bailWith("Could not set read buffer size: %s", err) } fmt.Fprintf(os.Stderr, "Successfully set buffer size\n") quitChan := make(chan bool) go func() { for { fmt.Fprintf(os.Stderr, "Type `quit' to exit: ") var input string fmt.Scanln(&input) if input == "quit" || input == "exit" { quitChan <- true break } } }() <-quitChan conn.Close() } func bailWith(format string, args ...interface{}) { _, err := ansi.Fprintf(os.Stderr, "@R{"+format+"}\n", args...) if err != nil { panic(fmt.Sprintf(format, args...)) } os.Exit(1) }
true