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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ac6c62d9b154bcfde99f2f71b8ffceb67fdbeb73
|
Go
|
theikalman/gohealthz
|
/internal/pkg/handler/website.go
|
UTF-8
| 4,333
| 3.359375
| 3
|
[] |
no_license
|
[] |
no_license
|
package handler
import (
"encoding/json"
"log"
"net/http"
"net/url"
"github.com/ajiyakin/gohealthz/internal/pkg/storage"
"github.com/google/uuid"
)
var (
httpGetRequestFunc = http.Get
)
type createWebsiteRequest struct {
URL string `json:"url"`
}
type getWebsitesResponse struct {
ID string `json:"id"`
URL string `json:"url"`
Healty bool `json:"healty"`
}
// NewWebsiteHandler initilize and get handler for doing website operations
// (POST, GET, DELETE)
func NewWebsiteHandler(database storage.Database) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
createWebsite(w, r, database)
return
}
if r.Method == http.MethodGet {
getWebsites(w, r, database)
return
}
if r.Method == http.MethodDelete {
deleteWebsite(w, r, database)
return
}
log.Printf("%s - method %s is not allowed", r.URL.Path, r.Method)
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
func getWebsites(w http.ResponseWriter, r *http.Request, database storage.Database) {
websites, err := database.Get()
if err != nil {
log.Printf("unable to get list of website from database: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
// initilize with make with 0 capacity so if there's no records found,
// the response body will be [] instead of null
responseBody := make([]getWebsitesResponse, 0)
for _, website := range websites {
responseBody = append(responseBody, getWebsitesResponse{
ID: website.ID,
URL: website.URL,
Healty: website.Healthy,
})
}
w.Header().Add("Content-Type", "application/json")
if err = json.NewEncoder(w).Encode(&responseBody); err != nil {
log.Printf("unable to encode records to response writter: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
log.Print("successfully retrieve website records")
}
func createWebsite(w http.ResponseWriter, r *http.Request, database storage.Database) {
var requestBody createWebsiteRequest
if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {
log.Printf("unable to decode request body: %v", err)
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
id, err := uuid.NewUUID()
if err != nil {
log.Printf("unable to generate new UUID: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
_, err = url.ParseRequestURI(requestBody.URL)
if err != nil {
log.Printf("unable to parse URL: %v with URL input: %s", err, requestBody.URL)
http.Error(w, "invalid URL. URL must be in form of absolute URL", http.StatusBadRequest)
return
}
// TODO Set timeout to 800ms
var healthiness bool
response, err := httpGetRequestFunc(requestBody.URL)
if err != nil {
log.Printf("url %s is not healthy: %v", requestBody.URL, err)
}
if err == nil && response.StatusCode == http.StatusOK {
healthiness = true
}
err = database.Save(storage.Website{
ID: id.String(),
URL: requestBody.URL,
Healthy: healthiness,
})
if err != nil {
log.Printf("unable to save to database: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
log.Print("successfully store website to database")
w.WriteHeader(http.StatusCreated)
}
// deleteWebsite removes a website from database. delete action will ALWAYS
// return success whether the record is found or not within database
func deleteWebsite(w http.ResponseWriter, r *http.Request, database storage.Database) {
if err := r.ParseForm(); err != nil {
log.Printf("unable to parse form: %v", err)
http.Error(w, "invalid form parameter", http.StatusBadRequest)
return
}
websiteID := r.FormValue("website_id")
if websiteID == "" {
log.Printf("website_id is empty")
http.Error(w, "website_id is required", http.StatusBadRequest)
return
}
if err := database.Delete(websiteID); err != nil {
log.Printf("unable to delete a website with id: %s from database: %v", websiteID, err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
log.Printf("success delete website with id: %s", websiteID)
w.WriteHeader(http.StatusOK)
}
| true
|
35936964c860690c38e45d6a5624e4e389c73f59
|
Go
|
dscalo/AdventOfCode2020
|
/puzzles/day25.go
|
UTF-8
| 1,290
| 3.375
| 3
|
[] |
no_license
|
[] |
no_license
|
package puzzles
import (
"bufio"
"fmt"
"os"
"strconv"
)
func init() {
Days[25] = Day25
}
func readKeys(path string) []int {
file, err := os.Open(path)
if err != nil {
panic(err)
}
keys := make([]int, 2)
scanner := bufio.NewScanner(file)
idx := 0
for scanner.Scan() {
line := scanner.Text()
n, _ := strconv.Atoi(line)
keys[idx] = n
idx++
}
return keys
}
func transform(subjectNumber, loopSize int) int {
value := 1
for i := 0; i < loopSize; i++ {
value *= subjectNumber
value = value % 20201227
//fmt.Printf("value: %d\n", value)
}
return value
}
func getLoopSize(key int) int {
subjectNumber := 7
value := 1
idx := 0
for {
//if idx > 100000000 {
// fmt.Println("SOMETHING IS WRONG")
// return -1
//}
value *= subjectNumber
value = value % 20201227
//fmt.Printf(" key : %d value = %d\n",key, value)
idx++
if value == key {
return idx
}
}
return -1
}
func Day25() {
inputs := []string{"test01", "puzzle"} //
for _, f := range inputs {
path := fmt.Sprintf("input/day25/%s.input", f)
keys := readKeys(path)
fmt.Println(keys)
lp1 := getLoopSize(keys[0])
//lp2 := getLoopSize(keys[1])
ansP1 := transform(keys[1], lp1)
ansP2 := -1
fmt.Printf("%s part 1 : %d | part 2: %d \n", f, ansP1, ansP2)
}
}
| true
|
6a683de20ea5da4c96dca362e309338141696bef
|
Go
|
pluscc93/leetcode
|
/26/removeDuplicates.go
|
UTF-8
| 415
| 3.25
| 3
|
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
func removeDuplicates(nums []int) int {
if len(nums) <= 0 {
return 0
}
tmp := nums[0]
i, j := 1, 1
for ; i < len(nums); i++ {
for i < len(nums) && tmp == nums[i] {
i++
}
if i >= len(nums) {
break
}
nums[j] = nums[i]
tmp = nums[i]
j++
}
nums = nums[:j]
fmt.Println(nums)
return j
}
func main() {
nums := []int{1, 1}
fmt.Println(removeDuplicates(nums))
}
| true
|
3a9ab2537fe52641b6b02aad558ce9a874a6b34d
|
Go
|
aarshkshah1992/go-ipld-prime
|
/_rsrch/microbench/multihoisting/soln/soln_test.go
|
UTF-8
| 1,060
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package solution
import (
"fmt"
"runtime"
"testing"
)
func init() {
runtime.GOMAXPROCS(1) // necessary if we want to do precise accounting on runtime.ReadMemStats.
}
var sink interface{}
func TestAllocCount(t *testing.T) {
memUsage := func(m1, m2 *runtime.MemStats) {
fmt.Println(
"Alloc:", m2.Alloc-m1.Alloc,
"TotalAlloc:", m2.TotalAlloc-m1.TotalAlloc,
"HeapAlloc:", m2.HeapAlloc-m1.HeapAlloc,
"Mallocs:", m2.Mallocs-m1.Mallocs,
"Frees:", m2.Frees-m1.Frees,
)
}
var m [99]runtime.MemStats
runtime.GC()
runtime.GC() // i know not why, but as of go-1.13.3, and not in go-1.12.5, i have to call this twice before we start to get consistent numbers.
runtime.ReadMemStats(&m[0])
var x Node
x = &Stroct{}
runtime.GC()
runtime.ReadMemStats(&m[1])
x = x.LookupByString("foo")
runtime.GC()
runtime.ReadMemStats(&m[2])
sink = x
runtime.GC()
runtime.ReadMemStats(&m[3])
sink = nil
runtime.GC()
runtime.ReadMemStats(&m[4])
memUsage(&m[0], &m[1])
memUsage(&m[0], &m[2])
memUsage(&m[0], &m[3])
memUsage(&m[0], &m[4])
}
| true
|
d9841345c36dcd89a7f5e807c0fcb641836597f7
|
Go
|
dachelie/fhir
|
/models/fhirdatetime.go
|
UTF-8
| 1,744
| 3.296875
| 3
|
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package models
import (
"fmt"
"encoding/json"
"time"
)
type Precision string
const (
Date = "date"
YearMonth = "year-month"
Year = "year"
Timestamp = "timestamp"
Time = "time"
)
type FHIRDateTime struct {
Time time.Time
Precision Precision
}
func (f *FHIRDateTime) UnmarshalJSON(data []byte) (err error) {
strData := string(data)
if len(data) <= 12 {
f.Precision = Precision("date")
f.Time, err = time.ParseInLocation("\"2006-01-02\"", strData, time.Local)
if err != nil {
f.Precision = Precision("year-month")
f.Time, err = time.ParseInLocation("\"2006-01\"", strData, time.Local)
}
if err != nil {
f.Precision = Precision("year")
f.Time, err = time.ParseInLocation("\"2006\"", strData, time.Local)
}
if err != nil {
// TODO: should move time into a separate type
f.Precision = Precision("time")
f.Time, err = time.ParseInLocation("\"15:04:05\"", strData, time.Local)
}
if err != nil {
err = fmt.Errorf("unable to parse DateTime: %s", strData)
f.Precision = ""
}
} else {
f.Precision = Precision("timestamp")
f.Time = time.Time{}
err = f.Time.UnmarshalJSON(data)
}
return err
}
func (f FHIRDateTime) MarshalJSON() ([]byte, error) {
if f.Precision == Timestamp {
return json.Marshal(f.Time.Format(time.RFC3339))
} else if f.Precision == YearMonth {
return json.Marshal(f.Time.Format("2006-01"))
} else if f.Precision == Year {
return json.Marshal(f.Time.Format("2006"))
} else if f.Precision == Time {
return json.Marshal(f.Time.Format("15:04:05"))
} else if f.Precision == Date {
return json.Marshal(f.Time.Format("2006-01-02"))
} else {
return nil, fmt.Errorf("FHIRDateTime.MarshalJSON: unrecognised precision: %s", f.Precision)
}
}
| true
|
ea3ec2f0a4102069206d0d6062a61f8d118b3b1a
|
Go
|
ArnaudCalmettes/go-chip16
|
/chip16/cpu/ops_unary.go
|
UTF-8
| 1,178
| 2.65625
| 3
|
[] |
no_license
|
[] |
no_license
|
package cpu
import "github.com/ArnaudCalmettes/go-chip16/chip16/vm"
// Set Rx to ^HHLL
func notiRxHHLL(v *vm.State, o vm.Opcode) error {
res := ^int16(o.HHLL())
v.Flags.SetZN(res)
v.Regs[o.X()] = res
return nil
}
// Set Rx to ^Rx
func notRx(v *vm.State, o vm.Opcode) error {
x := o.X()
res := ^v.Regs[x]
v.Flags.SetZN(res)
v.Regs[x] = res
return nil
}
// Set Rx to ^Ry
func notRxRy(v *vm.State, o vm.Opcode) error {
res := ^v.Regs[o.Y()]
v.Flags.SetZN(res)
v.Regs[o.X()] = res
return nil
}
// Set Rx to -HHLL
func negiRxHHLL(v *vm.State, o vm.Opcode) error {
res := -int16(o.HHLL())
v.Flags.SetZN(res)
v.Regs[o.X()] = res
return nil
}
// Set Rx to -Rx
func negRx(v *vm.State, o vm.Opcode) error {
x := o.X()
res := -v.Regs[x]
v.Flags.SetZN(res)
v.Regs[x] = res
return nil
}
// Set Rx to -Ry
func negRxRy(v *vm.State, o vm.Opcode) error {
res := -v.Regs[o.Y()]
v.Flags.SetZN(res)
v.Regs[o.X()] = res
return nil
}
func init() {
setOp(0xE0, "NOTI RX, HHLL", notiRxHHLL)
setOp(0xE1, "NOT Rx", notRx)
setOp(0xE2, "NOT Rx, Ry", notRxRy)
setOp(0xE3, "NEGI Rx, HHLL", negiRxHHLL)
setOp(0xE4, "NEG Rx", negRx)
setOp(0xE5, "NEG Rx, Ry", negRxRy)
}
| true
|
7a1e243ce31870e5871bba2f1fabba4826b06552
|
Go
|
fossabot/sectionctl
|
/commands/apps.go
|
UTF-8
| 11,323
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package commands
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"os"
"os/exec"
"strconv"
"strings"
"time"
"github.com/olekukonko/tablewriter"
"github.com/section/sectionctl/api"
)
// AppsCmd manages apps on Section
type AppsCmd struct {
List AppsListCmd `cmd help:"List apps on Section." default:"1"`
Info AppsInfoCmd `cmd help:"Show detailed app information on Section."`
Create AppsCreateCmd `cmd help:"Create new app on Section."`
Delete AppsDeleteCmd `cmd help:"Delete an existing app on Section."`
Init AppsInitCmd `cmd help:"Initialize your project for deployment."`
Stacks AppsStacksCmd `cmd help:"See the available stacks to create new apps with."`
}
// AppsListCmd handles listing apps running on Section
type AppsListCmd struct {
AccountID int `short:"a" help:"Account ID to find apps under"`
}
// NewTable returns a table with sectionctl standard formatting
func NewTable(out io.Writer) (t *tablewriter.Table) {
t = tablewriter.NewWriter(out)
t.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false})
t.SetCenterSeparator("|")
t.SetAlignment(tablewriter.ALIGN_LEFT)
return t
}
// Run executes the command
func (c *AppsListCmd) Run() (err error) {
var aids []int
if c.AccountID == 0 {
s := NewSpinner("Looking up accounts")
s.Start()
as, err := api.Accounts()
if err != nil {
return fmt.Errorf("unable to look up accounts: %w", err)
}
for _, a := range as {
aids = append(aids, a.ID)
}
s.Stop()
} else {
aids = append(aids, c.AccountID)
}
s := NewSpinner("Looking up apps")
s.Start()
apps := make(map[int][]api.App)
for _, id := range aids {
as, err := api.Applications(id)
if err != nil {
return fmt.Errorf("unable to look up applications: %w", err)
}
apps[id] = as
}
s.Stop()
table := NewTable(os.Stdout)
table.SetHeader([]string{"Account ID", "App ID", "App Name"})
for id, as := range apps {
for _, a := range as {
r := []string{strconv.Itoa(id), strconv.Itoa(a.ID), a.ApplicationName}
table.Append(r)
}
}
table.Render()
return err
}
// AppsInfoCmd shows detailed information on an app running on Section
type AppsInfoCmd struct {
AccountID int `required short:"a"`
AppID int `required short:"i"`
}
// Run executes the command
func (c *AppsInfoCmd) Run() (err error) {
s := NewSpinner("Looking up app info")
s.Start()
app, err := api.Application(c.AccountID, c.AppID)
s.Stop()
if err != nil {
return err
}
fmt.Printf("🌎🌏🌍\n")
fmt.Printf("App Name: %s\n", app.ApplicationName)
fmt.Printf("App ID: %d\n", app.ID)
fmt.Printf("Environment count: %d\n", len(app.Environments))
for i, env := range app.Environments {
fmt.Printf("\n-----------------\n\n")
fmt.Printf("Environment #%d: %s (ID:%d)\n\n", i+1, env.EnvironmentName, env.ID)
fmt.Printf("💬 Domains (%d total)\n", len(env.Domains))
for _, dom := range env.Domains {
fmt.Println()
table := NewTable(os.Stdout)
table.SetHeader([]string{"Attribute", "Value"})
table.SetAutoMergeCells(true)
r := [][]string{
[]string{"Domain name", dom.Name},
[]string{"Zone name", dom.ZoneName},
[]string{"CNAME", dom.CNAME},
[]string{"Mode", dom.Mode},
}
table.AppendBulk(r)
table.Render()
}
fmt.Println()
mod := "modules"
if len(env.Stack) == 1 {
mod = "module"
}
fmt.Printf("🥞 Stack (%d %s total)\n", len(env.Stack), mod)
fmt.Println()
table := NewTable(os.Stdout)
table.SetHeader([]string{"Name", "Image"})
table.SetAutoMergeCells(true)
for _, p := range env.Stack {
r := []string{p.Name, p.Image}
table.Append(r)
}
table.Render()
}
fmt.Println()
return err
}
// AppsCreateCmd handles creating apps on Section
type AppsCreateCmd struct {
AccountID int `required short:"a" help:"ID of account to create the app under"`
Hostname string `required short:"d" help:"FQDN the app can be accessed at"`
Origin string `required short:"o" help:"URL to fetch the origin"`
StackName string `required short:"s" help:"Name of stack to deploy"`
}
// Run executes the command
func (c *AppsCreateCmd) Run() (err error) {
s := NewSpinner(fmt.Sprintf("Creating new app %s", c.Hostname))
s.Start()
api.Timeout = 120 * time.Second // this specific request can take a long time
r, err := api.ApplicationCreate(c.AccountID, c.Hostname, c.Origin, c.StackName)
s.Stop()
if err != nil {
if err == api.ErrStatusForbidden {
stacks, herr := api.Stacks()
if herr != nil {
return fmt.Errorf("unable to query stacks: %w", herr)
}
for _, s := range stacks {
if s.Name == c.StackName {
return err
}
}
return fmt.Errorf("bad request: unable to find stack %s", c.StackName)
}
return err
}
fmt.Printf("\nSuccess: created app '%s' with id '%d'\n", r.ApplicationName, r.ID)
return err
}
// AppsDeleteCmd handles deleting apps on Section
type AppsDeleteCmd struct {
AccountID int `required short:"a" help:"ID of account the app belongs to"`
AppID int `required short:"i" help:"ID of the app to delete"`
}
// Run executes the command
func (c *AppsDeleteCmd) Run() (err error) {
s := NewSpinner(fmt.Sprintf("Deleting app with id '%d'", c.AppID))
s.Start()
api.Timeout = 120 * time.Second // this specific request can take a long time
_, err = api.ApplicationDelete(c.AccountID, c.AppID)
s.Stop()
if err != nil {
return err
}
fmt.Printf("\nSuccess: deleted app with id '%d'\n", c.AppID)
return err
}
// AppsInitCmd creates and validates server.conf and package.json to prepare an app for deployment
type AppsInitCmd struct {
StackName string `optional default:"nodejs-basic" short:"s" help:"Name of stack to deploy. Default is nodejs-basic"`
Force bool `optional short:"f" help:"Resets deployment specific files to their default configuration"`
}
func (c *AppsInitCmd) buildServerConf() []byte {
return []byte(
`location / {
proxy_set_header X-Forwarded-For $http_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
proxy_set_header Host $host;
include /etc/nginx/section.module/node.conf;
}
location ~ "/next-proxy-hop/" {
proxy_set_header X-Forwarded-For $http_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
proxy_set_header Host $host;
proxy_pass http://next-hop;
}`)
}
// Run executes the command
func (c *AppsInitCmd) Run() (err error) {
var stdout bytes.Buffer
var stderr bytes.Buffer
switch c.StackName {
case "nodejs-basic":
err := c.InitializeNodeBasicApp(stdout, stderr)
if err != nil {
return fmt.Errorf("[ERROR]: init completed with error %x", err)
}
default:
log.Printf("[ERROR]: Stack name %s does not have an initialization defined\n", c.StackName)
}
return err
}
// Create package.json
func (c *AppsInitCmd) CreatePkgJSON(stdout, stderr bytes.Buffer) (err error) {
cmd := exec.Command("npm", "init", "-y")
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err = cmd.Run()
return err
}
// InitializeNodeBasicApp initializes a basic node app.
func (c *AppsInitCmd) InitializeNodeBasicApp(stdout, stderr bytes.Buffer) (err error) {
if c.Force {
log.Println("[INFO] Removing old versions of server.conf and package.json")
err1 := os.Remove("package.json")
err2 := os.Remove("server.conf")
if err1 != nil || err2 != nil {
log.Println("[ERROR] unable to remove files, perhaps they do not exist?")
} else {
log.Println("[DEBUG] Files successfully removed")
}
}
log.Println("[DEBUG] Checking to see if server.conf exists")
checkServConf, err := os.Open("server.conf")
if err != nil {
log.Println("[WARN] server.conf does not exist. Creating server.conf")
f, err := os.Create("server.conf")
if err != nil {
return fmt.Errorf("error in creating a file: server.conf %w", err)
}
b := c.buildServerConf()
f.Write(b)
defer f.Close()
} else {
log.Println("[INFO] Validating server.conf")
fileinfo, err := checkServConf.Stat()
if err != nil {
return fmt.Errorf("error in finding stat of server.conf %w", err)
}
buf := make([]byte, fileinfo.Size())
_, err = checkServConf.Read(buf)
if err != nil {
return fmt.Errorf("error in size stat of server.conf %w", err)
}
fStr := string(buf)
if !strings.Contains(fStr, "location / {") {
log.Println("[WARN] default location unspecified. Edit or delete server.conf and rerun this command")
}
}
defer checkServConf.Close()
log.Println("[DEBUG] Checking to see if package.json exists")
checkPkgJSON, err := os.Open("package.json")
if err != nil {
log.Println("[WARN] package.json does not exist. Creating package.json")
err := c.CreatePkgJSON(stdout, stderr)
if err != nil {
return fmt.Errorf("there was an error creating package.json. Is node installed? %w", err)
}
log.Println("[INFO] package.json created")
}
defer checkPkgJSON.Close()
validPkgJSON, err := os.OpenFile("package.json", os.O_RDWR, 0777)
if err != nil {
return fmt.Errorf("failed to open package.json %w", err)
}
defer validPkgJSON.Close()
log.Println("[INFO] Validating package.json")
buf, err := os.ReadFile("package.json")
if err != nil {
return fmt.Errorf("failed to read package.json %w", err)
}
fStr := string(buf)
if len(fStr) == 0 {
err := os.Remove("package.json")
if err != nil {
log.Println("[ERROR] unable to remove empty package.json")
}
log.Println("[WARN] package.json is empty. Creating package.json")
err = c.CreatePkgJSON(stdout, stderr)
if err != nil {
return fmt.Errorf("there was an error creating package.json. Is node installed? %w", err)
}
log.Println("[INFO] package.json created from empty file")
buf, err = os.ReadFile("package.json")
if err != nil {
return fmt.Errorf("failed to read package.json %w", err)
}
fStr = string(buf)
}
jsonMap := make(map[string]interface{})
err = json.Unmarshal(buf, &jsonMap)
if err != nil {
return fmt.Errorf("package.json is not valid JSON %w", err)
}
lv := jsonMap["scripts"]
jsonToStrMap, ok := lv.(map[string]interface{})
if !ok {
return fmt.Errorf("json unable to be read as map[string]interface %w", err)
}
_, ok = jsonToStrMap["start"]
if !ok {
jsonToStrMap["start"] = "node YOUR_SERVER_HERE.js"
jsonMap["scripts"] = jsonToStrMap
err = os.Truncate("package.json", 0)
if err != nil {
return fmt.Errorf("failed to empty package.json %w", err)
}
set, err := json.MarshalIndent(jsonMap, "", " ")
if err != nil {
log.Println("[ERROR] unable to add start script placeholder")
}
_, err = validPkgJSON.Write(set)
if err != nil {
log.Println("[ERROR] unable to add start script placeholder")
}
}
if strings.Contains(fStr, `YOUR_SERVER_HERE.js`) {
log.Println("[ERROR] start script is required. Please edit the placeholder in package.json")
}
return err
}
// AppsStacksCmd lists available stacks to create new apps with
type AppsStacksCmd struct{}
// Run executes the command
func (c *AppsStacksCmd) Run() (err error) {
s := NewSpinner("Looking up stacks")
s.Start()
k, err := api.Stacks()
s.Stop()
if err != nil {
return fmt.Errorf("unable to look up stacks: %w", err)
}
table := NewTable(os.Stdout)
table.SetHeader([]string{"Name", "Label", "Description", "Type"})
for _, s := range k {
r := []string{s.Name, s.Label, s.Description, s.Type}
table.Append(r)
}
table.Render()
return err
}
| true
|
cc8db2a2b829330049606e173d04c848040d814a
|
Go
|
bcl/letterbox
|
/main_test.go
|
UTF-8
| 3,103
| 3.296875
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
[
"BSD-3-Clause"
] |
permissive
|
package main
import (
"bytes"
"fmt"
"io"
"log"
"os"
"strings"
"sync"
"testing"
)
// Borrowed from - https://medium.com/@hau12a1/golang-capturing-log-println-and-fmt-println-output-770209c791b4
// NOTE: NOT threadsafe due to swapping global os.Stdout/Stderr values
func captureOutput(f func(), captureStderr bool) string {
reader, writer, err := os.Pipe()
if err != nil {
panic(err)
}
// Save the current stdout and stderr, restore them on return
stdout := os.Stdout
stderr := os.Stderr
defer func() {
os.Stdout = stdout
os.Stderr = stderr
log.SetOutput(os.Stderr)
}()
// Capture the stdout and optionally stderr
os.Stdout = writer
if captureStderr {
os.Stderr = writer
}
// Switch the logger to use the writer
log.SetOutput(writer)
out := make(chan string)
wg := new(sync.WaitGroup)
wg.Add(1)
go func() {
var buf bytes.Buffer
wg.Done()
if _, err := io.Copy(&buf, reader); err != nil {
panic(err)
}
out <- buf.String()
}()
wg.Wait()
f()
writer.Close()
return <-out
}
func TestCaptureOutput(t *testing.T) {
// Capture just stdout
out := captureOutput(func() {
fmt.Println("capture stdout")
os.Stderr.WriteString("capture stderr\n")
}, false)
if strings.Contains(out, "capture stderr") {
t.Fatal("Should not contain stderr")
}
if !strings.Contains(out, "capture stdout") {
t.Fatal("Missing stdout only")
}
// Capture both stdout and stderr
out = captureOutput(func() {
fmt.Println("capture stdout")
os.Stderr.WriteString("capture stderr\n")
}, true)
if !strings.Contains(out, "capture stderr") {
t.Fatal("Missing stderr with stdout")
}
if !strings.Contains(out, "capture stdout") {
t.Fatal("Missing stdout with stderr")
}
}
func TestLogDebug(t *testing.T) {
// test with default config, no output
out := captureOutput(func() {
logDebugf("logging debug info")
}, false)
if strings.Contains(out, "logging debug info") {
t.Fatal("unexpected debug logging")
}
// set global debug to true
cmdline.Debug = true
out = captureOutput(func() {
logDebugf("logging debug info")
}, false)
cmdline.Debug = false
if !strings.Contains(out, "logging debug info") {
t.Fatal("Missing debug string")
}
}
func TestReadConfig(t *testing.T) {
// Empty config
r := bytes.NewReader([]byte(""))
cfg, err := readConfig(r)
if err != nil {
t.Fatalf("Error reading empty config: %s", err)
}
// Should be empty
if len(cfg.Hosts) > 0 || len(cfg.Emails) > 0 {
t.Fatalf("Config not empty: %#v", cfg)
}
// Config with hosts and emails
r = bytes.NewReader([]byte(`
hosts = ["192.168.101.0/24", "127.0.0.1"]
emails = ["[email protected]", "[email protected]"]`))
cfg, err = readConfig(r)
if err != nil {
t.Fatalf("Error reading full config: %s", err)
}
if len(cfg.Hosts) != 2 || len(cfg.Emails) != 2 {
t.Fatalf("Wrong number of values in config: %#v", cfg)
}
if cfg.Hosts[0] != "192.168.101.0/24" ||
cfg.Hosts[1] != "127.0.0.1" {
t.Fatalf("Hosts list is incorrect: %#v", cfg.Hosts)
}
if cfg.Emails[0] != "[email protected]" ||
cfg.Emails[1] != "[email protected]" {
t.Fatalf("Emails list is incorrect: %#v", cfg.Emails)
}
}
| true
|
2a9216296e29de19e87125f6efd7589e33319ad0
|
Go
|
egonelbre/adventofcode
|
/2019/day13/main.go
|
UTF-8
| 1,870
| 2.875
| 3
|
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"os"
"time"
"github.com/egonelbre/adventofcode/2019/day13/g"
"github.com/egonelbre/adventofcode/2019/day13/intcode"
)
const (
Empty = g.Color(0)
Wall = g.Color(1)
Block = g.Color(2)
Paddle = g.Color(3)
Ball = g.Color(4)
)
var colors = map[g.Color]rune{
Empty: ' ',
Wall: '█',
Block: '#',
Paddle: '-',
Ball: 'o',
}
func main() {
CountBlocks()
PlayGame()
}
func CountBlocks() {
var out int64
var at g.Vector
m := g.NewSparseImage(Empty)
cpu := &intcode.Computer{
Code: ArcadeCabinet.Clone(),
Output: func(v int64) {
switch out {
case 0:
at.X = v
case 1:
at.Y = v
case 2:
m.Set(at, g.Color(v))
}
out = (out + 1) % 3
},
}
err := cpu.Run()
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
fmt.Println("blocks", m.Count(Block))
m.Image().Print(colors)
}
func PlayGame() {
SegmentDisplay := g.Vector{-1, 0}
var out int64
var at g.Vector
var score int64
display := g.NewSparseImage(Empty)
cpu := &intcode.Computer{
Code: ArcadeCabinet.Clone(),
Input: func() int64 {
ball, okb := display.Find(Ball)
paddle, okp := display.Find(Paddle)
if !okb || !okp {
fmt.Fprintln(os.Stderr, "unable to find ball/paddle")
display.Image().Print(colors)
return 0
}
if false {
print("\033[H\033[2J")
fmt.Println("Score", score)
display.Image().Print(colors)
time.Sleep(30 * time.Millisecond)
}
return ball.Sub(paddle).Sign().X
},
Output: func(v int64) {
switch out {
case 0:
at.X = v
case 1:
at.Y = v
case 2:
if at == SegmentDisplay {
score = v
} else {
display.Set(at, g.Color(v))
}
}
out = (out + 1) % 3
},
}
cpu.Code[0] = 2
err := cpu.Run()
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
fmt.Println("score", score)
display.Image().Print(colors)
}
| true
|
18fe4e741cebf2156bce4c88aba3818f6775bec3
|
Go
|
angeliski/git-fork
|
/cmd/root.go
|
UTF-8
| 834
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package cmd
import (
"fmt"
"github.com/spf13/cobra"
"os"
)
var rootCmd = &cobra.Command{
Use: "git-fork",
Short: "git-fork helps you to maintain you repository updated",
}
var repositoryPath string
var verbose bool
func init() {
//cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&repositoryPath, "path", "", "Target directory to run git operations")
rootCmd.PersistentFlags().BoolVar(&verbose, "verbose", false, "Run operations with verbose mode")
}
// getRootCmd returns the rootCmd
func getRootCmd() *cobra.Command {
return rootCmd
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
| true
|
b487ae413c05265b5fa1880e92ea08edf07e0c1a
|
Go
|
hcxiong/pholcus
|
/reporter/log.go
|
UTF-8
| 860
| 3.296875
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
package reporter
import (
"fmt"
"os"
"time"
)
// 模仿标准包log打印报告
func Print(v ...interface{}) {
fmt.Print(time.Now().Format("2006/01/02 15:04:05") + " " + fmt.Sprint(v...))
}
func Printf(format string, v ...interface{}) {
fmt.Printf(time.Now().Format("2006/01/02 15:04:05")+" "+format+"\n", v...)
}
func Println(v ...interface{}) {
fmt.Println(time.Now().Format("2006/01/02 15:04:05") + " " + fmt.Sprint(v...))
}
// Fatal is equivalent to l.Print() followed by a call to os.Exit(1).
func Fatal(v ...interface{}) {
Print(v...)
os.Exit(1)
}
// Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1).
func Fatalf(format string, v ...interface{}) {
Printf(format, v...)
os.Exit(1)
}
// Fatalln is equivalent to l.Println() followed by a call to os.Exit(1).
func Fatalln(v ...interface{}) {
Println(v...)
os.Exit(1)
}
| true
|
687af6cdca5cb6cfb6f86ad824d108fae7d21cd0
|
Go
|
nickmachnik/google-kickstart
|
/rounds/2021_A/rabbit_house/main.go
|
UTF-8
| 5,682
| 3.1875
| 3
|
[] |
no_license
|
[] |
no_license
|
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"strconv"
"strings"
)
type testCase struct {
rows int
cols int
grid [][]int
}
type testCaseOrErr struct {
testCase
err error
}
func main() {
reader := bufio.NewReader(os.Stdin)
testCases := loadTestCasesToChannel(reader)
var testIx int
for test := range testCases {
testIx++
if test.err != nil {
log.Fatal(test.err)
}
numAdditions := makeRabbitHouseSafe(&test.testCase)
fmt.Printf("Case #%d: %d\n", testIx, numAdditions)
}
}
func makeRabbitHouseSafe(house *testCase) (totalHeightIncrease int) {
buckets := newHeightBuckets(&house.grid)
for {
if buckets.maxHeight == 0 {
break
}
totalHeightIncrease += secureNextLocation(buckets, house)
}
return
}
func secureNextLocation(buckets *heightBuckets, house *testCase) (addedHeight int) {
loc := buckets.getLocationAtMaxHeight()
locHeight := getLocationHeight(loc, house)
defer buckets.removeLocation(locHeight, loc)
for _, neighbor := range getNeighborLocations(loc, house) {
neighborHeight := getLocationHeight(neighbor, house)
heightDiff := locHeight - neighborHeight
if heightDiff > 1 {
addedHeight += heightDiff - 1
buckets.insertLocation(locHeight-1, neighbor)
setLocationHeight(locHeight-1, neighbor, house)
buckets.removeLocation(neighborHeight, neighbor)
}
}
return
}
func setLocationHeight(height int, loc location, house *testCase) {
house.grid[loc.row][loc.col] = height
}
func getLocationHeight(loc location, house *testCase) (height int) {
return house.grid[loc.row][loc.col]
}
func getNeighborLocations(loc location, house *testCase) (neighbors []location) {
if loc.row > 0 {
neighbors = append(neighbors, location{loc.row - 1, loc.col})
}
if loc.col < house.cols-1 {
neighbors = append(neighbors, location{loc.row, loc.col + 1})
}
if loc.row < house.rows-1 {
neighbors = append(neighbors, location{loc.row + 1, loc.col})
}
if loc.col > 0 {
neighbors = append(neighbors, location{loc.row, loc.col - 1})
}
return
}
type location struct {
row, col int
}
type heightBuckets struct {
buckets map[int]map[location]struct{}
maxHeight int
}
func (b *heightBuckets) getLocationAtMaxHeight() location {
loc, err := b.getLocationAtHeight(b.maxHeight)
if err != nil {
log.Fatal(err)
}
return loc
}
func (b *heightBuckets) getLocationAtHeight(height int) (loc location, err error) {
for loc = range b.buckets[height] {
return loc, err
}
return loc, fmt.Errorf("no location found at height: %d", height)
}
func (b *heightBuckets) insertLocation(height int, loc location) {
if _, ok := b.buckets[height]; !ok {
b.buckets[height] = map[location]struct{}{}
}
b.buckets[height][loc] = struct{}{}
if height > b.maxHeight {
b.maxHeight = height
}
}
func (b *heightBuckets) removeLocation(height int, loc location) {
delete(b.buckets[height], loc)
if len(b.buckets[height]) == 0 {
delete(b.buckets, height)
}
if height == b.maxHeight {
b.decreaseMaxHeight()
}
}
func (b *heightBuckets) decreaseMaxHeight() {
if len(b.buckets) == 0 {
b.maxHeight = 0
return
}
for {
if _, ok := b.buckets[b.maxHeight]; !ok {
b.maxHeight--
} else {
break
}
}
}
func newHeightBuckets(grid *[][]int) *heightBuckets {
ret := heightBuckets{
buckets: make(map[int]map[location]struct{}),
maxHeight: 0,
}
for rowIx, row := range *grid {
for colIx, height := range row {
ret.insertLocation(height, location{rowIx, colIx})
}
}
return &ret
}
// -------- Input reading -------- //
func newTestCase(rows, cols int, heights [][]int) testCase {
return testCase{
rows,
cols,
heights,
}
}
func newTestCaseOrErr(rows, cols int, grid [][]int, err error) testCaseOrErr {
return testCaseOrErr{
newTestCase(rows, cols, grid),
err,
}
}
func parseIntFields(line string) (ints []int, err error) {
for _, field := range strings.Fields(line) {
convField, err := strconv.Atoi(field)
if err != nil {
return []int{}, err
}
ints = append(ints, convField)
}
return
}
func parseIntsFromNextLine(reader *bufio.Reader) (ints []int, err error) {
line, err := reader.ReadString('\n')
if err != nil && err != io.EOF {
return
}
return parseIntFields(line)
}
func parseRowAndColNum(reader *bufio.Reader) (row, col int, err error) {
intFields, err := parseIntsFromNextLine(reader)
if err != nil {
return
}
if len(intFields) != 2 {
err = fmt.Errorf("number of int fields in first line of test case not equal to 2")
return
}
row = intFields[0]
col = intFields[1]
return
}
func parseNumTestCases(reader *bufio.Reader) (numTestCases int, err error) {
firstLineInts, err := parseIntsFromNextLine(reader)
if err != nil {
return
}
if len(firstLineInts) != 1 {
err = fmt.Errorf("unexpected number of ints in test case number definition")
return
}
numTestCases = firstLineInts[0]
return
}
func parseGrid(rows int, cols int, reader *bufio.Reader) ([][]int, error) {
grid := make([][]int, rows)
for i := 0; i < rows; i++ {
row, err := parseIntsFromNextLine(reader)
if err != nil {
return grid, err
}
grid[i] = row
}
return grid, nil
}
func loadTestCasesToChannel(reader *bufio.Reader) <-chan testCaseOrErr {
out := make(chan testCaseOrErr)
go func() {
defer close(out)
numberOfTestCases, err := parseNumTestCases(reader)
if err != nil {
out <- testCaseOrErr{err: err}
return
}
for i := 0; i < numberOfTestCases; i++ {
rows, cols, err := parseRowAndColNum(reader)
if err != nil {
out <- testCaseOrErr{err: err}
return
}
grid, err := parseGrid(rows, cols, reader)
out <- newTestCaseOrErr(rows, cols, grid, err)
}
}()
return out
}
| true
|
5b60ca5800ac94cdcf292db47a598131e25a10cf
|
Go
|
rranjik/ideal-octo-barnacle
|
/851-LoudAndRich.go
|
UTF-8
| 734
| 2.515625
| 3
|
[] |
no_license
|
[] |
no_license
|
func dfs(p int, adjl map[int][]int) int {
if _,ok := c[p]; ok {
return c[p]
}
res := p
if _,ok := adjl[p]; ok {
for _,v := range adjl[p]{
if k[res] > k[v] {
res = v
}
a := dfs(v, adjl)
if k[res] > k[a] {
res = a
}
}
}
c[p] = res
return res
}
var n int
var k []int
var c map[int]int
func loudAndRich(r [][]int, q []int) []int {
c = make(map[int]int)
k = q
adjl := make (map[int][]int)
n = len(q)
for _,v :=range r{
adjl[v[1]] = append(adjl[v[1]], v[0])
}
res := []int{}
for i := range q{
res = append(res, dfs(i, adjl))
}
return res
}
| true
|
4e703afc0adcb221a6a94b9277f0cb071760b850
|
Go
|
mikoim/isucon6-final
|
/bench/svg/parse.go
|
UTF-8
| 1,193
| 3.21875
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package svg
import (
"encoding/xml"
"errors"
"strconv"
"strings"
)
type Point struct {
X float32
Y float32
}
type PolyLine struct {
ID string `xml:"id,attr"`
Stroke string `xml:"stroke,attr"`
StrokeWidth int `xml:"stroke-width,attr"`
PointsRaw string `xml:"points,attr"`
Points []Point
}
type SVG struct {
Width int `xml:"width,attr"`
Height int `xml:"height,attr"`
Style string `xml:"style,attr"`
ViewBox string `xml:"viewBox,attr"`
PolyLines []PolyLine `xml:"polyline"`
}
func Parse(data []byte) (*SVG, error) {
v := &SVG{}
err := xml.Unmarshal(data, &v)
if err != nil {
return nil, err
}
for i, polyLine := range v.PolyLines {
points := make([]Point, 0)
for _, s := range strings.Split(polyLine.PointsRaw, " ") {
ps := strings.Split(s, ",")
if len(ps) < 2 {
return nil, errors.New("svgの形式が不正です")
}
x, err := strconv.ParseFloat(ps[0], 32)
if err != nil {
return nil, err
}
y, err := strconv.ParseFloat(ps[1], 32)
if err != nil {
return nil, err
}
points = append(points, Point{float32(x), float32(y)})
}
v.PolyLines[i].Points = points
}
return v, nil
}
| true
|
29390bac80b55b058fa458124d5ec365009121c2
|
Go
|
fm2901/stats2
|
/pkg/stats/stats.go
|
UTF-8
| 1,473
| 2.796875
| 3
|
[] |
no_license
|
[] |
no_license
|
package stats
import (
"github.com/fm2901/bank/v2/pkg/types"
)
func Avg(payments []types.Payment) types.Money {
var allSum types.Money
var allCount types.Money
if len(payments) < 1 {
return 0
}
for _, payment := range payments {
if payment.Status == types.StatusFail {
continue
}
allSum += payment.Amount
allCount += 1
}
return allSum / allCount
}
func TotalInCategory(payments []types.Payment, category types.Category) types.Money {
var sumInCategory types.Money
if len(payments) < 1 {
return 0
}
for _, payment := range payments {
if payment.Category != category || payment.Status == types.StatusFail {
continue
}
sumInCategory += payment.Amount
}
return sumInCategory
}
func CategoriesAvg(payments []types.Payment) map[types.Category]types.Money {
categories := map[types.Category]types.Money{}
counter := map[types.Category]int{}
for _, payment := range payments {
if payment.Amount > 0 {
categories[payment.Category] += payment.Amount
counter[payment.Category] += 1
}
}
for cat := range categories {
categories[cat] = categories[cat] / types.Money(counter[cat])
}
return categories
}
func PeriodsDynamic(
first map[types.Category]types.Money,
second map[types.Category]types.Money,
) map[types.Category]types.Money {
result := map[types.Category]types.Money{}
for key := range second {
result[key] += second[key]
}
for key := range first {
result[key] -= first[key]
}
return result
}
| true
|
adc8005b43322a78603b0120a33c563acc38b70a
|
Go
|
AlbertTian1987/GoStudy
|
/xml/xml.go
|
UTF-8
| 1,243
| 2.890625
| 3
|
[] |
no_license
|
[] |
no_license
|
package xml
import (
"encoding/xml"
"fmt"
"io/ioutil"
"os"
)
type Recurlyservers struct {
XMLName xml.Name `xml:"servers"`
Version string `xml:"version,attr"`
Svs []server `xml:"server"`
Description string `xml:",innerxml"`
}
type server struct {
XMLName xml.Name `xml:"server"`
ServerName serverName `xml:"ServerName"`
ServerIP string `xml:"serverIP"`
}
type serverName struct {
Key string `xml:"opt,attr"`
Value string `xml:",chardata"`
}
func Decode_Servers() *Recurlyservers {
file, err := os.Open("servers.xml")
checkError(err)
defer file.Close()
data, err := ioutil.ReadAll(file)
checkError(err)
v := Recurlyservers{}
err = xml.Unmarshal(data, &v)
checkError(err)
return &v
}
func checkError(err error) {
if err != nil {
fmt.Printf("error :v%", err)
return
}
}
func Encode_Servers() {
v := new(Recurlyservers)
v.Version = "1"
v.Svs = append(v.Svs, server{ServerName: serverName{"经济首都", "上海"}, ServerIP: "127.0.0.2"})
v.Svs = append(v.Svs, server{ServerName: serverName{"政治首都", "北京"}, ServerIP: "127.0.0.1"})
output, err := xml.MarshalIndent(&v, " ", " ")
checkError(err)
os.Stdout.Write([]byte(xml.Header))
os.Stdout.Write(output)
}
| true
|
7b93fd0f6e4d7ca611273a30be86e32a8c2f62f6
|
Go
|
DawnBreather/cicd-tools
|
/api_server/api_server.go
|
UTF-8
| 3,578
| 2.703125
| 3
|
[] |
no_license
|
[] |
no_license
|
package api_server
import (
"crypto/tls"
"github.com/DawnBreather/go-commons/ssl"
"github.com/gorilla/mux"
"log"
"net/http"
)
// ApiServer has router
type ApiServer struct {
Ssl ssl.Ssl
Router *mux.Router
Config map[string]interface{}
}
func (a *ApiServer) SetSslMetadata(locality, country, organization, province, postalCode, streetAddress string){
a.Ssl.
SetLocality(locality).
SetCountry(country).
SetOrganization(organization).
SetProvince(province).
SetPostalCode(postalCode).
SetStreetAddress(streetAddress)
}
// Initialize initializes the app with predefined configuration
func (a *ApiServer) Initialize(config map[string]interface{}) *ApiServer{
//func (a *ApiServer) Initialize() *ApiServer{
a.Ssl.InitializeCertificateAuthority()
a.Router = mux.NewRouter()
return a
}
//func (a *ApiServer) setRouters() {
// // Routing for handling the projects
// a.Get("/projects", a.handleRequest(handler.GetAllProjects))
// a.Post("/projects", a.handleRequest(handler.CreateProject))
// a.Get("/projects/{title}", a.handleRequest(handler.GetProjects))
// a.Put("/projects/{title}", a.handleRequest(handler.UpdateProject))
// a.Delete("/projects/{title}", a.handleRequest(handler.DeleteProject))
// a.Put("/projects/{title}/archive", a.handleRequest(handler.ArchiveProject))
// a.Delete("/projects/{title}/archive", a.handleRequest(handler.RestoreProject))
//
// // Routing for handling the tasks
// a.Get("/projects/{title}/tasks", a.handleRequest(handler.GetAllTasks))
// a.Post("/projects/{title}/tasks", a.handleRequest(handler.CreateTask))
// a.Get("/projects/{title}/tasks/{id:[0-9]+}", a.handleRequest(handler.GetTask))
// a.Put("/projects/{title}/tasks/{id:[0-9]+}", a.handleRequest(handler.UpdateTask))
// a.Delete("/projects/{title}/tasks/{id:[0-9]+}", a.handleRequest(handler.DeleteTask))
// a.Put("/projects/{title}/tasks/{id:[0-9]+}/complete", a.handleRequest(handler.CompleteTask))
// a.Delete("/projects/{title}/tasks/{id:[0-9]+}/complete", a.handleRequest(handler.UndoTask))
//}
// Get wraps the router for GET method
func (a *ApiServer) Get(path string, f func(w http.ResponseWriter, r *http.Request)) *ApiServer{
a.Router.HandleFunc(path, f).Methods("GET")
return a
}
// Post wraps the router for POST method
func (a *ApiServer) Post(path string, f func(w http.ResponseWriter, r *http.Request)) *ApiServer{
a.Router.HandleFunc(path, f).Methods("POST")
return a
}
// Put wraps the router for PUT method
func (a *ApiServer) Put(path string, f func(w http.ResponseWriter, r *http.Request)) *ApiServer{
a.Router.HandleFunc(path, f).Methods("PUT")
return a
}
// Delete wraps the router for DELETE method
func (a *ApiServer) Delete(path string, f func(w http.ResponseWriter, r *http.Request)) *ApiServer{
a.Router.HandleFunc(path, f).Methods("DELETE")
return a
}
// Run the app on it's router
func (a *ApiServer) Run(host string) {
log.Fatal(http.ListenAndServe(host, a.Router))
}
func (a *ApiServer) RunSslSelfSigned(host string, DNSNames []string) {
_, _, keyPair := a.Ssl.GenerateSignedCertificate(DNSNames)
server := &http.Server{
Addr: host,
Handler: a.Router,
TLSConfig: &tls.Config{
Certificates: []tls.Certificate{keyPair},
},
}
//log.Fatal(http.ListenAndServeTLS(host, "", "", a.Router))
log.Fatal(server.ListenAndServeTLS("", ""))
}
type RequestHandlerFunction func(w http.ResponseWriter, r *http.Request)
func (a *ApiServer) handleRequest(handler RequestHandlerFunction) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
handler(w, r)
}
}
| true
|
40a640ca18dda0091e1468f1171dd07e4e88de02
|
Go
|
kubernetes/kubernetes
|
/staging/src/k8s.io/kubectl/pkg/cmd/diff/diff_test.go
|
UTF-8
| 14,364
| 2.578125
| 3
|
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, 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 diff
import (
"bytes"
"fmt"
"os"
"path"
"path/filepath"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/cli-runtime/pkg/genericiooptions"
"k8s.io/utils/exec"
)
type FakeObject struct {
name string
merged map[string]interface{}
live map[string]interface{}
}
var _ Object = &FakeObject{}
func (f *FakeObject) Name() string {
return f.name
}
func (f *FakeObject) Merged() (runtime.Object, error) {
// Return nil if merged object does not exist
if f.merged == nil {
return nil, nil
}
return &unstructured.Unstructured{Object: f.merged}, nil
}
func (f *FakeObject) Live() runtime.Object {
// Return nil if live object does not exist
if f.live == nil {
return nil
}
return &unstructured.Unstructured{Object: f.live}
}
func TestDiffProgram(t *testing.T) {
externalDiffCommands := [3]string{"diff", "diff -ruN", "diff --report-identical-files"}
t.Setenv("LANG", "C")
for i, c := range externalDiffCommands {
t.Setenv("KUBECTL_EXTERNAL_DIFF", c)
streams, _, stdout, _ := genericiooptions.NewTestIOStreams()
diff := DiffProgram{
IOStreams: streams,
Exec: exec.New(),
}
err := diff.Run("/dev/zero", "/dev/zero")
if err != nil {
t.Fatal(err)
}
// Testing diff --report-identical-files
if i == 2 {
output_msg := "Files /dev/zero and /dev/zero are identical\n"
if output := stdout.String(); output != output_msg {
t.Fatalf(`stdout = %q, expected = %s"`, output, output_msg)
}
}
}
}
func TestPrinter(t *testing.T) {
printer := Printer{}
obj := &unstructured.Unstructured{Object: map[string]interface{}{
"string": "string",
"list": []int{1, 2, 3},
"int": 12,
}}
buf := bytes.Buffer{}
printer.Print(obj, &buf)
want := `int: 12
list:
- 1
- 2
- 3
string: string
`
if buf.String() != want {
t.Errorf("Print() = %q, want %q", buf.String(), want)
}
}
func TestDiffVersion(t *testing.T) {
diff, err := NewDiffVersion("MERGED")
if err != nil {
t.Fatal(err)
}
defer diff.Dir.Delete()
obj := FakeObject{
name: "bla",
live: map[string]interface{}{"live": true},
merged: map[string]interface{}{"merged": true},
}
rObj, err := obj.Merged()
if err != nil {
t.Fatal(err)
}
err = diff.Print(obj.Name(), rObj, Printer{})
if err != nil {
t.Fatal(err)
}
fcontent, err := os.ReadFile(path.Join(diff.Dir.Name, obj.Name()))
if err != nil {
t.Fatal(err)
}
econtent := "merged: true\n"
if string(fcontent) != econtent {
t.Fatalf("File has %q, expected %q", string(fcontent), econtent)
}
}
func TestDirectory(t *testing.T) {
dir, err := CreateDirectory("prefix")
defer dir.Delete()
if err != nil {
t.Fatal(err)
}
_, err = os.Stat(dir.Name)
if err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(filepath.Base(dir.Name), "prefix") {
t.Fatalf(`Directory doesn't start with "prefix": %q`, dir.Name)
}
entries, err := os.ReadDir(dir.Name)
if err != nil {
t.Fatal(err)
}
if len(entries) != 0 {
t.Fatalf("Directory should be empty, has %d elements", len(entries))
}
_, err = dir.NewFile("ONE")
if err != nil {
t.Fatal(err)
}
_, err = dir.NewFile("TWO")
if err != nil {
t.Fatal(err)
}
entries, err = os.ReadDir(dir.Name)
if err != nil {
t.Fatal(err)
}
if len(entries) != 2 {
t.Fatalf("ReadDir should have two elements, has %d elements", len(entries))
}
err = dir.Delete()
if err != nil {
t.Fatal(err)
}
_, err = os.Stat(dir.Name)
if err == nil {
t.Fatal("Directory should be gone, still present.")
}
}
func TestDiffer(t *testing.T) {
diff, err := NewDiffer("LIVE", "MERGED")
if err != nil {
t.Fatal(err)
}
defer diff.TearDown()
obj := FakeObject{
name: "bla",
live: map[string]interface{}{"live": true},
merged: map[string]interface{}{"merged": true},
}
err = diff.Diff(&obj, Printer{}, true)
if err != nil {
t.Fatal(err)
}
fcontent, err := os.ReadFile(path.Join(diff.From.Dir.Name, obj.Name()))
if err != nil {
t.Fatal(err)
}
econtent := "live: true\n"
if string(fcontent) != econtent {
t.Fatalf("File has %q, expected %q", string(fcontent), econtent)
}
fcontent, err = os.ReadFile(path.Join(diff.To.Dir.Name, obj.Name()))
if err != nil {
t.Fatal(err)
}
econtent = "merged: true\n"
if string(fcontent) != econtent {
t.Fatalf("File has %q, expected %q", string(fcontent), econtent)
}
}
func TestShowManagedFields(t *testing.T) {
diff, err := NewDiffer("LIVE", "MERGED")
if err != nil {
t.Fatal(err)
}
defer diff.TearDown()
testCases := []struct {
name string
showManagedFields bool
expectedFromContent string
expectedToContent string
}{
{
name: "without managed fields",
showManagedFields: false,
expectedFromContent: `live: true
metadata:
name: foo
`,
expectedToContent: `merged: true
metadata:
name: foo
`,
},
{
name: "with managed fields",
showManagedFields: true,
expectedFromContent: `live: true
metadata:
managedFields: mf-data
name: foo
`,
expectedToContent: `merged: true
metadata:
managedFields: mf-data
name: foo
`,
},
}
for i, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
obj := FakeObject{
name: fmt.Sprintf("TestCase%d", i),
live: map[string]interface{}{
"live": true,
"metadata": map[string]interface{}{
"managedFields": "mf-data",
"name": "foo",
},
},
merged: map[string]interface{}{
"merged": true,
"metadata": map[string]interface{}{
"managedFields": "mf-data",
"name": "foo",
},
},
}
err = diff.Diff(&obj, Printer{}, tc.showManagedFields)
if err != nil {
t.Fatal(err)
}
actualFromContent, _ := os.ReadFile(path.Join(diff.From.Dir.Name, obj.Name()))
if string(actualFromContent) != tc.expectedFromContent {
t.Fatalf("File has %q, expected %q", string(actualFromContent), tc.expectedFromContent)
}
actualToContent, _ := os.ReadFile(path.Join(diff.To.Dir.Name, obj.Name()))
if string(actualToContent) != tc.expectedToContent {
t.Fatalf("File has %q, expected %q", string(actualToContent), tc.expectedToContent)
}
})
}
}
func TestMasker(t *testing.T) {
type diff struct {
from runtime.Object
to runtime.Object
}
cases := []struct {
name string
input diff
want diff
}{
{
name: "no_changes",
input: diff{
from: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "abc",
"password": "123",
},
},
},
to: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "abc",
"password": "123",
},
},
},
},
want: diff{
from: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "***", // still masked
"password": "***", // still masked
},
},
},
to: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "***", // still masked
"password": "***", // still masked
},
},
},
},
},
{
name: "object_created",
input: diff{
from: nil, // does not exist yet
to: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "abc",
"password": "123",
},
},
},
},
want: diff{
from: nil, // does not exist yet
to: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "***", // no suffix needed
"password": "***", // no suffix needed
},
},
},
},
},
{
name: "object_removed",
input: diff{
from: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "abc",
"password": "123",
},
},
},
to: nil, // removed
},
want: diff{
from: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "***", // no suffix needed
"password": "***", // no suffix needed
},
},
},
to: nil, // removed
},
},
{
name: "data_key_added",
input: diff{
from: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "abc",
},
},
},
to: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "abc",
"password": "123", // added
},
},
},
},
want: diff{
from: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "***",
},
},
},
to: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "***",
"password": "***", // no suffix needed
},
},
},
},
},
{
name: "data_key_changed",
input: diff{
from: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "abc",
"password": "123",
},
},
},
to: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "abc",
"password": "456", // changed
},
},
},
},
want: diff{
from: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "***",
"password": "*** (before)", // added suffix for diff
},
},
},
to: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "***",
"password": "*** (after)", // added suffix for diff
},
},
},
},
},
{
name: "data_key_removed",
input: diff{
from: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "abc",
"password": "123",
},
},
},
to: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "abc",
// "password": "123", // removed
},
},
},
},
want: diff{
from: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "***",
"password": "***", // no suffix needed
},
},
},
to: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "***",
// "password": "***",
},
},
},
},
},
{
name: "empty_secret_from",
input: diff{
from: &unstructured.Unstructured{
Object: map[string]interface{}{}, // no data key
},
to: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "abc",
"password": "123",
},
},
},
},
want: diff{
from: &unstructured.Unstructured{
Object: map[string]interface{}{}, // no data key
},
to: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "***",
"password": "***",
},
},
},
},
},
{
name: "empty_secret_to",
input: diff{
from: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "abc",
"password": "123",
},
},
},
to: &unstructured.Unstructured{
Object: map[string]interface{}{}, // no data key
},
},
want: diff{
from: &unstructured.Unstructured{
Object: map[string]interface{}{
"data": map[string]interface{}{
"username": "***",
"password": "***",
},
},
},
to: &unstructured.Unstructured{
Object: map[string]interface{}{}, // no data key
},
},
},
{
name: "invalid_data_key",
input: diff{
from: &unstructured.Unstructured{
Object: map[string]interface{}{
"some_other_key": map[string]interface{}{ // invalid key
"username": "abc",
"password": "123",
},
},
},
to: &unstructured.Unstructured{
Object: map[string]interface{}{
"some_other_key": map[string]interface{}{ // invalid key
"username": "abc",
"password": "123",
},
},
},
},
want: diff{
from: &unstructured.Unstructured{
Object: map[string]interface{}{
"some_other_key": map[string]interface{}{
"username": "abc", // skipped
"password": "123", // skipped
},
},
},
to: &unstructured.Unstructured{
Object: map[string]interface{}{
"some_other_key": map[string]interface{}{
"username": "abc", // skipped
"password": "123", // skipped
},
},
},
},
},
}
for _, tc := range cases {
tc := tc // capture range variable
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
m, err := NewMasker(tc.input.from, tc.input.to)
if err != nil {
t.Fatal(err)
}
from, to := m.From(), m.To()
if from != nil && tc.want.from != nil {
if diff := cmp.Diff(from, tc.want.from); diff != "" {
t.Errorf("from: (-want +got):\n%s", diff)
}
}
if to != nil && tc.want.to != nil {
if diff := cmp.Diff(to, tc.want.to); diff != "" {
t.Errorf("to: (-want +got):\n%s", diff)
}
}
})
}
}
| true
|
5aa4424f42a45397d10adc081f7ce64faa0cc75c
|
Go
|
RobinChailley/digital-marketplace
|
/src/transactions/internal/infrastructure/accounts/api.go
|
UTF-8
| 2,437
| 2.859375
| 3
|
[] |
no_license
|
[] |
no_license
|
package accounts
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"marketplace/transactions/domain"
"marketplace/transactions/internal/conf"
"net/http"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
)
type API struct {
client *http.Client
address string
apiKey string
}
func NewAPI(config conf.Service) *API {
client := &http.Client{}
return &API{client, config.URL, config.ApiKey}
}
func (a *API) GetUserById(c *gin.Context, userId int64) (domain.Account, error) {
uri := fmt.Sprintf("%s/info/byId/%d", a.address, userId)
request, err := http.NewRequest(http.MethodGet, uri, nil)
if err != nil {
return domain.Account{}, errors.Wrap(err, "Unable to build http request.")
}
request = request.WithContext(c)
request.Header.Set("api-key", a.apiKey)
request.Header.Set("Authorization", c.Request.Header.Get("Authorization"))
resp, err := a.client.Do(request)
if err != nil {
return domain.Account{}, errors.Wrap(err, "Unable to handle the http request.")
}
switch resp.StatusCode {
case http.StatusOK:
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return domain.Account{}, errors.New("Can not read the body.")
}
user := domain.Account{}
err = json.Unmarshal(data, &user)
if err != nil {
return domain.Account{}, errors.Wrap(err, "Can not json.Unmarshal body")
}
return user, nil
default:
return domain.Account{}, errors.New(fmt.Sprintf("Unable to handle the http request. Code : %d", resp.StatusCode))
}
}
func (a *API) UpdateUserBalanceById(c *gin.Context, userId int64, deltaBalance float64) (error) {
uri := fmt.Sprintf("%s/update-balance/byId/%d", a.address, userId)
jsonString := []byte(fmt.Sprintf(`{"balance": %f}`, deltaBalance))
request, err := http.NewRequest(http.MethodPost, uri, bytes.NewBuffer(jsonString))
if err != nil {
return errors.Wrap(err, "Unable to build http request.")
}
request = request.WithContext(c)
request.Header.Set("api-key", a.apiKey)
request.Header.Set("Authorization", c.Request.Header.Get("Authorization"))
resp, err := a.client.Do(request)
if err != nil {
return errors.Wrap(err, "Unable to handle the http request.")
}
switch resp.StatusCode {
case http.StatusOK:
return nil
case http.StatusUnauthorized:
return errors.New("The user balance is too low to make this update.")
default:
return errors.New(fmt.Sprintf("Unable to handle the http request. Code : %d", resp.StatusCode))
}
}
| true
|
b3b861bc391b06e2aa02914210e348e1970b8ab4
|
Go
|
cygnusss/golang
|
/gostuff/channels-routines/redis.go
|
UTF-8
| 801
| 3.171875
| 3
|
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"strconv"
"time"
"github.com/go-redis/redis"
)
// RedisCli is a struct to control redis
type RedisCli struct {
Client *redis.Client
}
func ExampleNewClient() RedisCli {
c := redis.NewClient(&redis.Options{
Addr: ":6379",
Password: "", // no password set
DB: 0, // use default DB
})
pong, err := c.Ping().Result()
fmt.Println(pong, err)
return RedisCli{c}
}
func (r *RedisCli) Hash(key string) string {
h := 0
for i := 0; i < len(key); i++ {
h = 31*h + int(key[i])
}
return strconv.Itoa(h)
}
// Insert inserts data into redis
func (r *RedisCli) Insert(jk string) error {
k := r.Hash(jk)
err := r.Client.Set(k, jk, time.Hour*24).Err()
if err != nil {
return err
}
fmt.Printf("Insertion into redis, KEY: %s", k)
return nil
}
| true
|
e5db39aeac95d5b125030dd1aba549967c65beb0
|
Go
|
00mjk/gpeg
|
/memo/capture.go
|
UTF-8
| 2,217
| 3.390625
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package memo
import (
"bytes"
"fmt"
)
const (
tNode = iota
tDummy
)
type Capture struct {
id int32
typ int32
off int
length int
ment *Entry
children []*Capture
}
func NewCaptureNode(id int, start, length int, children []*Capture) *Capture {
c := &Capture{
id: int32(id),
typ: tNode,
off: start,
length: length,
children: children,
}
return c
}
func NewCaptureDummy(start, length int, children []*Capture) *Capture {
c := &Capture{
id: 0,
typ: tDummy,
off: start,
length: length,
children: children,
}
return c
}
func (c *Capture) ChildIterator(start int) func() *Capture {
i := 0
var subit, ret func() *Capture
ret = func() *Capture {
if i >= len(c.children) {
return nil
}
ch := c.children[i]
if ch.Dummy() && subit == nil {
subit = ch.ChildIterator(ch.off)
}
if subit != nil {
ch = subit()
} else {
i++
}
if ch == nil {
subit = nil
i++
return ret()
}
return ch
}
return ret
}
func (c *Capture) Child(n int) *Capture {
it := c.ChildIterator(0)
i := 0
for ch := it(); ch != nil; ch = it() {
if i == n {
return ch
}
i++
}
return nil
}
func (c *Capture) NumChildren() int {
nchild := 0
for _, ch := range c.children {
if ch.Dummy() {
nchild += ch.NumChildren()
} else {
nchild++
}
}
return nchild
}
func (c *Capture) Start() int {
if c.ment != nil {
return c.ment.pos.Pos() + c.off
}
return c.off
}
func (c *Capture) Len() int {
return c.length
}
func (c *Capture) End() int {
return c.Start() + c.length
}
func (c *Capture) Dummy() bool {
return c.typ == tDummy
}
func (c *Capture) Id() int {
return int(c.id)
}
func (c *Capture) setMEnt(e *Entry) {
if c.ment != nil {
return
}
c.ment = e
c.off = c.off - e.pos.Pos()
for _, c := range c.children {
c.setMEnt(e)
}
}
// String returns a readable string representation of this node, showing the ID
// of this node and its children.
func (c *Capture) String() string {
buf := &bytes.Buffer{}
for i, c := range c.children {
buf.WriteString(c.String())
if i != len(c.children)-1 {
buf.WriteString(", ")
}
}
return fmt.Sprintf("{%d, [%s]}", c.id, buf.String())
}
| true
|
90904ce0529f95925e4e66c384deccc34a6a9d7c
|
Go
|
busik0729/mogule
|
/helpers/array.go
|
UTF-8
| 1,290
| 3.171875
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package helpers
import (
"errors"
"fmt"
"reflect"
)
type ResMap map[string]interface{}
func IndexOf(value string, arr map[int]string) int {
for index, element := range arr {
if element == value {
return index
}
}
return -1
}
func GetStructName(p interface{}) string {
return reflect.TypeOf(p).Name()
}
func SetField(obj interface{}, name string, value interface{}) error {
structValue := reflect.ValueOf(obj).Elem()
structFieldValue := structValue.FieldByName(name)
if !structFieldValue.IsValid() {
return fmt.Errorf("No such field: %s in obj", name)
}
if !structFieldValue.CanSet() {
return fmt.Errorf("Cannot set %s field value", name)
}
structFieldType := structFieldValue.Type()
val := reflect.ValueOf(value)
if structFieldType != val.Type() {
return errors.New("Provided value type didn't match obj field type")
}
structFieldValue.Set(val)
return nil
}
func FillStruct(obj interface{}, m map[string]interface{}) (interface{}, error) {
err := new(error)
for k, v := range m {
err := SetField(obj, k, v)
if err != nil {
return obj, err
}
}
return obj, *err
}
func UnionMaps(m1, m2 map[string]interface{}) map[string]interface{} {
for ia, va := range m1 {
if _, ok := m2[ia]; ok {
continue
}
m2[ia] = va
}
return m2
}
| true
|
b69687a0d6d422b58d980491ca12664caffbba27
|
Go
|
gauravsinhasf/leetcode
|
/roman_to_integer.go
|
UTF-8
| 515
| 3.515625
| 4
|
[] |
no_license
|
[] |
no_license
|
func romanToInt(s string) int {
l := len(s)
if len(s) == 0 {
return 0
}
sum := 0
for i:=l-1; i >= 0; i-- {
sum = sum + value(string(s[i]))
if i != 0 && value(string(s[i])) > (value(string(s[i-1]))) {
sum = sum - value(string(s[i-1]))
i--
}
}
return sum
}
var mapping map[string]int = map[string]int {
"I":1, "V":5, "X":10, "L":50, "C":100, "M":1000, "D":500,
}
func value (str string) int {
return mapping[str]
}
| true
|
9d3bc7a2e0b9b3e180a38dc9cbe47883269138c4
|
Go
|
mkhalegaonkar3/golangexample
|
/ninja_exercise_6/03_defer_keyword.go
|
UTF-8
| 263
| 3.515625
| 4
|
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
func main() {
defer foo() /*we called this function first but deu to defer it will execute after bar()function excutes*/
bar()
}
func foo() {
fmt.Println("This is from foo :1")
}
func bar() {
fmt.Println("This is from bar :2")
}
| true
|
d8ba85b78445df0c8cb6555febc584c231aa6383
|
Go
|
mdnurahmed/design-patterns
|
/Creational/Factory/Vehicle.go
|
UTF-8
| 327
| 2.921875
| 3
|
[] |
no_license
|
[] |
no_license
|
package factory
type Vehicle struct {
typeofvehicle string
wheels int
maxSpeedMiles int
}
func (v *Vehicle) setType(typeofvehicle string) {
v.typeofvehicle = typeofvehicle
}
func (v *Vehicle) setWheels(wheels int) {
v.wheels = wheels
}
func (v *Vehicle) setMaxSpeedMiles(speed int) {
v.maxSpeedMiles = speed
}
| true
|
e84ed583e975d2e3af8d7af459da9ee0761a54a8
|
Go
|
stefanprodan/openfaas-certinfo
|
/certinfo/handler_test.go
|
UTF-8
| 599
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package function
import (
"regexp"
"testing"
)
func TestHandleReturnsCorrectResponse(t *testing.T) {
expected := "www.google.com"
resp := Handle([]byte("www.google.com/about/"))
r := regexp.MustCompile("(?m:" + expected + ")")
if !r.MatchString(resp) {
t.Fatalf("\nExpected: \n%v\nGot: \n%v", expected, resp)
}
}
func TestHandleReturnsMultiSanResponse(t *testing.T) {
expected := ".stefanprodan.com"
resp := Handle([]byte("stefanprodan.com"))
r := regexp.MustCompile("(?m:" + expected + ")")
if !r.MatchString(resp) {
t.Fatalf("\nExpected: \n%v\nGot: \n%v", expected, resp)
}
}
| true
|
9ae8f361fdb050f18d70d6cee827548bded5ca42
|
Go
|
arschles/azure-service-broker
|
/pkg/service/instance_test.go
|
UTF-8
| 4,010
| 2.828125
| 3
|
[
"MIT",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
[
"MIT",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
package service
import (
"encoding/base64"
"fmt"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
var (
testInstance *Instance
testInstanceJSON []byte
)
func init() {
instanceID := "test-instance-id"
serviceID := "test-service-id"
planID := "test-plan-id"
encryptedProvisiongingParameters := []byte(`{"foo":"bar"}`)
encryptedUpdatingParameters := []byte(`{"foo":"bar"}`)
statusReason := "in-progress"
encryptedProvisiongingContext := []byte(`{"baz":"bat"}`)
created, err := time.Parse(time.RFC3339, "2016-07-22T10:11:55-04:00")
if err != nil {
panic(err)
}
testInstance = &Instance{
InstanceID: instanceID,
ServiceID: serviceID,
PlanID: planID,
EncryptedProvisioningParameters: encryptedProvisiongingParameters,
EncryptedUpdatingParameters: encryptedUpdatingParameters,
Status: InstanceStateProvisioning,
StatusReason: statusReason,
EncryptedProvisioningContext: encryptedProvisiongingContext,
Created: created,
}
b64EncryptedProvisioningParameters := base64.StdEncoding.EncodeToString(
encryptedProvisiongingParameters,
)
b64EncryptedUpdatingParameters := base64.StdEncoding.EncodeToString(
encryptedUpdatingParameters,
)
b64EncryptedProvisioningContext := base64.StdEncoding.EncodeToString(
encryptedProvisiongingContext,
)
testInstanceJSONStr := fmt.Sprintf(
`{
"instanceId":"%s",
"serviceId":"%s",
"planId":"%s",
"provisioningParameters":"%s",
"updatingParameters":"%s",
"status":"%s",
"statusReason":"%s",
"provisioningContext":"%s",
"created":"%s"
}`,
instanceID,
serviceID,
planID,
b64EncryptedProvisioningParameters,
b64EncryptedUpdatingParameters,
InstanceStateProvisioning,
statusReason,
b64EncryptedProvisioningContext,
created.Format(time.RFC3339),
)
testInstanceJSONStr = strings.Replace(testInstanceJSONStr, " ", "", -1)
testInstanceJSONStr = strings.Replace(testInstanceJSONStr, "\n", "", -1)
testInstanceJSONStr = strings.Replace(testInstanceJSONStr, "\t", "", -1)
testInstanceJSON = []byte(testInstanceJSONStr)
}
func TestNewInstanceFromJSON(t *testing.T) {
instance, err := NewInstanceFromJSON(testInstanceJSON)
assert.Nil(t, err)
assert.Equal(t, testInstance, instance)
}
func TestInstanceToJSON(t *testing.T) {
json, err := testInstance.ToJSON()
assert.Nil(t, err)
assert.Equal(t, testInstanceJSON, json)
}
func TestSetProvisioningParametersOnInstance(t *testing.T) {
err := testInstance.SetProvisioningParameters(testArbitraryObject, noopCodec)
assert.Nil(t, err)
assert.Equal(
t,
testArbitraryObjectJSON,
testInstance.EncryptedProvisioningParameters,
)
}
func TestSetUpdatingParametersOnInstance(t *testing.T) {
err := testInstance.SetUpdatingParameters(testArbitraryObject, noopCodec)
assert.Nil(t, err)
assert.Equal(
t,
testArbitraryObjectJSON,
testInstance.EncryptedUpdatingParameters,
)
}
func TestGetProvisioningParametersOnInstance(t *testing.T) {
testInstance.EncryptedProvisioningParameters = testArbitraryObjectJSON
pp := &ArbitraryType{}
err := testInstance.GetProvisioningParameters(pp, noopCodec)
assert.Nil(t, err)
assert.Equal(t, testArbitraryObject, pp)
}
func TestGetUpdatingParametersOnInstance(t *testing.T) {
testInstance.EncryptedUpdatingParameters = testArbitraryObjectJSON
up := &ArbitraryType{}
err := testInstance.GetUpdatingParameters(up, noopCodec)
assert.Nil(t, err)
assert.Equal(t, testArbitraryObject, up)
}
func TestSetProvisioningContextOnInstance(t *testing.T) {
err := testInstance.SetProvisioningContext(testArbitraryObject, noopCodec)
assert.Nil(t, err)
assert.Equal(
t,
testInstance.EncryptedProvisioningContext,
testArbitraryObjectJSON,
)
}
func TestGetProvisioningContextOnInstance(t *testing.T) {
testInstance.EncryptedProvisioningContext = testArbitraryObjectJSON
pc := &ArbitraryType{}
err := testInstance.GetProvisioningContext(pc, noopCodec)
assert.Nil(t, err)
assert.Equal(t, testArbitraryObject, pc)
}
| true
|
ee90331eafbb30ad23bbe60122cff46bbcd8c263
|
Go
|
pvormste/yetzap
|
/zap.go
|
UTF-8
| 3,653
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package yetzap
import (
"strings"
"github.com/pvormste/yetenv"
"github.com/pvormste/yetlog"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// ConfigureSugaredFunc defines a function which can be used to configure a sugared logger. See function NewCustomSugaredLogger().
type ConfigureSugaredFunc func() (*zap.SugaredLogger, error)
// SugaredLogger is the wrapper for the actual sugared logger.
type SugaredLogger struct {
zapLogger *zap.SugaredLogger
}
// NewDefaultSugaredLogger creates a new sugared logger with some default configurations for different environments.
func NewDefaultSugaredLogger(environment yetenv.Environment, rawMinLevel string) (yetlog.Logger, error) {
return NewCustomSugaredLogger(func() (*zap.SugaredLogger, error) {
minLevel := zapcore.InfoLevel
if err := minLevel.Set(strings.ToLower(rawMinLevel)); err != nil {
return nil, err
}
var loggerConf zap.Config
switch environment {
case yetenv.Production:
loggerConf = DefaultProductionConfig(minLevel)
default:
loggerConf = DefaultDevelopmentConfig(minLevel)
}
loggerConf.DisableStacktrace = true
logger, err := loggerConf.Build(zap.AddCallerSkip(1))
if err != nil {
return nil, err
}
return logger.Sugar(), nil
})
}
// NewCustomSugaredLogger can be used to create a custom sugared logger by providing a ConfigureSugaredFunc function.
func NewCustomSugaredLogger(zapConfigureFunc ConfigureSugaredFunc) (yetlog.Logger, error) {
zapSugaredLogger, err := zapConfigureFunc()
if err != nil {
return nil, err
}
return SugaredLogger{
zapLogger: zapSugaredLogger,
}, nil
}
// WrapSugaredLogger wraps an existent sugared logger without needing to touch any configuration.
func WrapSugaredLogger(sugaredLogger *zap.SugaredLogger) yetlog.Logger {
return SugaredLogger{
zapLogger: sugaredLogger,
}
}
// DefaultProductionConfig returns the default production config which is used to create a default sugared logger.
func DefaultProductionConfig(minLevel zapcore.Level) zap.Config {
loggerConf := zap.NewProductionConfig()
loggerConf.Level.SetLevel(minLevel)
return loggerConf
}
// DefaultDevelopmentConfig returns the default development config which is used to create a default sugared logger.
func DefaultDevelopmentConfig(minLevel zapcore.Level) zap.Config {
loggerConf := zap.NewDevelopmentConfig()
loggerConf.Level.SetLevel(minLevel)
loggerConf.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
return loggerConf
}
// Reconfigure is currently not implemented and logs a warning.
func (s SugaredLogger) Reconfigure(_ interface{}) {
s.Warn("reconfigure is not implemented", "logger", "zap")
}
// NewNamedLogger creates a new named logger.
func (s SugaredLogger) NewNamedLogger(name string) yetlog.Logger {
namedLogger := s.zapLogger.Named(name)
return SugaredLogger{
zapLogger: namedLogger,
}
}
// Debug logs a debug message with parameters.
func (s SugaredLogger) Debug(message string, fields ...interface{}) {
s.zapLogger.Debugw(message, fields...)
}
// Info logs a info message with parameters.
func (s SugaredLogger) Info(message string, fields ...interface{}) {
s.zapLogger.Infow(message, fields...)
}
// Warn logs a warning message with parameters.
func (s SugaredLogger) Warn(message string, fields ...interface{}) {
s.zapLogger.Warnw(message, fields...)
}
// Error logs a error message with paramters.
func (s SugaredLogger) Error(message string, fields ...interface{}) {
s.zapLogger.Errorw(message, fields...)
}
// Fatal logs a fatal message with paramters.
func (s SugaredLogger) Fatal(message string, fields ...interface{}) {
s.zapLogger.Fatalw(message, fields...)
}
| true
|
21914b84ecf0ed9faaf2a469e8b31deb202b9efc
|
Go
|
shinjikoike8848/TourOfGo
|
/equivalent_binary_trees_test.go
|
UTF-8
| 524
| 2.84375
| 3
|
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"testing"
"golang.org/x/tour/tree"
)
func TestBinaryTree(t *testing.T) {
treeInstance := tree.New(10)
ch := make(chan int)
go func() {
Walk(treeInstance, ch)
close(ch)
}()
for v := range ch {
fmt.Println(v)
}
k := 10
if !Same(tree.New(k), tree.New(k)) {
t.Errorf("Same func should return true when compare tree.New(sameValue)")
}
defK := 11
if Same(tree.New(k), tree.New(defK)) {
t.Errorf("Same func should return false when compare tree.New(defferenceValue)")
}
}
| true
|
47438852470e2ddc22b702c625c1330cd29d1cbe
|
Go
|
shipperizer/argocd-image-updater
|
/pkg/env/env.go
|
UTF-8
| 778
| 3.515625
| 4
|
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package env
import (
"os"
"strings"
)
// Package env provides some utility functions to interact with the environment
// of the process.
// GetBoolVal retrieves a boolean value from given environment envVar.
// Returns default value if envVar is not set.
func GetBoolVal(envVar string, defaultValue bool) bool {
if val := os.Getenv(envVar); val != "" {
if strings.ToLower(val) == "true" {
return true
} else if strings.ToLower(val) == "false" {
return false
}
}
return defaultValue
}
// GetStringVal retrieves a string value from given environment envVar
// Returns default value if envVar is not set.
func GetStringVal(envVar string, defaultValue string) string {
if val := os.Getenv(envVar); val != "" {
return val
} else {
return defaultValue
}
}
| true
|
06dfc67c577d04694a6d5659202d893364b1e7a9
|
Go
|
bowd/quip-exporter
|
/scraper/node_current_user.go
|
UTF-8
| 1,748
| 2.546875
| 3
|
[] |
no_license
|
[] |
no_license
|
package scraper
import (
"context"
"github.com/bowd/quip-exporter/interfaces"
"github.com/bowd/quip-exporter/repositories"
"github.com/bowd/quip-exporter/types"
"github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
"path"
)
type CurrentUserNode struct {
*BaseNode
currentUser *types.QuipUser
onlyPrivate bool
}
func NewCurrentUserNode(ctx context.Context, onlyPrivate bool) interfaces.INode {
wg, ctx := errgroup.WithContext(ctx)
return &CurrentUserNode{
BaseNode: &BaseNode{
logger: logrus.WithField("module", types.NodeTypes.CurrentUser),
path: "/",
wg: wg,
ctx: ctx,
},
onlyPrivate: onlyPrivate,
}
}
func (node CurrentUserNode) Type() types.NodeType {
return types.NodeTypes.CurrentUser
}
func (node CurrentUserNode) ID() string {
return "root"
}
func (node CurrentUserNode) Path() string {
return path.Join("data", "root.json")
}
func (node CurrentUserNode) Children() []interfaces.INode {
children := make([]interfaces.INode, 0, 0)
for _, folderID := range node.currentUser.Folders(node.onlyPrivate) {
children = append(children, NewFolderNode(node.ctx, node.path, folderID))
}
return children
}
func (node *CurrentUserNode) Process(repo interfaces.IRepository, quip interfaces.IQuipClient, search interfaces.ISearchIndex) error {
var currentUser *types.QuipUser
var err error
currentUser, err = repo.GetCurrentUser(node)
if err != nil && repositories.IsNotFoundError(err) {
if currentUser, err = quip.GetCurrentUser(); err != nil {
return err
}
if err := repo.SaveNodeJSON(node, currentUser); err != nil {
return err
}
} else if err != nil {
return err
} else {
node.logger.Debugf("loaded from repository")
}
node.currentUser = currentUser
return nil
}
| true
|
30f6fb2d7b34557bd7ef87fad4d89bb562514087
|
Go
|
tsawler/gowatcher-client
|
/check-cpu.go
|
UTF-8
| 1,093
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"fmt"
"github.com/shirou/gopsutil/cpu"
)
const CPUWarningThreshold = 77.0
const CPUThreshold = 90.0
func checkCPU() (bool, string, string, int, error) {
// get the average cpu usage across all cpus
c, err := cpu.Percent(0, false)
if err != nil {
return false, fmt.Sprintf("Error checking CPU: %s", err.Error()), "", StatusProblem, err
}
// count the number of cpus
numCPU, err := cpu.Counts(true)
if err != nil {
return false, fmt.Sprintf("Error checking CPU: %s", err.Error()), "", StatusProblem, err
}
okay := true
newStatusID := StatusHealthy
msg := fmt.Sprintf("CPU usage okay: %0.4f%% average usage for %d cpu(s)", c[0], numCPU)
// check if there is a warning/problem
if c[0] > CPUWarningThreshold {
newStatusID = StatusWarning
msg = fmt.Sprintf("Warning: Moderate CPU usage: %0.4f%% for %d cpu(s)", c[0], numCPU)
okay = false
} else if c[0] > CPUThreshold {
okay = false
msg = fmt.Sprintf("Problem: High CPU usage %0.4f%% for %d cpu(s)", c[0], numCPU)
newStatusID = StatusProblem
}
return okay, msg, "", newStatusID, nil
}
| true
|
38be3c2d484208dc6f1515fbd3e763564bb99bca
|
Go
|
afinapr/be_fs
|
/service/userService.go
|
UTF-8
| 1,881
| 2.765625
| 3
|
[] |
no_license
|
[] |
no_license
|
package service
import (
"be_fs/models"
"be_fs/repository"
"fmt"
"log"
"net/http"
"strconv"
"github.com/labstack/echo"
)
type ResponseModel struct {
Code int `json: "code" validate: "required"`
Message string `json: "message" validate: "required"`
}
// Createfunction
func CreateUser(c echo.Context) error {
Res := &ResponseModel{400, "Bad Request"}
U := new(models.User)
if err := c.Bind(U); err != nil {
return nil
}
Res = (*ResponseModel)(repository.CreateUser(U))
return c.JSON(http.StatusOK, Res)
}
// ReadAllUserFunction
func ReadAllUser(c echo.Context) error {
limit := c.Param("limit")
dataLimit, _ := strconv.Atoi(limit)
offset := c.Param("offset")
dataOffset, _ := strconv.Atoi(offset)
result := repository.ReadAllUser(dataLimit, dataOffset)
return c.JSON(http.StatusOK, result)
}
// ReadAllUserFunction
func ReadAllUserNoLimit(c echo.Context) error {
result := repository.ReadAllUserNoLimit()
return c.JSON(http.StatusOK, result)
}
// ReadIdUserFunction
func ReadIdUser(c echo.Context) error {
id := c.Param("userId")
data, _ := strconv.Atoi(id)
result := repository.ReadByIdUser(data)
return c.JSON(http.StatusOK, result)
}
// UpdateFunction
func UpdateUser(c echo.Context) error {
Res := &ResponseModel{400, "Bad Request"}
id := c.Param("userId")
data, _ := strconv.Atoi(id)
U := new(models.User)
if err := c.Bind(U); err != nil {
log.Println(err.Error())
return nil
}
Res = (*ResponseModel)(repository.UpdateUser(U, data))
return c.JSON(http.StatusOK, Res)
}
// DeleteFunction
func DeleteUser(c echo.Context) error {
Res := &ResponseModel{400, "Bad Request"}
id := c.Param("userId")
data, _ := strconv.Atoi(id)
fmt.Println("userId", data)
Res = (*ResponseModel)(repository.DeleteUser(data))
return c.JSON(http.StatusOK, Res)
}
| true
|
246895cd006cc1105ba1402f6ba6efc6224b2c61
|
Go
|
yzhlove/Go
|
/action.com/src/interview/chat12/main.go
|
UTF-8
| 320
| 3.4375
| 3
|
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
type People interface {
Show()
}
type Student struct{}
func (stu *Student) Show() {
}
func live() People {
var stu *Student
return stu
}
func main() {
lv := live()
fmt.Printf("%T\n", lv)
fmt.Printf("%T\n", nil)
if lv == nil {
fmt.Println("A")
} else {
fmt.Println("B")
}
}
| true
|
c2b8bd3e72e1f9ebb393dd46d618713654814076
|
Go
|
JayceChant/OnlineJudgeSolutions
|
/leetcode/13/ans.go
|
UTF-8
| 887
| 3.28125
| 3
|
[] |
no_license
|
[] |
no_license
|
package main
var (
strToInt = map[string]int{
"M": 1000,
"CM": 900,
"D": 500,
"CD": 400,
"C": 100,
"XC": 90,
"L": 50,
"XL": 40,
"X": 10,
"IX": 9,
"V": 5,
"IV": 4,
"I": 1,
}
)
// 12ms 49.14% (min 0ms)
// 3.1MB 100%
func romanToInt1(s string) int {
ans := 0
i := 0
for i < len(s)-1 {
if d := strToInt[s[i:i+2]]; d > 0 {
ans += d
i += 2
} else {
ans += strToInt[s[i:i+1]]
i++
}
}
if i < len(s) {
ans += strToInt[s[i:i+1]]
}
return ans
}
var (
charToInt = map[byte]int{
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
}
)
// 4ms, 94.60% (min 0ms)
// 3.1MB, 40% (mine 3076, min 3072)
func romanToInt(s string) int {
right := 0
ans := 0
for i := len(s) - 1; i >= 0; i-- {
cur := charToInt[s[i]]
if cur >= right {
ans += cur
} else {
ans -= cur
}
right = cur
}
return ans
}
| true
|
c797937e4ab6f188d2e9a5776139073ca70b5e13
|
Go
|
alex/zlint
|
/lints/base.go
|
UTF-8
| 1,929
| 2.6875
| 3
|
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package lints
import (
"time"
"github.com/zmap/zcrypto/x509"
)
// global
var (
Lints map[string]*Lint = make(map[string]*Lint)
)
const ZLintVersion = 3
type ZLintResult struct {
ZLintVersion int64 `json:"version"`
Timestamp int64 `json:"timestamp"`
ZLint map[string]ResultStruct `json:"lints"`
NoticesPresent bool `json:"notices_present"`
WarningsPresent bool `json:"warnings_present"`
ErrorsPresent bool `json:"errors_present"`
FatalsPresent bool `json:"fatals_present"`
}
func (result *ZLintResult) Execute(cert *x509.Certificate) error {
result.ZLint = make(map[string]ResultStruct, len(Lints))
for name, l := range Lints {
res, _ := l.ExecuteTest(cert)
result.ZLint[name] = res
result.updateErrorStatePresent(res)
}
return nil
}
func (zlintResult *ZLintResult) updateErrorStatePresent(result ResultStruct) {
switch result.Result {
case Notice:
zlintResult.NoticesPresent = true
case Warn:
zlintResult.WarningsPresent = true
case Error:
zlintResult.ErrorsPresent = true
case Fatal:
zlintResult.FatalsPresent = true
}
}
type LintTest interface {
// runs once globally
Initialize() error
CheckApplies(c *x509.Certificate) bool
RunTest(c *x509.Certificate) (ResultStruct, error)
}
type Lint struct {
Name string
Description string
Provenance string
EffectiveDate time.Time
Test LintTest
}
func (l *Lint) ExecuteTest(cert *x509.Certificate) (ResultStruct, error) {
if !l.Test.CheckApplies(cert) {
return ResultStruct{Result: NA}, nil
} else if !l.EffectiveDate.IsZero() && l.EffectiveDate.After(cert.NotBefore) {
return ResultStruct{Result: NE}, nil
}
return l.Test.RunTest(cert)
}
func RegisterLint(l *Lint) {
if Lints == nil {
Lints = make(map[string]*Lint)
}
l.Test.Initialize()
Lints[l.Name] = l
}
| true
|
c3b5c95b3d037b1f152fd3fa107622181be17c43
|
Go
|
AnupamKSingh/GolangPractice
|
/Context/log/log.go
|
UTF-8
| 516
| 2.921875
| 3
|
[] |
no_license
|
[] |
no_license
|
package log
import (
"fmt"
"math/rand"
"net/http"
"context"
)
const requestIdKey = 42
func Println(ctx context.Context, msg string) {
id, ok := ctx.Value(requestIdKey).(int64)
if !ok {
fmt.Println("Not able to set the context Value")
return
}
fmt.Println(id, msg)
}
func Decorator(f http.HandlerFunc) (http.HandlerFunc) {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
id := rand.Int63()
ctx = context.WithValue(ctx, requestIdKey, id)
f(w, r.WithContext(ctx))
}
}
| true
|
50b647ab8db5bb4e71fc054e153c78a5bb513ba8
|
Go
|
ksharpdabu/wcf
|
/wcf/src/proxy/http/http_connector.go
|
UTF-8
| 2,463
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package http
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"net"
"net_utils"
"proxy"
"strconv"
"strings"
"time"
)
func init() {
proxy.RegistClient("http", func(addr string, proxy string, timeout time.Duration) (net.Conn, error) {
return DialWithTimeout(addr, proxy, timeout)
})
}
type HttpClient struct {
net.Conn
rbuf []byte
}
func (this *HttpClient) Read(b []byte) (int, error) {
if len(this.rbuf) != 0 {
cnt := copy(b, this.rbuf)
if cnt == len(this.rbuf) {
this.rbuf = nil
} else {
this.rbuf = this.rbuf[cnt:]
}
return cnt, nil
}
return this.Conn.Read(b)
}
var CONNECT_STRING = "CONNECT %s HTTP/1.0\r\n\r\n"
var HTTP_END = "\r\n\r\n"
func handleShake(addr string, conn net.Conn) (*HttpClient, error) {
err := net_utils.SendSpecLen(conn, []byte(fmt.Sprintf(CONNECT_STRING, addr)))
if err != nil {
return nil, errors.New(fmt.Sprintf("send connect req fail, err:%v", err))
}
buf := make([]byte, 2048)
index := 0
total := len(buf)
var loc int = -1
for index < total {
cnt, err := conn.Read(buf[index:])
if err != nil {
return nil, errors.New(fmt.Sprintf("recv connect rsp fail, err:%v", err))
}
index += cnt
loc = bytes.Index(buf[0:index], []byte(HTTP_END))
if loc < 0 {
continue
}
break
}
if loc < 0 {
return nil, errors.New(fmt.Sprintf("not found http end from buf, buf:%s", hex.EncodeToString(buf[:index])))
}
codeinfo := strings.SplitN(string(buf[:index]), " ", 3)
if len(codeinfo) != 3 {
return nil, errors.New(fmt.Sprintf("invalid http rsp line, code len:%d", len(codeinfo)))
}
code, err := strconv.ParseInt(codeinfo[1], 10, 32)
if err != nil {
return nil, errors.New(fmt.Sprintf("recv http code invalid, may not num, err:%v", err))
}
if code != 200 {
return nil, errors.New(fmt.Sprintf("recv invalid rsp code:%d", code))
}
cli := &HttpClient{Conn: conn}
if loc+4 < index {
cli.rbuf = buf[loc+4:]
}
return cli, nil
}
func Dial(addr string, proxy string) (net.Conn, error) {
return DialWithTimeout(addr, proxy, 1*time.Hour)
}
func DialWithTimeout(addr string, proxy string, timeout time.Duration) (net.Conn, error) {
conn, err := net.DialTimeout("tcp", proxy, timeout)
if err != nil {
return nil, errors.New(fmt.Sprintf("dial err:%v, target:%s", err, proxy))
}
conn.SetDeadline(time.Now().Add(timeout))
newConn, err := handleShake(addr, conn)
conn.SetDeadline(time.Time{})
if err != nil {
conn.Close()
return nil, err
}
return newConn, nil
}
| true
|
77fcddf00274e126ebb38dd9d671ab19570be7ee
|
Go
|
yiqing95/hellogo
|
/src/hello-go/gowebexamples/TemplateAdvUsage/main.go
|
UTF-8
| 419
| 2.625
| 3
|
[] |
no_license
|
[] |
no_license
|
package main
import (
"html/template"
"log"
"net/http"
)
func main() {
// tmpl := template.Must(template.ParseFiles("base.tmpl", "home.tmpl"))
tmpl := template.Must(template.ParseFiles("views/layouts/base.html", "views/home.html"))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if err := tmpl.Execute(w, nil); err != nil {
log.Fatal(err)
}
})
http.ListenAndServe(":80", nil)
}
| true
|
a1ffaa102bd4441418cb159b8e34d8ce8ce6d01e
|
Go
|
ozoncp/ocp-presentation-api
|
/internal/ocp-slide-api/repo/repo_test.go
|
UTF-8
| 13,169
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package repo_test
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"github.com/ozoncp/ocp-presentation-api/internal/ocp-slide-api/model"
"github.com/ozoncp/ocp-presentation-api/internal/ocp-slide-api/repo"
"github.com/DATA-DOG/go-sqlmock"
"github.com/jmoiron/sqlx"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var errDatabaseConnection = errors.New("error establishing a database connection")
var _ = Describe("Repo", func() {
const (
n = 10
numberOfFields = 3
)
var (
err error
mock sqlmock.Sqlmock
db *sql.DB
sqlxDB *sqlx.DB
ctx context.Context
repository repo.Repo
slides = []model.Slide{
{ID: 1, PresentationID: 1},
{ID: 2, PresentationID: 2},
{ID: 3, PresentationID: 3},
{ID: 4, PresentationID: 4},
{ID: 5, PresentationID: 5},
{ID: 6, PresentationID: 6},
{ID: 7, PresentationID: 7},
{ID: 8, PresentationID: 8},
{ID: 9, PresentationID: 9},
{ID: 10, PresentationID: 10},
}
)
BeforeEach(func() {
db, mock, err = sqlmock.New()
Expect(err).Should(BeNil())
sqlxDB = sqlx.NewDb(db, "sqlmock")
ctx = context.Background()
repository = repo.NewRepo(sqlxDB)
})
JustBeforeEach(func() {
})
AfterEach(func() {
mock.ExpectClose()
err = db.Close()
Expect(err).Should(BeNil())
})
// ////////////////////////////////////////////////////////////////////////
Context("when the repository saves the new slide successfully", func() {
for i, slide := range slides {
mockID := uint64(i)
slide := slide
var id uint64
BeforeEach(func() {
rows := sqlmock.NewRows([]string{
"id",
})
rows.AddRow(
mockID,
)
query := mock.ExpectQuery("INSERT INTO slide")
query.WithArgs(
slide.PresentationID,
slide.Number,
slide.Type,
)
query.WillReturnRows(rows)
id, err = repository.CreateSlide(ctx, slide)
})
It("should return the ID correctly", func() {
Expect(id).To(Equal(mockID))
})
It("should not be an error", func() {
Expect(err).Should(BeNil())
})
}
})
Context("when the repository fails to save the new slide", func() {
for _, slide := range slides {
slide := slide
var id uint64
BeforeEach(func() {
query := mock.ExpectQuery("INSERT INTO slide")
query.WithArgs(
slide.PresentationID,
slide.Number,
slide.Type,
)
query.WillReturnError(errDatabaseConnection)
id, err = repository.CreateSlide(ctx, slide)
})
It("should return the zero-value for the ID", func() {
Expect(id).To(BeZero())
})
It("should be the error", func() {
Expect(err).Should(MatchError(errDatabaseConnection))
})
}
})
Context("when the repository saves the new slides successfully", func() {
for i := 0; i < n; i++ {
var (
lastInsertID int64
rowsAffected int64
numberOfTheCreatedSlides int64
)
BeforeEach(func() {
rowsAffected = int64(len(slides))
values := make([]driver.Value, numberOfFields*rowsAffected)
for i, slide := range slides {
lastInsertID = int64(slide.ID)
values[numberOfFields*i] = slide.PresentationID
values[numberOfFields*i+1] = slide.Number
values[numberOfFields*i+2] = slide.Type
}
mock.ExpectExec("INSERT INTO slide").
WithArgs(values...).
WillReturnResult(sqlmock.NewResult(lastInsertID, rowsAffected))
numberOfTheCreatedSlides, err = repository.MultiCreateSlides(ctx, slides)
})
It("should return the number of the created slides correctly", func() {
Expect(numberOfTheCreatedSlides).To(Equal(rowsAffected))
})
It("should not be an error", func() {
Expect(err).Should(BeNil())
})
}
})
Context("when the repository fails to save the new slides", func() {
for i := 0; i < n; i++ {
var (
rowsAffected int64
numberOfTheCreatedSlides int64
)
BeforeEach(func() {
rowsAffected = int64(len(slides))
values := make([]driver.Value, numberOfFields*rowsAffected)
for i, slide := range slides {
values[numberOfFields*i] = slide.PresentationID
values[numberOfFields*i+1] = slide.Number
values[numberOfFields*i+2] = slide.Type
}
mock.ExpectExec("INSERT INTO slide").WithArgs(values...).WillReturnError(errDatabaseConnection)
numberOfTheCreatedSlides, err = repository.MultiCreateSlides(ctx, slides)
})
It("should return the zero-value for the number of the created slides", func() {
Expect(numberOfTheCreatedSlides).To(BeZero())
})
It("should be the error", func() {
Expect(err).Should(MatchError(errDatabaseConnection))
})
}
})
// ////////////////////////////////////////////////////////////////////////
Context("when the repository updates the slide successfully", func() {
for _, slide := range slides {
slide := slide
var found bool
BeforeEach(func() {
query := mock.ExpectExec("UPDATE slide SET")
query.WithArgs(
slide.PresentationID,
slide.Number,
slide.Type,
slide.ID,
)
query.WillReturnResult(sqlmock.NewResult(1, 1))
found, err = repository.UpdateSlide(ctx, slide)
})
It("should return true", func() {
Expect(found).Should(BeTrue())
})
It("should not be an error", func() {
Expect(err).Should(BeNil())
})
}
})
Context("when the repository fails to update the slide", func() {
for _, slide := range slides {
slide := slide
var found bool
BeforeEach(func() {
query := mock.ExpectExec("UPDATE slide SET")
query.WithArgs(
slide.PresentationID,
slide.Number,
slide.Type,
slide.ID,
)
query.WillReturnError(errDatabaseConnection)
found, err = repository.UpdateSlide(ctx, slide)
})
It("should return false", func() {
Expect(found).Should(BeFalse())
})
It("should be the error", func() {
Expect(err).Should(MatchError(errDatabaseConnection))
})
}
})
Context("when the repository updates the slide unsuccessfully", func() {
for _, slide := range slides {
slide := slide
var found bool
BeforeEach(func() {
query := mock.ExpectExec("UPDATE slide SET")
query.WithArgs(
slide.PresentationID,
slide.Number,
slide.Type,
slide.ID,
)
query.WillReturnResult(sqlmock.NewResult(0, 0))
found, err = repository.UpdateSlide(ctx, slide)
})
It("should return false", func() {
Expect(found).Should(BeFalse())
})
It("should be the error", func() {
Expect(err).Should(MatchError(repo.ErrSlideNotFound))
})
}
})
// ////////////////////////////////////////////////////////////////////////
Context("when the repository describes the slide successfully", func() {
for _, slide := range slides {
slide := slide
var result *model.Slide
BeforeEach(func() {
rows := sqlmock.NewRows([]string{
"id",
"presentation_id",
"number",
"type",
})
rows.AddRow(
slide.ID,
slide.PresentationID,
slide.Number,
slide.Type,
)
query := mock.ExpectQuery("SELECT id, presentation_id, number, type FROM slide WHERE")
query.WithArgs(
slide.ID,
)
query.WillReturnRows(rows)
result, err = repository.DescribeSlide(ctx, slide.ID)
})
It("should populate the slide correctly", func() {
Expect(*result).Should(BeEquivalentTo(slide))
})
It("should not be an error", func() {
Expect(err).Should(BeNil())
})
}
})
Context("when the repository fails to describe the slide", func() {
for _, slide := range slides {
slide := slide
var result *model.Slide
BeforeEach(func() {
rows := sqlmock.NewRows([]string{
"id",
"presentation_id",
"number",
"type",
})
rows.AddRow(
slide.ID,
slide.PresentationID,
slide.Number,
slide.Type,
)
query := mock.ExpectQuery("SELECT id, presentation_id, number, type FROM slide WHERE")
query.WithArgs(
slide.ID,
)
query.WillReturnError(errDatabaseConnection)
result, err = repository.DescribeSlide(ctx, slide.ID)
})
It("should be nil", func() {
Expect(result).Should(BeNil())
})
It("should be the error", func() {
Expect(err).Should(MatchError(errDatabaseConnection))
})
}
})
Context("when the repository describes the slide unsuccessfully", func() {
for _, slide := range slides {
slide := slide
var result *model.Slide
BeforeEach(func() {
query := mock.ExpectQuery("SELECT id, presentation_id, number, type FROM slide WHERE")
query.WithArgs(
slide.ID,
)
query.WillReturnError(sql.ErrNoRows)
result, err = repository.DescribeSlide(ctx, slide.ID)
})
It("should be nil", func() {
Expect(result).Should(BeNil())
})
It("should be the error", func() {
Expect(err).Should(MatchError(repo.ErrSlideNotFound))
})
}
})
// ////////////////////////////////////////////////////////////////////////
Context("when the repository returns the list of slides successfully", func() {
const (
maxLimit = 15
offset = 0
)
for limit := 1; limit <= maxLimit; limit++ {
limit := limit
var result []model.Slide
BeforeEach(func() {
rows := sqlmock.NewRows([]string{
"id",
"presentation_id",
"number",
"type",
})
for i, slide := range slides {
if i == limit {
break
}
rows.AddRow(
slide.ID,
slide.PresentationID,
slide.Number,
slide.Type,
)
}
query := fmt.Sprintf("SELECT id, presentation_id, number, type FROM slide LIMIT %d OFFSET %d",
limit,
offset)
mock.ExpectQuery(query).WillReturnRows(rows)
result, err = repository.ListSlides(ctx, uint64(limit), offset)
})
It("should populate the slice correctly", func() {
Expect(len(result)).Should(BeEquivalentTo(min(limit, len(result))))
})
It("should not be an error", func() {
Expect(err).Should(BeNil())
})
}
})
Context("when the repository fails to return the list of slides", func() {
const (
limit = 10
offset = 0
)
for i := 0; i < n; i++ {
var result []model.Slide
BeforeEach(func() {
query := fmt.Sprintf(
"SELECT id, presentation_id, number, type FROM slide LIMIT %d OFFSET %d",
limit,
offset)
mock.ExpectQuery(query).WillReturnError(errDatabaseConnection)
result, err = repository.ListSlides(ctx, limit, offset)
})
It("should return the empty list of the slides", func() {
Expect(result).Should(BeNil())
})
It("should be the error", func() {
Expect(err).Should(MatchError(errDatabaseConnection))
})
}
})
Context("when the repository returns the list of slides unsuccessfully", func() {
const (
limit = 10
offset = 0
)
for i := 0; i < n; i++ {
var result []model.Slide
BeforeEach(func() {
query := mock.ExpectQuery(fmt.Sprintf(
"SELECT id, presentation_id, number, type FROM slide LIMIT %d OFFSET %d",
limit,
offset))
query.WillReturnError(sql.ErrNoRows)
result, err = repository.ListSlides(ctx, limit, offset)
})
It("should return the empty list of slides", func() {
Expect(result).Should(BeEmpty())
})
It("should be the error", func() {
Expect(err).Should(MatchError(repo.ErrSlideNotFound))
})
}
})
// ////////////////////////////////////////////////////////////////////////
Context("when the repository removes the slide successfully", func() {
for _, slide := range slides {
slide := slide
var found bool
BeforeEach(func() {
query := mock.ExpectExec("DELETE FROM slide WHERE")
query.WithArgs(
slide.ID,
)
query.WillReturnResult(sqlmock.NewResult(1, 1))
found, err = repository.RemoveSlide(ctx, slide.ID)
})
It("should return true", func() {
Expect(found).Should(BeTrue())
})
It("should not be an error", func() {
Expect(err).Should(BeNil())
})
}
})
Context("when the repository fails to remove the slide", func() {
for _, slide := range slides {
slide := slide
var found bool
BeforeEach(func() {
query := mock.ExpectExec("DELETE FROM slide WHERE")
query.WithArgs(
slide.ID,
)
query.WillReturnError(errDatabaseConnection)
found, err = repository.RemoveSlide(ctx, slide.ID)
})
It("should return false", func() {
Expect(found).Should(BeFalse())
})
It("should be the error", func() {
Expect(err).Should(MatchError(errDatabaseConnection))
})
}
})
Context("when the repository removes the slide unsuccessfully", func() {
for _, slide := range slides {
slide := slide
var found bool
BeforeEach(func() {
query := mock.ExpectExec("DELETE FROM slide WHERE")
query.WithArgs(
slide.ID,
)
query.WillReturnResult(sqlmock.NewResult(0, 0))
found, err = repository.RemoveSlide(ctx, slide.ID)
})
It("should return false", func() {
Expect(found).Should(BeFalse())
})
It("should be the error", func() {
Expect(err).Should(MatchError(repo.ErrSlideNotFound))
})
}
})
})
func min(lhs int, rhs int) int {
if lhs <= rhs {
return lhs
}
return rhs
}
| true
|
ec58f7d31f9927a631d96d98faa593910642f67e
|
Go
|
chenjr15/leetcode
|
/剑指Offer-2/037-小行星碰撞/037-小行星碰撞.go
|
UTF-8
| 1,814
| 3.34375
| 3
|
[] |
no_license
|
[] |
no_license
|
func asteroidCollision(asteroids []int) []int {
// 1. 符号相同的不会相遇
// 2. 相遇后绝对值大的留下,相等的同时消失
// 考虑用双链表模拟,先构建双链表,然后从做到右找第一个异号的数字开始碰
// 碰了以后将消失的删掉,然后留下的在和左边的比符号,如果左边为空则和右边比符号,重复上述步骤,直到没有异号
// 注意最左边的负号将没得碰,因此直接跳掉
// -- 这个过程可以直接用一个栈来简化
stack:= make([]int,0,len(asteroids))
for _,star := range asteroids{
if len(stack) == 0 || stack[len(stack)-1] < 0||star >0{
// 左边是空或者全是符号的,或者当前行星是往右的,直接进栈
stack=append(stack,star)
}else if star*stack[len(stack)-1] <0{
// fmt.Println("开始撞",stack,star)
// 就一直撞直到:1. 左边没了,2.右边的撞没 3.左边的是往左走的
for len(stack) != 0 && star!=0 && stack[len(stack)-1]>0{
// 异号,且star<0 ,开始撞
if -star == stack[len(stack)-1] {
// 同归于尽
stack=stack[:len(stack)-1]
// 消除star
star = 0
}else if -star < stack[len(stack)-1]{
// 右边消失
star = 0
break
}else{
// 左边消失,需要将左边的提上来再比
stack=stack[:len(stack)-1]
}
}
// fmt.Println("结果",stack,star)
if star != 0{
stack=append(stack,star)
}
}
}
return stack
}
| true
|
529be1ffb8b1ebe4922360c20fc926e50af4dbd7
|
Go
|
ssonal/gorse
|
/model/co_clustering.go
|
UTF-8
| 7,568
| 2.875
| 3
|
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package model
import (
"github.com/zhenghaoz/gorse/base"
"github.com/zhenghaoz/gorse/core"
"math"
)
// CoClustering [5] is a novel collaborative filtering approach based on weighted
// co-clustering algorithm that involves simultaneous clustering of users and
// items.
//
// Let U={u_i}^m_{i=1} be the set of users such that |U|=m and P={p_j}^n_{j=1} be
// the set of items such that |P|=n. Let A be the m x n ratings matrix such that
// A_{ij} is the rating of the user u_i for the item p_j. The approximate matrix
// \hat{A}_{ij} is given by
// \hat{A}_{ij} = A^{COC}_{gh} + (A^R_i - A^{RC}_g) + (A^C_j - A^{CC}_h)
// where g=ρ(i), h=γ(j) and A^R_i, A^C_j are the average ratings of user u_i and
// item p_j, and A^{COC}_{gh}, A^{RC}_g and A^{CC}_h are the average ratings of
// the corresponding co-cluster, user-cluster and item-cluster respectively.
//
// Hyper-parameters:
// NEpochs - The number of iterations of the optimization procedure. Default is 20.
// NUserClusters - The number of user clusters. Default is 3.
// NItemClusters - The number of item clusters. Default is 3.
// RandomState - The random seed. Default is 0.
type CoClustering struct {
Base
GlobalMean float64 // A^{global}
UserMeans []float64 // A^{R}
ItemMeans []float64 // A^{R}
UserClusters []int // p(i)
ItemClusters []int // y(i)
UserClusterMeans []float64 // A^{RC}
ItemClusterMeans []float64 // A^{CC}
CoClusterMeans [][]float64 // A^{COC}
// Hyper-parameters
nUserClusters int // The number of user clusters
nItemClusters int // The number of user clusters
nEpochs int // The number of iterations of the optimization procedure
}
// NewCoClustering creates a CoClustering model.
func NewCoClustering(params base.Params) *CoClustering {
coc := new(CoClustering)
coc.SetParams(params)
return coc
}
// SetParams sets hyper-parameters for the CoClustering model.
func (coc *CoClustering) SetParams(params base.Params) {
coc.Base.SetParams(params)
// Setup hyper-parameters
coc.nUserClusters = coc.Params.GetInt(base.NUserClusters, 3)
coc.nItemClusters = coc.Params.GetInt(base.NItemClusters, 3)
coc.nEpochs = coc.Params.GetInt(base.NEpochs, 20)
}
// Predict by the CoClustering model.
func (coc *CoClustering) Predict(userId, itemId int) float64 {
// Convert IDs to indices
userIndex := coc.UserIndexer.ToIndex(userId)
itemIndex := coc.ItemIndexer.ToIndex(itemId)
return coc.predict(userIndex, itemIndex)
}
func (coc *CoClustering) predict(userIndex, itemIndex int) float64 {
prediction := 0.0
if userIndex != base.NotId && itemIndex != base.NotId &&
!math.IsNaN(coc.UserMeans[userIndex]) && !math.IsNaN(coc.ItemMeans[itemIndex]) {
// old user & old item
userCluster := coc.UserClusters[userIndex]
itemCluster := coc.ItemClusters[itemIndex]
prediction = coc.UserMeans[userIndex] + coc.ItemMeans[itemIndex] -
coc.UserClusterMeans[userCluster] - coc.ItemClusterMeans[itemCluster] +
coc.CoClusterMeans[userCluster][itemCluster]
} else if userIndex != base.NotId && !math.IsNaN(coc.UserMeans[userIndex]) {
// old user & new item
prediction = coc.UserMeans[userIndex]
} else if itemIndex != base.NotId && !math.IsNaN(coc.ItemMeans[itemIndex]) {
// new user & old item
prediction = coc.ItemMeans[itemIndex]
} else {
// new user & new item
prediction = coc.GlobalMean
}
return prediction
}
// Fit the CoClustering model.
func (coc *CoClustering) Fit(trainSet core.DataSetInterface, options *base.RuntimeOptions) {
coc.Init(trainSet)
// Initialize parameters
coc.GlobalMean = trainSet.GlobalMean()
coc.UserMeans = make([]float64, trainSet.UserCount())
for i := 0; i < trainSet.UserCount(); i++ {
coc.UserMeans[i] = trainSet.UserByIndex(i).Mean()
}
coc.ItemMeans = make([]float64, trainSet.ItemCount())
for i := 0; i < trainSet.ItemCount(); i++ {
coc.ItemMeans[i] = trainSet.ItemByIndex(i).Mean()
}
coc.UserClusters = make([]int, trainSet.UserCount())
for i := range coc.UserClusters {
if trainSet.UserByIndex(i).Len() > 0 {
coc.UserClusters[i] = coc.rng.Intn(coc.nUserClusters)
}
}
coc.ItemClusters = make([]int, trainSet.ItemCount())
for i := range coc.ItemClusters {
if trainSet.ItemByIndex(i).Len() > 0 {
coc.ItemClusters[i] = coc.rng.Intn(coc.nItemClusters)
}
}
coc.UserClusterMeans = make([]float64, coc.nUserClusters)
coc.ItemClusterMeans = make([]float64, coc.nItemClusters)
coc.CoClusterMeans = base.NewMatrix(coc.nUserClusters, coc.nItemClusters)
// Clustering
for ep := 0; ep < coc.nEpochs; ep++ {
options.Logf("epoch = %v/%v", ep+1, coc.nEpochs)
// Compute averages A^{COC}, A^{RC}, A^{CC}, A^R, A^C
coc.clusterMean(coc.UserClusterMeans, coc.UserClusters, trainSet.Users())
coc.clusterMean(coc.ItemClusterMeans, coc.ItemClusters, trainSet.Items())
coc.coClusterMean(coc.CoClusterMeans, coc.UserClusters, coc.ItemClusters, trainSet.Users())
// Update row (user) cluster assignments
base.ParallelFor(0, trainSet.UserCount(), func(userIndex int) {
bestCluster, leastCost := -1, math.Inf(1)
for g := 0; g < coc.nUserClusters; g++ {
cost := 0.0
trainSet.UserByIndex(userIndex).ForEachIndex(func(_, itemIndex int, value float64) {
itemCluster := coc.ItemClusters[itemIndex]
prediction := coc.UserMeans[userIndex] + coc.ItemMeans[itemIndex] -
coc.UserClusterMeans[g] -
coc.ItemClusterMeans[itemCluster] +
coc.CoClusterMeans[g][itemCluster]
temp := prediction - value
cost += temp * temp
})
if cost < leastCost {
bestCluster = g
leastCost = cost
}
}
coc.UserClusters[userIndex] = bestCluster
})
// Update column (item) cluster assignments
base.ParallelFor(0, trainSet.ItemCount(), func(itemIndex int) {
bestCluster, leastCost := -1, math.Inf(1)
for h := 0; h < coc.nItemClusters; h++ {
cost := 0.0
trainSet.ItemByIndex(itemIndex).ForEachIndex(func(_, userIndex int, value float64) {
userCluster := coc.UserClusters[userIndex]
prediction := coc.UserMeans[userIndex] + coc.ItemMeans[itemIndex] -
coc.UserClusterMeans[userCluster] - coc.ItemClusterMeans[h] +
coc.CoClusterMeans[userCluster][h]
temp := prediction - value
cost += temp * temp
})
if cost < leastCost {
bestCluster = h
leastCost = cost
}
}
coc.ItemClusters[itemIndex] = bestCluster
})
}
}
// clusterMean computes the mean ratings of clusters.
func (coc *CoClustering) clusterMean(dst []float64, clusters []int, ratings []*base.MarginalSubSet) {
base.FillZeroVector(dst)
count := make([]float64, len(dst))
for index, cluster := range clusters {
ratings[index].ForEachIndex(func(_, index int, value float64) {
dst[cluster] += value
count[cluster]++
})
}
for i := range dst {
if count[i] > 0 {
dst[i] /= count[i]
} else {
dst[i] = coc.GlobalMean
}
}
}
// coClusterMean computes the mean ratings of co-clusters.
func (coc *CoClustering) coClusterMean(dst [][]float64, userClusters, itemClusters []int, userRatings []*base.MarginalSubSet) {
base.FillZeroMatrix(dst)
count := base.NewMatrix(coc.nUserClusters, coc.nItemClusters)
for userIndex, userCluster := range userClusters {
userRatings[userIndex].ForEachIndex(func(_, itemIndex int, value float64) {
itemCluster := itemClusters[itemIndex]
count[userCluster][itemCluster]++
dst[userCluster][itemCluster] += value
})
}
for i := range dst {
for j := range dst[i] {
if count[i][j] > 0 {
dst[i][j] /= count[i][j]
} else {
dst[i][j] = coc.GlobalMean
}
}
}
}
| true
|
e9132b05b6d7eaba78928967cf2b40b4a9988b12
|
Go
|
shenjindui/go-learn
|
/src/go-code/project01/main/slice.go
|
UTF-8
| 4,555
| 4.09375
| 4
|
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
/**
切片 [] 标识切片类型
*/
func main() {
//切片 slice 切片的长度是不固定的,可以追加元素,在追加时可能使切片的容量增大。 [] 表示是切片类型
//切片是可索引的,并且可以由 len() 方法获取长度。 切片提供了计算容量的方法 cap() 可以测量切片最长可以达到多少。
//一个切片在未初始化之前默认为 nil,长度为 0
var slice []int = make([]int, 5, 5)
slice[0] = '2'
//fmt.Println(slice[0])
var slice2 []int
if slice2 == nil {
//fmt.Printf("kongde ")
}
//fmt.Printf("%T\n %v",slice2,slice2)
//增加切片的容量 使用append copy 函数
var slice3 []int
fmt.Printf("slice3%v\n", slice3)
slice3 = append(slice3, 0)
fmt.Printf("slice3%v\n", slice3)
slice3 = append(slice3, 1, 2, 3, 4)
fmt.Printf("slice3%v\n", slice3)
fmt.Printf("slice3 cap = %v\n", cap(slice3))
//copy函数
number1 := make([]int, len(slice3), cap(slice3)*2)
copy(number1, slice3)
fmt.Printf("number1 = %v\n", len(number1))
string := []string{"nihao", "shenjindui", "1000"}
test1(string...)
//slice自身维护了一个指针属性,指向它底层数组中的某些元素的集合。 (可以理解为就是一个指针)
//每一个slice结构都由3部分组成:容量cap(capacity)、长度len(length)和指向底层数组某元素的指针,
//它们各占8字节(1个机器字长,64位机器上一个机器字长为64bit,共8字节大小,32位架构则是32bit,占用4字节),所以任何一个slice都是24字节(3个机器字长)
testSlice := make([]int, 3, 5)
fmt.Println("testSlice = ", testSlice)
//make()和new()
//make()比new()函数多一些操作,new()函数只会进行内存分配并做默认的赋0初始化,而make()可以先为底层数组分配好内存,
//然后从这个底层数组中再额外生成一个slice并初始化。另外,make只能构建slice、map和channel这3种结构的数据对象,
//因为它们都指向底层数据结构,都需要先为底层数据结构分配好内存并初始化。
//array 和 slice的区别
// 创建长度为3的int数组
array := [3]int{10, 20, 30}
fmt.Println("array=", array)
// 创建长度和容量都为3的slice
slice1 := []int{10, 20, 30}
fmt.Println("slice=", cap(slice1))
//对slice进行切片 (左闭右开)
mySlice := []int{11, 22, 33, 44, 55}
// 生成新的slice,从第二个元素取,切取的长度为2
newSlice := mySlice[1:3]
fmt.Println("newSlice=", newSlice)
//合并slice 合并slice时,通过append函数,只需将append()的第二个参数后加上 ...
s1 := []int{1, 2}
s2 := []int{3, 4}
s3 := append(s1, s2...)
fmt.Println(s3)
//传递slice给函数
//Go中函数的参数是按值传递的,所以调用函数时会复制一个参数的副本传递给函数。如果传递给函数的是slice,
//它将复制该slice副本给函数,这个副本实际上就是[3/5]0xc42003df10,所以传递给函数的副本仍然指向源slice的底层数组。
//换句话说,如果函数内部对slice进行了修改,有可能会直接影响函数外部的底层数组,从而影响其它slice。但并不总是如此,
//例如函数内部对slice进行扩容,扩容时生成了一个新的底层数组,函数后续的代码只对新的底层数组操作,这样就不会影响原始的底层数组
//虽然函数参数传递是拷贝一份,然而拷贝的一份地址仍然指向原来的那一个slice.
s4 := []int{11, 22, 33, 44}
foo(s4)
fmt.Println(s4[1]) // 输出:23
//内存上关于slice
//由于slice的底层是数组,很可能数组很大,但slice所取的元素数量却很小,这就导致数组占用的绝大多数空间是被浪费的。
//特别地,垃圾回收器(GC)不会回收正在被引用的对象,当一个函数直接返回指向底层数组的slice时,这个底层数组将不会随函数退出而被回收,
//而是因为slice的引用而永远保留,除非返回的slice也消失。
//因此,当函数的返回值是一个指向底层数组的数据结构时(如slice),应当在函数内部将slice拷贝一份保存到一个使用自己底层数组的新slice中,
//并返回这个新的slice。这样函数一退出,原来那个体积较大的底层数组就会被回收,保留在内存中的是小的slice。
}
/**
测试 ...
*/
func test1(args ...string) {
for _, v := range args {
fmt.Printf("%v\n", v)
}
}
func foo(s []int) {
for index, _ := range s {
s[index] += 1
}
}
| true
|
627b303969d0a936205746cfe3cc843a238352d5
|
Go
|
altipla-consulting/libs
|
/rdb/session_test.go
|
UTF-8
| 1,117
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package rdb
import (
"context"
"testing"
"github.com/stretchr/testify/require"
)
func TestLoadMultipleTimesSameEntityDoesNotFail(t *testing.T) {
ctx := context.Background()
db := initCollectionTestbed(t)
collection := db.Collection(new(FooCollectionModel))
foo3 := &FooCollectionModel{
ID: "foo-collections/3",
DisplayName: "foo-collections/4",
}
require.NoError(t, collection.Put(ctx, foo3))
foo4 := &FooCollectionModel{
ID: "foo-collections/4",
DisplayName: "Foo-Dest",
}
require.NoError(t, collection.Put(ctx, foo4))
ctx, sess := db.NewSession(ctx)
var other *FooCollectionModel
require.NoError(t, collection.Get(ctx, "foo-collections/3", &other, Include("DisplayName")))
var first *FooCollectionModel
require.NoError(t, sess.Load("foo-collections/4", &first))
require.Equal(t, first.ID, "foo-collections/4")
require.Equal(t, first.DisplayName, "Foo-Dest")
var repeated *FooCollectionModel
require.NoError(t, sess.Load("foo-collections/4", &repeated))
require.Equal(t, repeated.ID, "foo-collections/4")
require.Equal(t, repeated.DisplayName, "Foo-Dest")
}
| true
|
370c07a578aa368beebdb75b893faad06a901149
|
Go
|
perryyo/tilt
|
/internal/build/tar.go
|
UTF-8
| 5,042
| 2.78125
| 3
|
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package build
import (
"archive/tar"
"bytes"
"context"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
"github.com/pkg/errors"
"github.com/windmilleng/tilt/internal/dockerfile"
"github.com/windmilleng/tilt/internal/model"
opentracing "github.com/opentracing/opentracing-go"
)
type ArchiveBuilder struct {
tw *tar.Writer
buf *bytes.Buffer
filter model.PathMatcher
}
func NewArchiveBuilder(filter model.PathMatcher) *ArchiveBuilder {
buf := new(bytes.Buffer)
tw := tar.NewWriter(buf)
if filter == nil {
filter = model.EmptyMatcher
}
return &ArchiveBuilder{tw: tw, buf: buf, filter: filter}
}
func (a *ArchiveBuilder) close() error {
return a.tw.Close()
}
func (a *ArchiveBuilder) archiveDf(ctx context.Context, df dockerfile.Dockerfile) error {
span, ctx := opentracing.StartSpanFromContext(ctx, "daemon-archiveDf")
defer span.Finish()
tarHeader := &tar.Header{
Name: "Dockerfile",
Typeflag: tar.TypeReg,
Size: int64(len(df)),
ModTime: time.Now(),
AccessTime: time.Now(),
ChangeTime: time.Now(),
}
err := a.tw.WriteHeader(tarHeader)
if err != nil {
return err
}
_, err = a.tw.Write([]byte(df))
if err != nil {
return err
}
return nil
}
// ArchivePathsIfExist creates a tar archive of all local files in `paths`. It quietly skips any paths that don't exist.
func (a *ArchiveBuilder) ArchivePathsIfExist(ctx context.Context, paths []pathMapping) error {
span, ctx := opentracing.StartSpanFromContext(ctx, "daemon-ArchivePathsIfExist")
defer span.Finish()
for _, p := range paths {
err := a.tarPath(ctx, p.LocalPath, p.ContainerPath)
if err != nil {
return errors.Wrapf(err, "tarPath '%s'", p.LocalPath)
}
}
return nil
}
func (a *ArchiveBuilder) BytesBuffer() (*bytes.Buffer, error) {
err := a.close()
if err != nil {
return nil, err
}
return a.buf, nil
}
// tarPath writes the given source path into tarWriter at the given dest (recursively for directories).
// e.g. tarring my_dir --> dest d: d/file_a, d/file_b
// If source path does not exist, quietly skips it and returns no err
func (a *ArchiveBuilder) tarPath(ctx context.Context, source, dest string) error {
span, ctx := opentracing.StartSpanFromContext(ctx, fmt.Sprintf("daemon-tarPath-%s", source))
span.SetTag("source", source)
span.SetTag("dest", dest)
defer span.Finish()
sourceInfo, err := os.Stat(source)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return errors.Wrapf(err, "%s: stat", source)
}
sourceIsDir := sourceInfo.IsDir()
if sourceIsDir {
// Make sure we can trim this off filenames to get valid relative filepaths
if !strings.HasSuffix(source, "/") {
source += "/"
}
}
dest = strings.TrimPrefix(dest, "/")
err = filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
if err != nil {
return errors.Wrapf(err, "error walking to %s", path)
}
matches, err := a.filter.Matches(path, info.IsDir())
if err != nil {
return err
} else if matches {
return nil
}
header, err := tar.FileInfoHeader(info, path)
if err != nil {
return errors.Wrapf(err, "%s: making header", path)
}
if sourceIsDir {
// Name of file in tar should be relative to source directory...
header.Name = strings.TrimPrefix(path, source)
// ...and live inside `dest`
header.Name = filepath.Join(dest, header.Name)
} else if strings.HasSuffix(dest, string(filepath.Separator)) {
header.Name = filepath.Join(dest, filepath.Base(source))
} else {
header.Name = dest
}
header.Name = filepath.Clean(header.Name)
err = a.tw.WriteHeader(header)
if err != nil {
return errors.Wrapf(err, "%s: writing header", path)
}
if info.IsDir() {
return nil
}
if header.Typeflag == tar.TypeReg {
file, err := os.Open(path)
if err != nil {
// In case the file has been deleted since we last looked at it.
if os.IsNotExist(err) {
return nil
}
return errors.Wrapf(err, "%s: open", path)
}
defer func() {
_ = file.Close()
}()
_, err = io.CopyN(a.tw, file, info.Size())
if err != nil && err != io.EOF {
return errors.Wrapf(err, "%s: copying Contents", path)
}
}
return nil
})
return err
}
func (a *ArchiveBuilder) len() int {
return a.buf.Len()
}
func tarContextAndUpdateDf(ctx context.Context, df dockerfile.Dockerfile, paths []pathMapping, filter model.PathMatcher) (*bytes.Buffer, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "daemon-tarContextAndUpdateDf")
defer span.Finish()
ab := NewArchiveBuilder(filter)
err := ab.ArchivePathsIfExist(ctx, paths)
if err != nil {
return nil, errors.Wrap(err, "archivePaths")
}
err = ab.archiveDf(ctx, df)
if err != nil {
return nil, errors.Wrap(err, "archiveDf")
}
return ab.BytesBuffer()
}
func tarDfOnly(ctx context.Context, df dockerfile.Dockerfile) (*bytes.Buffer, error) {
ab := NewArchiveBuilder(model.EmptyMatcher)
err := ab.archiveDf(ctx, df)
if err != nil {
return nil, errors.Wrap(err, "tarDfOnly")
}
return ab.BytesBuffer()
}
| true
|
aaf77dadca0de0bf54069f792c6066c23e9c7297
|
Go
|
Z1298174226/go-leetcode
|
/src/array/ZeroOneTwoConfig.go
|
UTF-8
| 490
| 3.15625
| 3
|
[] |
no_license
|
[] |
no_license
|
package array
func ZeroOneTwoConfig(arr *[]int) {
len := len(*arr)
if *arr == nil || len < 2 {
return
}
left := -1
right := len
index := 0
for {
if index >= right {
break
} else {
if (*arr)[index] == 0 {
left++
SwapConfig(index, left, arr)
index++
} else if (*arr)[index] == 2 {
right--
SwapConfig(index, right, arr)
} else {
index++
}
}
}
}
func SwapConfig(i int, j int, arr *[]int) {
(*arr)[i], (*arr)[j] = (*arr)[j], (*arr)[i]
}
| true
|
07a47f1cffc58d8d04c02f4de64b4915e5130932
|
Go
|
higashi000/sleahck
|
/sleahckSlack/channelList.go
|
UTF-8
| 911
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package sleahckSlack
import (
"log"
"net/http"
"io/ioutil"
"os"
"encoding/json"
)
type Channels struct {
Ok bool `json:"ok"`
Channel []struct {
Id string `json:"id"`
Name string `json:"name"`
} `json:"Channels"`
}
func GetChannels() *Channels {
var channels *Channels
reqURL := "https://slack.com/api/users.conversations"
req, err := http.NewRequest("GET", reqURL, nil)
if err != nil {
log.Println(err)
}
req.Header.Add("Authorization", "Bearer " + os.Getenv("SLACK_TOKEN"))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
client := new(http.Client)
resp, err := client.Do(req)
if err != nil {
log.Println(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println(err)
}
err = json.Unmarshal(body, &channels)
if err != nil {
log.Println(err)
}
return channels
}
| true
|
99d0abab2d1125ab61bdc3c403344c560a654107
|
Go
|
ankeesler/flexec
|
/main.go
|
UTF-8
| 4,502
| 2.65625
| 3
|
[] |
no_license
|
[] |
no_license
|
package main
import (
"bufio"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/pkg/errors"
yaml "gopkg.in/yaml.v1"
"github.com/ankeesler/flexec/helper"
)
func main() {
if err := run(); err != nil {
log.Fatalf("error: %s", err.Error())
}
}
func run() error {
if len(os.Args) != 2 {
fmt.Printf("usage: %s <task-name>\n", os.Args[0])
os.Exit(1)
}
log.SetFlags(0)
log.SetPrefix(fmt.Sprintf("%s: ", filepath.Base(os.Args[0])))
flexecConfig := helper.NewFlexecConfig()
if err := helper.ReadFlexecConfig(flexecConfig); err != nil {
return errors.Wrap(err, "load flexexec config")
}
defer func() {
if err := helper.WriteFlexecConfig(flexecConfig); err != nil {
log.Printf("note: error: write flexec config: %s", err.Error())
}
}()
taskName := os.Args[1]
taskConfigPath := filepath.Join(
os.Getenv("HOME"),
"workspace",
"credhub-ci",
"tasks",
taskName,
"task.yml",
)
taskConfigData, err := getTaskConfigData(taskConfigPath)
if err != nil {
return errors.Wrap(err, "get task config data")
}
var taskConfig helper.TaskConfig
if err := yaml.Unmarshal(taskConfigData, &taskConfig); err != nil {
return errors.Wrap(err, "unmarshal task config yaml")
}
cmdBuilder := helper.NewCmdBuilder(taskConfigPath)
if err := resolveInputs(&taskConfig, cmdBuilder.OnInput); err != nil {
return errors.Wrap(err, "resolve inputs")
}
if err := resolveOutputs(&taskConfig, cmdBuilder.OnOutput); err != nil {
return errors.Wrap(err, "resolve outputs")
}
if err := resolveParams(
&taskConfig,
flexecConfig.ParamDefaults,
cmdBuilder.OnParam,
); err != nil {
return errors.Wrap(err, "resolve params")
}
cmd := cmdBuilder.Build()
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
log.Printf("running command: \n %s", cmdBuilder.String())
if err := cmd.Run(); err != nil {
return errors.Wrap(err, "run command")
}
return nil
}
func getTaskConfigData(taskConfigPath string) ([]byte, error) {
log.Printf("reading task path %s", taskConfigPath)
taskConfigData, err := ioutil.ReadFile(taskConfigPath)
if err != nil {
return nil, errors.Wrap(err, "read task config file")
}
return taskConfigData, nil
}
func resolveInputs(config *helper.TaskConfig, handler func(name, path string)) error {
for _, inputMap := range config.Inputs {
input, ok := inputMap["name"]
if !ok {
return fmt.Errorf("input map does not contain name: %s", inputMap)
}
path, ok := resolveRepo(input)
if !ok {
path = fmt.Sprintf("/tmp/%s", input)
if err := os.MkdirAll(path, 0700); err != nil {
return errors.Wrap(err, fmt.Sprintf("mkdir (%s)", path))
}
log.Printf("cannot resolve repo for input %s", input)
}
log.Printf("resolved input %s to path %s", input, path)
handler(input, path)
}
return nil
}
func resolveOutputs(config *helper.TaskConfig, handler func(name, path string)) error {
for _, outputMap := range config.Outputs {
output, ok := outputMap["name"]
if !ok {
return fmt.Errorf("output map does not contain name: %s", outputMap)
}
path := fmt.Sprintf("/tmp/%s", output)
log.Printf("resolved output %s to path %s", output, path)
handler(output, path)
}
return nil
}
func resolveParams(
config *helper.TaskConfig,
defaults map[string]string,
handler func(paramKey, paramValue string),
) error {
for paramKey, paramValue := range config.Params {
if paramValue == "" {
fmt.Printf(
"enter value for param %s (default '%s'): ",
paramKey,
defaults[paramKey],
)
text, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil {
return errors.Wrap(err, "read string from stdin")
}
paramValue = strings.TrimSpace(text)
if len(paramValue) == 0 {
paramValue = defaults[paramKey]
}
defaults[paramKey] = paramValue
}
log.Printf("setting param: %s => %s", paramKey, paramValue)
handler(paramKey, paramValue)
}
return nil
}
func resolveRepo(name string) (string, bool) {
repo := filepath.Join(
os.Getenv("HOME"),
"workspace",
name,
)
if _, err := os.Stat(repo); err == nil {
return repo, true
}
cmd := exec.Command(
"find",
filepath.Join(os.Getenv("HOME"), "go"),
"-name",
name,
)
output, err := cmd.CombinedOutput()
if err != nil {
log.Printf("note: failed to run find command (output = %s)", string(output))
return "", false
}
outputString := string(output)
if strings.Count(outputString, "\n") == 1 {
return strings.TrimSpace(outputString), true
}
return "", false
}
| true
|
74cdeb7a81b7cc94d40a7fc4839d9c4a3ffd2194
|
Go
|
funnythingz/go-plog-api
|
/services/auth-service.go
|
UTF-8
| 921
| 2.828125
| 3
|
[] |
no_license
|
[] |
no_license
|
package service
import (
"github.com/funnythingz/go-plog-api/config"
"net/http"
"net/url"
)
type Auth struct{}
func (a *Auth) BeforeAuth(w http.ResponseWriter, r *http.Request) bool {
t := a.ParseAccessKeyFromRequest(r)
isAuth := a.CheckAuth(t)
if isAuth == false {
http.Redirect(w, r, "/", 404)
}
return isAuth
}
func (a *Auth) ParseAccessKeyFromRequest(r *http.Request) string {
u, _ := url.Parse(r.RequestURI)
q, err := url.ParseQuery(u.RawQuery)
if err != nil {
return err.Error()
}
if q["access_key"] != nil {
return q["access_key"][0]
}
return ""
}
func (a *Auth) CheckAuth(accessKey string) bool {
return accessKey == config.Params.Auth.AccessKey
}
var AuthService = Auth{}
func BeforeAuth(w http.ResponseWriter, r *http.Request) bool {
return AuthService.BeforeAuth(w, r)
}
func ParseAccessKeyFromRequest(r *http.Request) string {
return AuthService.ParseAccessKeyFromRequest(r)
}
| true
|
9b7bdebb9b5c43e8619460f820f3cef7149c07de
|
Go
|
jingchunzhang/cctool
|
/internal/utils/utils.go
|
UTF-8
| 1,814
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package utils
import (
"crypto/md5"
"encoding/hex"
"fmt"
"github.com/golang/protobuf/ptypes/duration"
"math/rand"
"os"
"path/filepath"
"time"
)
func init() {
rand.Seed(time.Now().Unix())
}
func Md5String(str string) string {
h := md5.New()
h.Write([]byte(str))
return hex.EncodeToString(h.Sum(nil))
}
func GetIntRandomNumber(min int64, max int64) int64 {
return rand.Int63n(max-min) + min
}
func CheckFileExist(path string) (flag bool) {
var (
err error
absFile string
)
absFile, err = filepath.Abs(path)
if err != nil {
return
}
_, err = os.Stat(absFile)
if err == nil {
flag = true
return
}
if os.IsNotExist(err) {
flag = false
}
return
}
func MillisDurationConv(d int64) (ret string) {
var (
millis int64
seconds int64
mins int64
hours int64
)
//微秒
millis = (d % 1000)
//秒
seconds = (d / 1000)
if seconds > 59 {
mins = (d / 1000) / 60
seconds = seconds % 60
}
//分
if mins > 59 {
hours = (d / 1000) / 3600
mins = mins % 60
}
strHours := fmt.Sprintf("%02d", hours)
strMins := fmt.Sprintf("%02d", mins)
strSeconds := fmt.Sprintf("%02d", seconds)
strMills := fmt.Sprintf("%03d", millis)
return strHours + ":" + strMins + ":" + strSeconds + "," + strMills
}
func DurationConv(src *duration.Duration) string {
var (
millis int64
seconds int64
mins int64
hours int64
)
millis = int64(src.Nanos) / 1000 / 1000
d := src.Seconds
seconds = d
if seconds > 59 {
mins = d / 60
seconds = seconds % 60
}
//分
if mins > 59 {
hours = d / 3600
mins = mins % 60
}
strHours := fmt.Sprintf("%02d", hours)
strMins := fmt.Sprintf("%02d", mins)
strSeconds := fmt.Sprintf("%02d", seconds)
strMills := fmt.Sprintf("%03d", millis)
return strHours + ":" + strMins + ":" + strSeconds + "," + strMills
}
| true
|
73d29ea3aa3c51514906218241050c25ec020b88
|
Go
|
pranavgore09/wit-on-minishift
|
/remoteworkitem/trackerquery_repository_test.go
|
UTF-8
| 6,423
| 2.65625
| 3
|
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package remoteworkitem
import (
"net/http"
"net/url"
"testing"
"context"
errs "github.com/fabric8-services/fabric8-wit/errors"
"github.com/fabric8-services/fabric8-wit/gormsupport/cleaner"
"github.com/fabric8-services/fabric8-wit/gormtestsupport"
"github.com/fabric8-services/fabric8-wit/resource"
"github.com/fabric8-services/fabric8-wit/space"
uuid "github.com/satori/go.uuid"
"github.com/goadesign/goa"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
)
type TestTrackerQueryRepository struct {
gormtestsupport.DBTestSuite
trackerRepo TrackerRepository
queryRepo TrackerQueryRepository
clean func()
}
func TestRunTrackerQueryRepository(t *testing.T) {
suite.Run(t, &TestTrackerQueryRepository{DBTestSuite: gormtestsupport.NewDBTestSuite("../config.yaml")})
}
func (test *TestTrackerQueryRepository) SetupTest() {
test.trackerRepo = NewTrackerRepository(test.DB)
test.queryRepo = NewTrackerQueryRepository(test.DB)
test.clean = cleaner.DeleteCreatedEntities(test.DB)
}
func (test *TestTrackerQueryRepository) TearDownTest() {
test.clean()
}
func (test *TestTrackerQueryRepository) TestTrackerQueryCreate() {
t := test.T()
resource.Require(t, resource.Database)
req := &http.Request{Host: "localhost"}
params := url.Values{}
ctx := goa.NewContext(context.Background(), nil, req, params)
query, err := test.queryRepo.Create(ctx, "abc", "xyz", uuid.NewV4(), space.SystemSpace)
assert.IsType(t, InternalError{}, err)
assert.Nil(t, query)
tracker := Tracker{
URL: "http://issues.jboss.com",
Type: ProviderJira,
}
err = test.trackerRepo.Create(ctx, &tracker)
query, err = test.queryRepo.Create(ctx, "abc", "xyz", tracker.ID, space.SystemSpace)
assert.Nil(t, err)
assert.Equal(t, "abc", query.Query)
assert.Equal(t, "xyz", query.Schedule)
query2, err := test.queryRepo.Load(ctx, query.ID)
assert.Nil(t, err)
assert.Equal(t, query, query2)
}
func (test *TestTrackerQueryRepository) TestExistsTrackerQuery() {
t := test.T()
resource.Require(t, resource.Database)
t.Run("tracker query exists", func(t *testing.T) {
t.Parallel()
// given
req := &http.Request{Host: "localhost"}
params := url.Values{}
ctx := goa.NewContext(context.Background(), nil, req, params)
tracker := Tracker{
URL: "http://issues.jboss.com",
Type: ProviderJira,
}
err := test.trackerRepo.Create(ctx, &tracker)
assert.Nil(t, err)
query, err := test.queryRepo.Create(ctx, "abc", "xyz", tracker.ID, space.SystemSpace)
assert.Nil(t, err)
err = test.queryRepo.CheckExists(ctx, query.ID)
assert.Nil(t, err)
})
t.Run("tracker query doesn't exist", func(t *testing.T) {
t.Parallel()
req := &http.Request{Host: "localhost"}
params := url.Values{}
ctx := goa.NewContext(context.Background(), nil, req, params)
err := test.queryRepo.CheckExists(ctx, "11111111111")
require.IsType(t, errs.NotFoundError{}, err)
})
}
func (test *TestTrackerQueryRepository) TestTrackerQuerySave() {
t := test.T()
resource.Require(t, resource.Database)
req := &http.Request{Host: "localhost"}
params := url.Values{}
ctx := goa.NewContext(context.Background(), nil, req, params)
query, err := test.queryRepo.Load(ctx, "abcd")
assert.IsType(t, NotFoundError{}, err)
assert.Nil(t, query)
tracker := Tracker{
URL: "http://issues.jboss.com",
Type: ProviderJira,
}
err = test.trackerRepo.Create(ctx, &tracker)
tracker2 := Tracker{
URL: "http://api.github.com",
Type: ProviderGithub,
}
err = test.trackerRepo.Create(ctx, &tracker2)
query, err = test.queryRepo.Create(ctx, "abc", "xyz", tracker.ID, space.SystemSpace)
query2, err := test.queryRepo.Load(ctx, query.ID)
assert.Nil(t, err)
assert.Equal(t, query, query2)
query.Query = "after"
query.Schedule = "the"
query.TrackerID = tracker2.ID
if err != nil {
t.Errorf("could not convert id: %s", tracker2.ID)
}
query2, err = test.queryRepo.Save(ctx, *query)
assert.Nil(t, err)
assert.Equal(t, query, query2)
err = test.trackerRepo.Delete(ctx, uuid.NewV4())
assert.NotNil(t, err)
query.TrackerID = uuid.NewV4()
query2, err = test.queryRepo.Save(ctx, *query)
assert.IsType(t, InternalError{}, err)
assert.Nil(t, query2)
}
func (test *TestTrackerQueryRepository) TestTrackerQueryDelete() {
t := test.T()
resource.Require(t, resource.Database)
req := &http.Request{Host: "localhost"}
params := url.Values{}
ctx := goa.NewContext(context.Background(), nil, req, params)
err := test.queryRepo.Delete(ctx, "asdf")
assert.IsType(t, NotFoundError{}, err)
tracker := Tracker{
URL: "http://api.github.com",
Type: ProviderGithub,
}
err = test.trackerRepo.Create(ctx, &tracker)
tq, _ := test.queryRepo.Create(ctx, "is:open is:issue user:arquillian author:aslakknutsen", "15 * * * * *", tracker.ID, space.SystemSpace)
err = test.queryRepo.Delete(ctx, tq.ID)
assert.Nil(t, err)
tq, err = test.queryRepo.Load(ctx, tq.ID)
assert.IsType(t, NotFoundError{}, err)
assert.Nil(t, tq)
tq, err = test.queryRepo.Load(ctx, "100000")
assert.IsType(t, NotFoundError{}, err)
assert.Nil(t, tq)
}
func (test *TestTrackerQueryRepository) TestTrackerQueryList() {
t := test.T()
resource.Require(t, resource.Database)
req := &http.Request{Host: "localhost"}
params := url.Values{}
ctx := goa.NewContext(context.Background(), nil, req, params)
trackerqueries1, _ := test.queryRepo.List(ctx)
tracker1 := Tracker{
URL: "http://api.github.com",
Type: ProviderGithub,
}
err := test.trackerRepo.Create(ctx, &tracker1)
assert.Nil(t, err)
test.queryRepo.Create(ctx, "is:open is:issue user:arquillian author:aslakknutsen", "15 * * * * *", tracker1.ID, space.SystemSpace)
test.queryRepo.Create(ctx, "is:close is:issue user:arquillian author:aslakknutsen", "15 * * * * *", tracker1.ID, space.SystemSpace)
tracker2 := Tracker{
URL: "http://issues.jboss.com",
Type: ProviderJira,
}
err = test.trackerRepo.Create(ctx, &tracker2)
assert.Nil(t, err)
test.queryRepo.Create(ctx, "project = ARQ AND text ~ 'arquillian'", "15 * * * * *", tracker2.ID, space.SystemSpace)
test.queryRepo.Create(ctx, "project = ARQ AND text ~ 'javadoc'", "15 * * * * *", tracker2.ID, space.SystemSpace)
trackerqueries2, _ := test.queryRepo.List(ctx)
assert.Equal(t, len(trackerqueries1)+4, len(trackerqueries2))
trackerqueries3, _ := test.queryRepo.List(ctx)
assert.Equal(t, trackerqueries2[1], trackerqueries3[1])
}
| true
|
48f1660cc40e158e3cd40cd1aafca99b5050316e
|
Go
|
badgerodon/collections
|
/tuples.go
|
UTF-8
| 253
| 3.421875
| 3
|
[
"Unlicense"
] |
permissive
|
[
"Unlicense"
] |
permissive
|
package collections
// A Pair is a pair of values.
type Pair[T1, T2 any] struct {
First T1
Second T2
}
// NewPair creates a new Pair.
func NewPair[T1, T2 any](first T1, second T2) Pair[T1, T2] {
return Pair[T1, T2]{First: first, Second: second}
}
| true
|
a52f26852300183a2ac2e8e037c983ce13cb7e66
|
Go
|
yuankunluo/algo-leetcode
|
/0-299/0004.median-of-two-sorted-arrays/median-of-two-sorted-arrays_test.go
|
UTF-8
| 434
| 2.84375
| 3
|
[] |
no_license
|
[] |
no_license
|
package problem0004
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
var testCases = []struct {
n1 []int
n2 []int
median float64
}{
{
n1: []int{1, 2},
n2: []int{3, 4},
median: 2.5,
},
}
func TestFindMeianSortedArrays(t *testing.T) {
ast := assert.New(t)
for _, tc := range testCases {
ans := findMedianSortedArrays(tc.n1, tc.n2)
fmt.Println(ans)
ast.Equal(tc.median, ans)
}
}
| true
|
73d1516d9ba23d072486d0fe3c54108c0008992f
|
Go
|
paulusrobin/go-memory-cache
|
/memory-cache/data.go
|
UTF-8
| 3,098
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package memory_cache
import (
"fmt"
sigar "github.com/cloudfoundry/gosigar"
"github.com/paulusrobin/go-memory-cache/logs"
"github.com/pkg/errors"
"reflect"
"sync"
"time"
)
var tooManyKeysInvoked = "Too many keys invoked"
var windowsTooLarge = "Windows too large"
var valueTooLarge = "Entry value too large"
var memoryExceed = "Memory exceed"
type cache struct {
option Option
mu sync.Mutex
log logs.Logger
data map[string]interface{}
queue []string
size uintptr
}
func (c *cache) Set(key string, value interface{}, ttl time.Duration) error {
c.mu.Lock()
defer c.mu.Unlock()
newItemSize := c.getSize(value)
if newItemSize > uintptr(c.option.MaxEntrySize) {
return errors.New(valueTooLarge)
}
for {
if c.size+newItemSize > uintptr(c.option.MaxEntriesInWindow) {
c.forceRemove(c.queue[0], windowsTooLarge)
} else {
break
}
}
if len(c.data) >= c.option.MaxEntriesKey {
c.forceRemove(c.queue[0], tooManyKeysInvoked)
}
c.data[key] = value
c.queue = append(c.queue, key)
c.size += newItemSize
time.AfterFunc(ttl, func() { _ = c.Remove(key) })
return nil
}
func (c *cache) Get(key string) (interface{}, error) {
c.mu.Lock()
defer c.mu.Unlock()
if value, ok := c.data[key]; ok {
return value, nil
}
return nil, errors.New(fmt.Sprintf("key %s is not found", key))
}
func (c *cache) Remove(key string) error {
data, err := c.Get(key)
if err != nil {
return errors.WithStack(err)
}
c.mu.Lock()
defer c.mu.Unlock()
delete(c.data, key)
c.removeQueue()
if c.option.OnRemove != nil {
c.option.OnRemove(key, data)
}
return nil
}
func (c *cache) Truncate() error {
c.mu.Lock()
defer c.mu.Unlock()
for key := range c.data {
delete(c.data, key)
c.removeQueue()
}
return nil
}
func (c *cache) Len() int {
c.mu.Lock()
defer c.mu.Unlock()
return len(c.data)
}
func (c *cache) Size() uintptr {
c.mu.Lock()
defer c.mu.Unlock()
return c.size
}
func (c *cache) forceRemove(key string, reason string) {
delete(c.data, key)
c.removeQueue()
if c.option.OnRemoveWithReason != nil {
c.option.OnRemoveWithReason(key, reason)
}
}
func (c *cache) removeQueue() {
if len(c.queue) > 1 {
sizeItemToRemove := c.getSize(c.queue[0])
c.queue = c.queue[1:len(c.queue)]
c.size -= sizeItemToRemove
} else {
c.queue = make([]string, 0)
c.size = 0
}
}
func (c *cache) getSize(T interface{}) uintptr {
return reflect.TypeOf(T).Size()
}
func (c *cache) Cleaner(duration time.Duration, done <-chan bool) {
tick := time.Tick(duration)
for {
select {
case <-tick:
mem := sigar.Mem{}
if err := mem.Get(); err != nil {
c.log.Errorf("error get memory = ", err.Error())
break
}
percentageUsed := float64(mem.ActualUsed) / float64(mem.Total) * 100
if percentageUsed > c.option.MaxPercentageMemory {
if c.option.OnMemoryExceed != nil {
c.option.OnMemoryExceed(percentageUsed, c.option.MaxPercentageMemory, float64(mem.ActualUsed))
}
if len(c.queue) > 0 {
_ = c.Truncate()
}
}
case <-done:
return
}
}
}
func (c *cache) Keys() []string {
return c.queue
}
| true
|
234f3d40e633ef0102f6a6745d97035ce9cedcf5
|
Go
|
serverwentdown/huge-piano
|
/keymap.go
|
UTF-8
| 1,133
| 3.21875
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package main
import (
"encoding/csv"
"log"
"os"
"strconv"
)
type keymap struct {
changes chan stateFlip
mapped map[int]int
play chan int
}
func (k *keymap) load(file string) {
f, err := os.Open(file)
if err != nil {
panic(err)
}
r := csv.NewReader(f)
mapping, err := r.ReadAll()
if err != nil {
panic(err)
}
k.mapped = make(map[int]int)
for _, m := range mapping {
key, err := strconv.Atoi(m[0])
if err != nil {
panic(err)
}
value, err := strconv.Atoi(m[1])
if err != nil {
panic(err)
}
k.mapped[key] = value
}
}
func (k *keymap) lookup(key stateFlip) int {
value, has := k.mapped[key.i]
if !has {
log.Printf("key %d not found", key.i)
return -1
}
return value
}
func (k *keymap) watch() {
log.Println("Awaiting stateFlips...")
for key := range k.changes {
play := k.lookup(key)
if play >= 0 {
log.Println(play)
k.play <- play
log.Println("change read")
}
}
log.Println("No more stateFlips")
}
func newKeymap(changes chan stateFlip, mapFile string) *keymap {
k := &keymap{
changes: changes,
play: make(chan int),
}
k.load(mapFile)
return k
}
| true
|
9c1df97d1efed4fb88a3594d6bafba40cf4a1d1a
|
Go
|
c0ff33un/taurus-game-ms
|
/protocol/client.go
|
UTF-8
| 4,441
| 2.84375
| 3
|
[] |
no_license
|
[] |
no_license
|
// Copyright 2013 The Gorilla WebSocket 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 protocol
import (
//"bytes"
"encoding/json"
"io"
"log"
"time"
"github.com/coff33un/game-server-ms/game"
"github.com/gorilla/websocket"
)
const (
// Time allowed to write a message to the peer.
writeWait = 10 * time.Second
// Time allowed to read the next pong message from the peer.
pongWait = 60 * time.Second
// Send pings to peer with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
// Maximum message size allowed from peer.
maxMessageSize = 512
)
// Client is a mIDdleman between the websocket connection and the hub.
type Client struct {
room *Room
// user ID
Id string
Handle string
Leave bool
// The websocket connection.
conn *websocket.Conn
// Buffered channel of outbound messages.
send chan interface{}
}
type message struct {
Type string `json:"type"`
}
type textMessage struct {
message
Text string `json:"text"`
}
type connectMessage struct {
message
Handle string `json:"handle"`
Length int `json:"length"`
}
func (c *Client) getLeaveMessage(length int) interface{} {
return leaveMessage{
message: message{Type: "leave"},
Handle: c.Handle,
Length: length,
}
}
type leaveMessage struct {
message
Handle string `json:"handle"`
Length int `json:"length"`
}
// readPump pumps messages from the websocket connection to the hub.
//
// The application runs readPump in a per-connection goroutine. The application
// ensures that there is at most one reader on a connection by executing all
// reads from this goroutine.
func (c *Client) ReadPump() {
log.Println("ReadPump Started")
defer func() {
log.Println("ReadPump Ended")
c.room.unregister <- c
c.conn.Close()
c.room.Done() // Anonymous WaitGroup
}()
c.conn.SetReadLimit(maxMessageSize)
c.conn.SetReadDeadline(time.Now().Add(pongWait))
c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
for {
_, message, err := c.conn.ReadMessage()
if err != nil {
log.Println("Error", err)
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("error: %v\n", err)
}
break
}
var mp map[string]interface{}
err = json.Unmarshal(message, &mp)
if err != nil {
continue
}
Type := mp["type"].(string)
switch Type {
case "message":
m := textMessage{}
json.Unmarshal(message, &m)
c.room.broadcast <- m
case "connect":
m := connectMessage{}
json.Unmarshal(message, &m)
m.Handle = c.Handle
m.Length = c.room.Length
c.room.broadcast <- m
case "move":
if c.room.Running {
m := game.ClientMoveMessage{}
json.Unmarshal(message, &m)
m.Id = c.Id
c.room.game.Update <- m
}
case "leave":
c.Leave = true
c.room.unregister <- c
}
}
}
func writeJSON(w io.WriteCloser, v interface{}) error {
err := json.NewEncoder(w).Encode(v)
return err
}
// writePump pumps messages from the hub to the websocket connection.
//
// A goroutine running writePump is started for each connection. The
// application ensures that there is at most one writer to a connection by
// executing all writes from this goroutine.
func (c *Client) WritePump() {
log.Println("WritePump Started")
ticker := time.NewTicker(pingPeriod)
defer func() {
log.Println("WritePump Ended")
ticker.Stop()
c.conn.Close()
c.room.Done() // Anonymous WaitGroup
}()
for {
select {
case message, ok := <-c.send:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if !ok {
// The hub closed the channel.
log.Println("The hub closed the channel")
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
//common.PrintJSON(message.(map[string]interface{}))
w, err := c.conn.NextWriter(websocket.TextMessage) // Uses this instead of c.conn.WriteJSON to reuse Writer
if err != nil {
return
}
writeJSON(w, message)
// Add queued chat messages to the current websocket message.
n := len(c.send)
for i := 0; i < n; i++ {
writeJSON(w, <-c.send)
}
if err := w.Close(); err != nil {
return
}
case <-ticker.C:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
}
| true
|
bef7c76c991dc2e767c5bcd97e1bbadddd6b4039
|
Go
|
ispiroglu/YTU-ITC-Algorithms-in-Go
|
/Algorithms - ITC/16 - Symetric Matrix Checker/symmetricMatrix.go
|
UTF-8
| 711
| 3.890625
| 4
|
[] |
no_license
|
[] |
no_license
|
//An algorithm that checks the martix is symetric or not.
package main
import "fmt"
func main() {
var n int
var matrix [50][50]int
fmt.Println("For checking symetry, Matrix must be a square matrix.")
fmt.Println("Please enter the dimenson of matrix.")
fmt.Scan(&n)
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
fmt.Println("Please enter the", i+1, ". row,", j+1, "column value.")
fmt.Scan(&matrix[i][j])
}
}
i := 0
symetric := 1
for i < (n-1) && symetric == 1 {
j := i + 1
for j < n && symetric == 1 {
if matrix[i][j] != matrix[j][i] {
symetric = 0
}
j++
}
i++
}
if symetric == 1 {
fmt.Println("Symetric.")
} else {
fmt.Println("Not symetric.")
}
}
| true
|
502f396913ca30cebfbd8df372bdaa30a7d1912f
|
Go
|
mh-cbon/mdl-go-components
|
/components/pagination.go
|
UTF-8
| 2,809
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package components
import (
"math"
"net/url"
"strconv"
mgc "github.com/mh-cbon/mdl-go-components"
base "github.com/mh-cbon/mdl-go-components/components_common"
)
type Pagination struct {
mgc.ViewComponent
base.Node
BtPrev *Button
BtNext *Button
Select *Select
GoToText string
BaseUrl *url.URL
PageParamName string
CurrentPage uint64
PageCnt uint64
}
func NewPagination() *Pagination {
ret := &Pagination{}
ret.SetBlock("mgc/pagination")
ret.BtPrev = NewSubmit()
ret.BtPrev.SetIcon("keyboard_arrow_left")
ret.BtNext = NewSubmit()
ret.BtNext.SetIcon("keyboard_arrow_right")
ret.Select = NewSelect()
ret.Select.UpdateWindowUrl(true)
return ret
}
func (view *Pagination) SetBaseUrl(u *url.URL) {
view.BaseUrl = u
view.GuessCurrentPage()
}
func (view *Pagination) SetPageParamName(s string) {
view.PageParamName = s
}
func (view *Pagination) HasPreviousPage() bool {
return view.CurrentPage > 1
}
func (view *Pagination) HasNextPage() bool {
return view.CurrentPage < view.GetPagesCnt()
}
func (view *Pagination) GuessCurrentPage() {
q := view.BaseUrl.Query()
view.CurrentPage = uint64(1)
if x := q.Get(view.PageParamName); x != "" {
i, err := strconv.Atoi(x)
if err != nil {
panic(err)
}
view.CurrentPage = uint64(i)
}
}
func (view *Pagination) SetPagesCnt(limit uint64, total uint64) {
view.PageCnt = 1
if total >= 2 {
view.PageCnt = uint64(math.Ceil(float64(total) / float64(limit)))
}
}
func (view *Pagination) GetPagesCnt() uint64 {
return view.PageCnt
}
func (view *Pagination) GetUrl(p string) string {
q := view.BaseUrl.Query()
q.Set(view.PageParamName, p)
view.BaseUrl.RawQuery = q.Encode()
return view.BaseUrl.String()
}
func (view *Pagination) SetTotalItemCount(limit uint64, total uint64) {
view.SetPagesCnt(limit, total)
for i := uint64(1); i <= view.PageCnt; i++ {
p := strconv.FormatUint(i, 10)
view.Select.AddOption(view.GetUrl(p), p)
}
view.Select.SetValue(view.GetUrl(strconv.FormatUint(view.CurrentPage, 10)))
view.BtPrev.SetDisabled(!view.HasPreviousPage())
view.BtNext.SetDisabled(!view.HasNextPage())
view.BtPrev.SetLink("#")
view.BtNext.SetLink("#")
if view.HasPreviousPage() {
view.BtPrev.SetLink(view.GetUrl(strconv.FormatUint(view.CurrentPage-1, 10)))
}
if view.HasNextPage() {
view.BtNext.SetLink(view.GetUrl(strconv.FormatUint(view.CurrentPage+1, 10)))
}
}
func (view *Pagination) Translate(t base.Translator) {
view.BtPrev.Translate(t)
view.BtNext.Translate(t)
view.Select.Translate(t)
}
func (view *Pagination) Render(args ...interface{}) (string, error) {
view.GetRenderContext().AttachTo(view.BtPrev)
view.GetRenderContext().AttachTo(view.BtNext)
view.GetRenderContext().AttachTo(view.Select)
return view.GetRenderContext().RenderComponent(view, args)
}
| true
|
9a0e458f8e8f7dfc250dd9a41ccbf3d5cd5ab656
|
Go
|
edmondlafay/advent_2019
|
/15/solution.go
|
UTF-8
| 7,488
| 3.28125
| 3
|
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"math"
"strings"
"strconv"
"io/ioutil"
)
const ADD, MULTIPLY, GET, PUT, JUMPIF, JUMPUNLESS, LOWERTHAN, EQUALTO, CHANGEREL, HALT int = 1, 2, 3, 4, 5, 6, 7, 8, 9, 99
func check(e error) {
if e != nil { panic(e) }
}
func ArrayStoArrayI(t []string) []int {
var t2 = []int{}
for _, i := range t {
if len(i)>0 {
j, err := strconv.Atoi(i)
check(err)
t2 = append(t2, j)
}
}
return t2
}
func replaceAtIndex(in string, r rune, i int) string {
out := []rune(in)
out[i] = r
return string(out)
}
func get_params(memory map[int]int, i int, length int, modes int, relative_base int) []int {
params := make([]int, 0)
for j:=0; j < length-1; j++ {
mode := (modes/int(math.Pow10(j)))%10
absolute, direct, relative := 0, 1, 2
switch mode {
case absolute: params = append(params, memory[i+j+1])
case direct: params = append(params, i+j+1)
case relative: params = append(params, relative_base+memory[i+j+1])
default: panic(fmt.Sprintf("Error: compute has an invalid mode %d (modes: %d).\n", mode, modes))
}
}
return params
}
func compute(input_data []int, input chan int, output chan int, number int) {
memory := make(map[int]int)
for memory_position, memory_order := range input_data {
memory[memory_position] = memory_order
}
relative_base, i, length := 0, 0, 0
for i < len(memory) {
action, modes := memory[i]%100 , memory[i]/100
var params []int
switch action {
case ADD:
length = 4
params = get_params(memory, i, length, modes, relative_base)
memory[params[2]] = memory[params[1]] + memory[params[0]]
case MULTIPLY:
length = 4
params = get_params(memory, i, length, modes, relative_base)
memory[params[2]] = memory[params[1]] * memory[params[0]]
case GET:
length = 2
params = get_params(memory, i, length, modes, relative_base)
memory[params[0]] = <-input
case PUT:
length = 2
params = get_params(memory, i, length, modes, relative_base)
output <- memory[params[0]]
case JUMPIF:
length = 3
params = get_params(memory, i, length, modes, relative_base)
if memory[params[0]]!=0 {
i=memory[params[1]]
continue
}
case JUMPUNLESS:
length = 3
params = get_params(memory, i, length, modes, relative_base)
if memory[params[0]]==0 {
i=memory[params[1]]
continue
}
case LOWERTHAN:
length = 4
params = get_params(memory, i, length, modes, relative_base)
if memory[params[0]]<memory[params[1]] { memory[params[2]]=1 } else { memory[params[2]]=0 }
case EQUALTO:
length = 4
params = get_params(memory, i, length, modes, relative_base)
if memory[params[0]]==memory[params[1]] { memory[params[2]]=1 } else { memory[params[2]]=0 }
case CHANGEREL:
length = 2
params = get_params(memory, i, length, modes, relative_base)
relative_base += memory[params[0]]
case HALT:
close(output)
return
default:
panic(fmt.Sprintf("Error: compute has an invalid action %d.\n", action))
}
i += length
}
}
func printCanvas(canvas map[[2]int]string, start_x, start_y, end_x, end_y, minX, minY, maxX, maxY, step int) {
fmt.Printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n%d\n", step)
for y:=minY; y< maxY; y++ {
for x:=minX; x< maxX; x++ {
if x==start_x && y==start_y {
fmt.Printf("£")
} else if x==end_x && y==end_y {
fmt.Printf("$")
} else if known_position, ok := canvas[[2]int{x,y}]; ok {
fmt.Printf("%s", known_position)
} else {
fmt.Printf(" ")
}
}
fmt.Printf("\n")
}
}
func chooseDirection (canvas map[[2]int]string, input_chan chan int, x, y int) (next_x, next_y, next_movement int) {
switch canvas[[2]int{x, y}] {
case "<":
if canvas[[2]int{x, y+1}] != "#" {
next_x, next_y = x, y+1
next_movement = 2
return
} else {
canvas[[2]int{x, y}] = "^"
return chooseDirection(canvas, input_chan, x, y)
}
case "^":
if canvas[[2]int{x-1, y}] != "#" {
next_x, next_y = x-1, y
next_movement = 3
return
} else {
canvas[[2]int{x, y}] = ">"
return chooseDirection(canvas, input_chan, x, y)
}
case ">":
if canvas[[2]int{x, y-1}] != "#" {
next_x, next_y = x, y-1
next_movement = 1
return
} else {
canvas[[2]int{x, y}] = "v"
return chooseDirection(canvas, input_chan, x, y)
}
case "v":
if canvas[[2]int{x+1, y}] != "#" {
next_x, next_y = x+1, y
next_movement = 4
return
} else {
canvas[[2]int{x, y}] = "<"
return chooseDirection(canvas, input_chan, x, y)
}
}
return x, y, 1
}
func propagate(canvas map[[2]int]string, x, y int) int{
time := 0
propagated := false
if canvas[[2]int{x-1,y}] == "." {
canvas[[2]int{x-1,y}] = "O"
propagated = true
tmp := propagate(canvas, x-1,y)
if tmp > time { time = tmp }
}
if canvas[[2]int{x+1,y}] == "." {
canvas[[2]int{x+1,y}] = "O"
propagated = true
tmp := propagate(canvas, x+1,y)
if tmp > time { time = tmp }
}
if canvas[[2]int{x,y-1}] == "." {
canvas[[2]int{x,y-1}] = "O"
propagated = true
tmp := propagate(canvas, x,y-1)
if tmp > time { time = tmp }
}
if canvas[[2]int{x,y+1}] == "." {
canvas[[2]int{x,y+1}] = "O"
propagated = true
tmp := propagate(canvas, x, y+1)
if tmp > time { time = tmp }
}
if propagated {
time++
}
return time
}
func main() {
file, err := ioutil.ReadFile("input.txt")
check(err)
canvas := make(map[[2]int]string)
input_chan := make(chan int)
output_chan := make(chan int)
go compute(ArrayStoArrayI(strings.Split(string(file), ",")), input_chan, output_chan, 0)
start_x,start_y,minX,minY,maxX,maxY,step:=40,25,0,0,80,50,0
x,y := start_x,start_y
movements := "^v<>"
canvas[[2]int{x,y}] = "<"
// go down
next_x, next_y := x+1, y
next_movement := 4
keep_going := true
for keep_going {
input_chan <- next_movement
if step%100==0 { printCanvas(canvas, start_x, start_y, start_x-20, start_y-12, minX, minY, maxX, maxY, step) }
output := <- output_chan
switch output {
case 0:
canvas[[2]int{next_x, next_y}] = "#"
case 1:
canvas[[2]int{next_x, next_y}] = string(movements[next_movement-1])
canvas[[2]int{x, y}] = "."
x, y=next_x, next_y
case 2:
canvas[[2]int{next_x, next_y}] = string(movements[next_movement-1])
canvas[[2]int{x, y}] = "."
x, y=next_x, next_y
// canvas[[2]int{next_x, next_y}] = "$"
// keep_going = false
}
if step==3000 { keep_going = false }
if keep_going {
next_x, next_y, next_movement = chooseDirection (canvas, input_chan, x, y)
step++
}
}
printCanvas(canvas, start_x, start_y, start_x-20, start_y-12, minX, minY, maxX, maxY, step)
canvas[[2]int{x, y}] = "."
canvas[[2]int{start_x, start_y}] = "."
canvas[[2]int{start_x-20, start_y-12}] = "O"
res2 := propagate(canvas, start_x-20, start_y-12)
printCanvas(canvas, start_x, start_y, start_x-20, start_y-12, minX, minY, maxX, maxY, step)
fmt.Printf("RESULT 2: %d\n\n", res2)
}
| true
|
390563ff4b7599569ca808450b3f06ff26e1551f
|
Go
|
adrg/unipdf-examples
|
/redact/redact_text.go
|
UTF-8
| 2,353
| 2.890625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
[
"BSD-3-Clause"
] |
permissive
|
/*
* Redact text: Redacts text that match given regexp patterns on a PDF document.
*
* Run as: go run redact_text.go input.pdf output.pdf
*/
package main
import (
"fmt"
"os"
"regexp"
"github.com/unidoc/unipdf/v3/common/license"
"github.com/unidoc/unipdf/v3/creator"
"github.com/unidoc/unipdf/v3/model"
"github.com/unidoc/unipdf/v3/redactor"
)
func init() {
// Make sure to load your metered License API key prior to using the library.
// If you need a key, you can sign up and create a free one at https://cloud.unidoc.io
err := license.SetMeteredKey(os.Getenv(`UNIDOC_LICENSE_API_KEY`))
if err != nil {
panic(err)
}
}
func main() {
if len(os.Args) < 3 {
fmt.Printf("Usage: go run redact_text.go inputFile.pdf outputFile.pdf \n")
os.Exit(1)
}
inputFile := os.Args[1]
outputFile := os.Args[2]
// List of regex patterns and replacement strings
patterns := []string{
// Regex for matching credit card number.
`(^|\s+)(\d{4}[ -]\d{4}[ -]\d{4}[ -]\d{4})(?:\s+|$)`,
// Regex for matching emails.
`[a-zA-Z0-9\.\-+_]+@[a-zA-Z0-9\.\-+_]+\.[a-z]+`,
}
// Initialize the RectangleProps object.
rectProps := &redactor.RectangleProps{
FillColor: creator.ColorBlack,
BorderWidth: 0.0,
FillOpacity: 1.0,
}
err := redactText(patterns, rectProps, inputFile, outputFile)
if err != nil {
panic(err)
}
fmt.Println("successfully redacted.")
}
// redactText redacts the text in `inputFile` according to given patterns and saves result at `outputFile`.
func redactText(patterns []string, rectProps *redactor.RectangleProps, inputFile, destFile string) error {
// Initialize RedactionTerms with regex patterns.
terms := []redactor.RedactionTerm{}
for _, pattern := range patterns {
regexp, err := regexp.Compile(pattern)
if err != nil {
panic(err)
}
redTerm := redactor.RedactionTerm{Pattern: regexp}
terms = append(terms, redTerm)
}
pdfReader, f, err := model.NewPdfReaderFromFile(inputFile, nil)
if err != nil {
panic(err)
}
defer f.Close()
// Define RedactionOptions.
options := redactor.RedactionOptions{Terms: terms}
red := redactor.New(pdfReader, &options, rectProps)
if err != nil {
return err
}
err = red.Redact()
if err != nil {
return err
}
// write the redacted document to destFile.
err = red.WriteToFile(destFile)
if err != nil {
return err
}
return nil
}
| true
|
7fe8b586eb7c4eee0b85a8cfa96cda06b1cb1142
|
Go
|
xiaolong26/gotest
|
/test/test.go
|
UTF-8
| 1,579
| 2.921875
| 3
|
[] |
no_license
|
[] |
no_license
|
package test
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
//"google.golang.org/appengine/log"
//"time"
)
type User struct {
Id int `db:"id"`
Username string `db:"username"` //由于在mysql的users表中name没有设置为NOT NULL,所以name可能为null,在查询过程中会返回nil,如果是string类型则无法接收nil,但sql.NullString则可以接收nil值
Passwd string `db:"string"`
}
var DB *sql.DB
func init(){
var err error
DB, err = sql.Open("mysql", "gotest:123456@tcp(127.0.0.1:3306)/gotest?charset=utf8")
if err != nil{
fmt.Println(err)
}
/*var err error
for i := 1; i <= 64; i <<= 1 {
DB, err = sql.Open("mysql","gotest:123456@tcp(127.0.0.1:3306)/gotest?charset=utf8" )
if err != nil {
//log.Errorf("Connect %s failed: %s; on...: %v","gotest:123456@tcp(127.0.0.1:3306)/gotest?charset=utf8", err, i)
time.Sleep(time.Second * time.Duration(i))
continue
} else {
break
}
}
DB.SetMaxOpenConns(0)
DB.SetMaxIdleConns(0)
for i := 1; i <= 64; i <<= 1 {
if err := DB.Ping(); err != nil {
//log.Errorf("Connect %s fatal %s", "gotest:123456@tcp(127.0.0.1:3306)/gotest?charset=utf8", err)
time.Sleep(time.Second * time.Duration(i))
continue
} else {
break
}
}*/
}
func Query(DB *sql.DB) (int,string,string) {
var user User
rows,err := DB.Query("select id,username,passwd from user ")
if err != nil{
fmt.Println(err)
}
for rows.Next(){
rows.Scan(&user.Id,&user.Username,&user.Passwd)
//fmt.Println(id,name,age)
}
rows.Close()
return user.Id,user.Username,user.Passwd
}
| true
|
ccf65c860be7195c5c986626244f912c5b32583f
|
Go
|
zombor/logger
|
/http/handler_test.go
|
UTF-8
| 656
| 2.75
| 3
|
[] |
no_license
|
[] |
no_license
|
package main
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/zombor/logger/Godeps/_workspace/src/github.com/stretchr/testify/assert"
)
func Test_handlerHandle_SendsReqBody_ToWorkQueue(t *testing.T) {
jsonInput := map[string]string{
"message": "hello world",
}
body := new(bytes.Buffer)
json.NewEncoder(body).Encode(jsonInput)
request, _ := http.NewRequest("POST", "/", body)
response := httptest.NewRecorder()
workQueue := make(chan string, 1)
handler{workQueue: workQueue}.CreateLog(response, request)
passedBody := <-workQueue
assert.Equal(t, "{\"message\":\"hello world\"}\n", passedBody)
}
| true
|
fa6f10af5c1c808f84709140ee2666074a0a72d4
|
Go
|
w1r2p1/peernotify
|
/core/tokens/tokens.go
|
UTF-8
| 4,843
| 2.796875
| 3
|
[] |
no_license
|
[] |
no_license
|
package tokens
import (
"bytes"
"crypto/rand"
"crypto/sha256"
"errors"
"math"
"path"
"github.com/mrwhythat/peernotify/storage"
)
//------------------------------------------------------------------------------
// Model
type Token struct {
OneTimeKey []byte
UserIdKey []byte
UserSecret []byte
}
type TokenManager interface {
// Returns binary representation of the set of keys and ID key
// which can be used to index keyset in storage
NewKeyset() ([]byte, []byte, error)
// Returns ID key of the keyset that generated given token
Generator(tokenBytes []byte) ([]byte, error)
}
type PeernotifyClient interface {
// Generate new token based on the keyset
NewToken() ([]byte, error)
}
const (
IDSize = 8
KeySize = 32
MaskSize = 32
TokenSize = 40
MaxTokens = math.MaxInt16
)
var (
RandError = errors.New("Ur randomz numbez iz broken, mate!")
IncorrectTokenError = errors.New("Incorrect token")
)
//------------------------------------------------------------------------------
// Simple token manager implementation
type simpleTokenManager struct {
keys storage.Storage
tokens storage.Storage
}
func NewTokenManager(storeDir string) (TokenManager, error) {
keys, err := storage.NewStorage(path.Join(storeDir, "peernotify.keys"))
if err != nil {
return nil, err
}
tokens, err := storage.NewStorage(path.Join(storeDir, "peernotify.tokens"))
if err != nil {
return nil, err
}
return &simpleTokenManager{keys: keys, tokens: tokens}, nil
}
func (tm *simpleTokenManager) NewKeyset() ([]byte, []byte, error) {
id := make([]byte, IDSize)
if _, err := rand.Read(id); err != nil {
return nil, nil, RandError
}
key := make([]byte, KeySize)
if _, err := rand.Read(key); err != nil {
return nil, nil, RandError
}
mask := make([]byte, MaskSize)
if _, err := rand.Read(mask); err != nil {
return nil, nil, RandError
}
rootKeyset := append(key, mask...)
if err := tm.keys.Store(id, rootKeyset); err != nil {
return nil, nil, err
}
return id, append(id, rootKeyset...), nil
}
func (tm *simpleTokenManager) Generator(tokenBytes []byte) ([]byte, error) {
// Break raw token bytes into ID and token data
id, token := tokenBytes[:IDSize], tokenBytes[IDSize:]
// fmt.Printf(`
// vid: %s
// `, base58.Encode(id))
// Get root keyset for ID
rootKeyset, err := tm.keys.Get(id)
if err != nil {
return nil, err
}
// Get token set for ID
rawTokenSet, err := tm.tokens.Get(id)
if err != nil {
return nil, err
}
tokenSet := NewTokenSet(rawTokenSet)
// Break root keyset into pieces
var (
key [KeySize]byte
mask [MaskSize]byte
link [MaskSize]byte
)
// Check token
copy(key[:], rootKeyset[:KeySize])
copy(mask[:], rootKeyset[KeySize:])
// fmt.Printf(`
// vkey: %s
// vmask: %s
// `, base58.Encode(key[:]), base58.Encode(mask[:]))
xorBytes(link[:], key[:], mask[:])
var found bool
for i := 0; i < MaxTokens; i++ {
key = sha256.Sum256(key[:])
mask = sha256.Sum256(mask[:])
xorBytes(link[:], key[:], mask[:])
if bytes.Equal(link[:], token) {
if tokenSet.GetAt(i) {
return nil, IncorrectTokenError
}
tokenSet = tokenSet.AddAt(i)
found = true
break
}
}
// Remove used tokens from token set
copy(key[:], rootKeyset[:KeySize])
copy(mask[:], rootKeyset[KeySize:])
xorBytes(link[:], key[:], mask[:])
var i int
for i = 0; tokenSet.GetAt(i); i++ {
key = sha256.Sum256(key[:])
mask = sha256.Sum256(mask[:])
xorBytes(link[:], key[:], mask[:])
}
// Save new root keyset and tokenset
tm.keys.Store(id, append(key[:], mask[:]...))
tm.tokens.Store(id, tokenSet.DropUntil(i))
// Return ID of the generator
if found {
return id, nil
} else {
return nil, IncorrectTokenError
}
}
func xorBytes(dst, a, b []byte) int {
n := len(a)
if len(b) < n {
n = len(b)
}
for i := 0; i < n; i++ {
dst[i] = a[i] ^ b[i]
}
return n
}
//------------------------------------------------------------------------------
// Simple client implementation
type simpleClient struct {
keyset []byte
}
func NewPeernotifyClient(keyset []byte) (PeernotifyClient, error) {
return &simpleClient{keyset: keyset}, nil
}
func (client *simpleClient) NewToken() ([]byte, error) {
kSet := client.keyset
keyEnd := IDSize + KeySize
id, key, mask := kSet[:IDSize], kSet[IDSize:keyEnd], kSet[keyEnd:]
// fmt.Printf(`
// id: %s
// key: %s
// mask: %s
// `, base58.Encode(id), base58.Encode(key), base58.Encode(mask))
newKey, newMask := sha256.Sum256(key), sha256.Sum256(mask)
// fmt.Printf(`
// new key: %s
// new mask: %s
// `, base58.Encode(newKey[:]), base58.Encode(newMask[:]))
copy(client.keyset[IDSize:keyEnd], newKey[:])
copy(client.keyset[keyEnd:], newMask[:])
token := make([]byte, TokenSize)
copy(token[:IDSize], id)
xorBytes(token[IDSize:], newKey[:], newMask[:])
return token, nil
}
| true
|
9b476a07eaba7c0103c27569fcf816c8062dbc58
|
Go
|
igncp/code-gym
|
/go/src/by_example/0-20/02-variables/variables.go
|
UTF-8
| 643
| 4.1875
| 4
|
[
"CC-BY-3.0"
] |
permissive
|
[
"CC-BY-3.0"
] |
permissive
|
package main
import "fmt"
func p(title string, value interface{}) {
fmt.Println(title, value)
}
func main() {
var a string = "initial"
p("a:", a)
var b, c int = 1, 2
p("b:", b)
p("c:", c)
var d = true
p("d:", d)
var e int
p("e:", e)
f := "short"
p("f:", f)
var anything interface{} = "I'm a string" // An interface{} type is a type that could be any value. It’s like Object in Java.
p("anything:", anything)
var foo interface{}
switch foo.(type) {
case string:
fmt.Println("foo is a string")
case int32, int64:
fmt.Println("foo is an int")
default:
fmt.Println("foo is other than a string or an int")
}
}
| true
|
25095885b5b0ab967466e770cd9b18e3c61cc37d
|
Go
|
nateriver520/gogo-cache
|
/algorithm/FIFO.go
|
UTF-8
| 668
| 3
| 3
|
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package algorithm
import (
"gogo-cache/link"
)
type FIFOQueue struct {
maxSize int64
queue *link.Link
}
func (q *FIFOQueue) Insert(node link.Node) *link.Node {
for q.queue.Length >= q.maxSize {
q.queue.Pop()
}
return q.queue.Unshift(node)
}
func (q *FIFOQueue) Del(node *link.Node) {
q.queue.Del(node)
}
func (q *FIFOQueue) Update(node *link.Node) {
}
func (q *FIFOQueue) Clear() {
q.queue.Clear()
}
func (q *FIFOQueue) Print() {
q.queue.Print()
}
func (q *FIFOQueue) Equal(keys []string) bool {
return q.queue.Equal(keys)
}
func New_FIFO(size int64) *FIFOQueue {
q := link.New_Link()
return &FIFOQueue{
maxSize: size,
queue: q,
}
}
| true
|
f6c93729d045bc342a4a00d6d1fc4de8417100d5
|
Go
|
martincrxz/flappy-bird-clone
|
/bird.go
|
UTF-8
| 1,767
| 2.953125
| 3
|
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"sync"
"github.com/veandco/go-sdl2/img"
"github.com/veandco/go-sdl2/sdl"
)
const (
birdWidth = 50
birdHeigth = 43
initY = 300
initX = 10
gravity = 0.1
)
type bird struct {
mu sync.RWMutex
textures []*sdl.Texture
speed float64
y, x int32
dead bool
}
func newBird(r *sdl.Renderer) (*bird, error) {
var textures []*sdl.Texture
for i := 1; i <= 4; i++ {
path := fmt.Sprintf("res/img/bird_frame_%d.png", i)
texture, err := img.LoadTexture(r, path)
if err != nil {
return nil, fmt.Errorf("could not load bird, %v", err)
}
textures = append(textures, texture)
}
return &bird{
textures: textures,
y: initY,
x: initX,
dead: false}, nil
}
func (b *bird) update() {
b.y += int32(b.speed)
b.speed -= gravity
if b.y < 0 {
b.dead = true
}
}
func (b *bird) paint(r *sdl.Renderer, t uint64) error {
rect := &sdl.Rect{W: birdWidth, H: birdHeigth, X: b.x, Y: 600 - b.y - int32(birdHeigth/2)}
texIndex := (t / 10) % uint64(len(b.textures))
if err := r.Copy(b.textures[texIndex], nil, rect); err != nil {
return fmt.Errorf("could not copy bird, %v", err)
}
return nil
}
func (b *bird) jump() {
if b.speed < 0 {
b.speed = 3
} else if b.speed > 6 {
b.speed = 6
} else {
b.speed += 2
}
}
func (b *bird) isDead() bool {
return b.dead
}
func (b *bird) revive() {
b.speed = 0
b.y = initY
b.x = initX
b.dead = false
}
func (b *bird) move(m int) {
b.x += int32(m)
}
func (b *bird) hit(p *pipe) {
b.mu.Lock()
defer b.mu.Unlock()
if b.x+birdWidth < p.x {
return
}
if b.x > p.x+p.w {
return
}
if !p.inverted && b.y-birdHeigth/2 > p.h {
return
}
if p.inverted && height-p.h > b.y+birdHeigth/2 {
return
}
b.dead = true
}
| true
|
1b1ff380faeb896c1f90b503c36428eff88e91f7
|
Go
|
xfstart07/learngo
|
/gobasics/regex/example_test.go
|
UTF-8
| 3,710
| 3.375
| 3
|
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"regexp"
"testing"
)
func TestExampleRegexNumber(t *testing.T) {
ExampleRegNumber()
}
func TestPatternOr(t *testing.T) {
// xy 匹配x y
// x|y 匹配x或者y 优先x
source := "asdfdsxxxyyfergsfasfxyfa"
pattern := `x|y|a`
reg := regexp.MustCompile(pattern)
ret := reg.FindStringIndex(source)
fmt.Println(ret)
}
func TestPatternN2M(t *testing.T) {
//x* 匹配零个或者多个x,优先匹配多个
//x+ 匹配一个或者多个x,优先匹配多个
//x? 匹配零个或者一个x,优先匹配一个
//source = "xxxxewexxxasdfdsxxxyyfergsfasfxyfa"
//pattern = `x*`
// x{n,m} 匹配n个到m个x,优先匹配m个
// x{n,} 匹配n个到多个x,优先匹配更多
// x{n} 或者x{n}? 只匹配n个x
source = "xxxxxxxewexxxasdfdsxxxyyfergsfasfxyfa"
pattern = `x{4,}`
reg := regexp.MustCompile(pattern)
ret := reg.FindString(source)
fmt.Println(ret)
}
func TestPatternPriorityN(t *testing.T) {
// x{n,m}? 匹配n个到m个x,优先匹配n个
// x{n,}? 匹配n个到多个x,优先匹配n个
// x*? 匹配零个或者多个x,优先匹配0个
// x+? 匹配一个或者多个x,优先匹配1个
// x?? 匹配零个或者一个x,优先匹配0个
source = "xxxxxxxewexxxasdfdsxxxyyfergsfasfxyfa"
pattern = `x+?`
reg := regexp.MustCompile(pattern)
ret := reg.FindString(source)
fmt.Println(ret)
}
func TestPatternNumberN2M(t *testing.T) {
//[\d] 或者[^\D] 匹配数字
//[^\d]或者 [\D] 匹配非数字
source = "xx435ff5237yy6346fergsfasfxyfa"
pattern = `[\d]{3,}` //匹配3个或者更多个数字
reg := regexp.MustCompile(pattern)
ret := reg.FindString(source)
fmt.Println(ret)
}
func TestPatternAlpha(t *testing.T) {
source = "xx435ffGUTEYgjk52RYPHFY37yy6346ferg6987sfasfxyfa"
pattern = `[[:alpha:]]{5,}` //5个或者多个字母,相当于A-Za-z
reg := regexp.MustCompile(pattern)
ret := reg.FindString(source)
fmt.Println(ret)
}
func TestPatternHan(t *testing.T) {
source = "xx435,./$%(*(_&jgshgs发个^$%ffG返回福hjh放假啊啥UTEYgjk52RYPHFY37yy6346ferg6987sfasfxyfa"
pattern = `[\p{Han}]+` //匹配连续的汉字
reg := regexp.MustCompile(pattern)
ret := reg.FindString(source)
fmt.Println(ret)
}
func TestPatternPhone(t *testing.T) {
source = "13244820821HG74892109977HJA15200806084S11233240697hdgsfhah假发发货"
pattern = `1[3|5|7|8|9][\d]{9}` //匹配电话号码
reg := regexp.MustCompile(pattern)
ret := reg.FindString(source)
fmt.Println(ret)
}
func TestPatternEmail(t *testing.T) {
source = "[email protected]@163.cn200806084S11233240697hdgsfhah假发发货"
pattern = `\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*` //匹配电子邮箱
reg := regexp.MustCompile(pattern)
ret := reg.FindString(source)
fmt.Println(ret)
}
func TestPatternOther(t *testing.T) {
//匹配用户名或者密码 `^[a-zA-Z0-9_-]{4,16}$` 字母或者数字开头,区分大小写,最短4位最长16位
//匹配IP地址1 `^$(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$`
//匹配IP地址2
//pattern = `((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)`
// 匹配IP地址3
// pattern = `(\d+).(\d+).(\d+).(\d+)`
// 匹配IP地址4
//匹配日期 年-月-日 `(\d{4}|\d{2})-((1[0-2])|(0?[1-9]))-(([12][0-9])|(3[01])|(0?[1-9]))`
//匹配日期 月-日-年 `((1[0-2])|(0?[1-9]))/(([12][0-9])|(3[01])|(0?[1-9]))/(\d{4}|\d{2})`
//匹配时间 小时:分钟 24小时制 ` ((1|0?)[0-9]|2[0-3]):([0-5][0-9]) `
//匹配邮编 `[1-9][\d]5`
//匹配URL `[a-zA-z]+://[^\s]*`
}
func ExampleRegNumber() {
text := "132121111"
reg := regexp.MustCompile(`\d{4}$`)
regText := reg.ReplaceAllString(text, "0000")
fmt.Println(regText)
}
| true
|
5ddd1bc687872b02059bdeb6cf82f1db7aaef66e
|
Go
|
nevermore-muyi/muyifs
|
/pkg/fuse/normal_read_writer.go
|
UTF-8
| 6,316
| 2.625
| 3
|
[] |
no_license
|
[] |
no_license
|
package fuse
import (
"fmt"
"github.com/nevermore/muyifs/pkg/backend"
"k8s.io/klog/v2"
)
type WriterAt struct {
key string
fs *FileSystem
cache *WriteCache
}
type WriteCache struct {
uploadID string
part []*backend.Part
num int
length uint64
offset int64
errState bool
buf []byte
chunks []*Chunk
}
type Chunk struct {
offset int64
buf []byte
}
func NewWriter(key string, fs *FileSystem) CommonWriter {
return &WriterAt{
key: key,
fs: fs,
cache: &WriteCache{
uploadID: "",
part: nil,
num: 1,
length: 0,
buf: make([]byte, CacheSize, CacheSize),
},
}
}
func (w *WriterAt) WriteAt(p []byte, off int64) (n int, err error) {
if w.cache.errState {
klog.Errorf("WriteAt has cache error, do not continue")
return 0, fmt.Errorf("write error")
}
pLen := len(p)
// Init
if off == 0 {
mu, err := w.fs.Backend.InitiateMultipartUpload(w.key)
if err != nil {
klog.Errorf("WriteAt buffer InitiateMultipartUpload error %v", err)
return 0, err
}
w.cache.uploadID = mu.UploadID
w.cache.length = 0
w.cache.offset = 0
w.cache.num = 1
w.cache.part = make([]*backend.Part, 0)
}
if w.cache.length+uint64(pLen) > CacheSize {
// need upload
part, err := w.fs.Backend.UploadPart(w.key, w.cache.uploadID, w.cache.num, w.cache.buf[:w.cache.length])
if err != nil {
klog.Errorf("WriteAt buffer error %v", err)
w.cache.errState = true
return 0, err
}
w.cache.part = append(w.cache.part, part)
w.cache.length = 0
w.cache.num++
}
if off == w.cache.offset {
copy(w.cache.buf[w.cache.length:w.cache.length+uint64(pLen)], p)
w.cache.length += uint64(pLen)
w.cache.offset += int64(pLen)
} else {
c := &Chunk{}
c.offset = off
c.buf = make([]byte, pLen)
copy(c.buf, p)
w.cache.chunks = append(w.cache.chunks, c)
}
for i := 0; i < len(w.cache.chunks); {
if w.cache.chunks[i].offset == w.cache.offset {
if w.cache.length+uint64(len(w.cache.chunks[i].buf)) > CacheSize {
part, err := w.fs.Backend.UploadPart(w.key, w.cache.uploadID, w.cache.num, w.cache.buf[:w.cache.length])
if err != nil {
klog.Errorf("WriteAt buffer error %v", err)
w.cache.errState = true
return 0, err
}
w.cache.part = append(w.cache.part, part)
w.cache.length = 0
w.cache.num++
}
copy(w.cache.buf[w.cache.length:w.cache.length+uint64(len(w.cache.chunks[i].buf))], w.cache.chunks[i].buf)
w.cache.length += uint64(len(w.cache.chunks[i].buf))
w.cache.offset += int64(len(w.cache.chunks[i].buf))
w.cache.chunks = append(w.cache.chunks[:i], w.cache.chunks[i+1:]...)
i = 0
continue
}
i++
}
return pLen, nil
}
func (w *WriterAt) Flush() error {
if w.cache.errState {
klog.Errorf("WriteAt has cache error, do not flush")
w.fs.Backend.AbortUpload(w.key, w.cache.uploadID)
return fmt.Errorf("flush error")
}
if w.cache.length == 0 && len(w.cache.chunks) == 0 {
return nil
}
// do upload
for i := 0; i < len(w.cache.chunks); {
if w.cache.chunks[i].offset == w.cache.offset {
if w.cache.length+uint64(len(w.cache.chunks[i].buf)) > CacheSize {
part, err := w.fs.Backend.UploadPart(w.key, w.cache.uploadID, w.cache.num, w.cache.buf[:w.cache.length])
if err != nil {
klog.Errorf("WriteAt buffer error %v", err)
w.cache.errState = true
return err
}
w.cache.part = append(w.cache.part, part)
w.cache.length = 0
w.cache.num++
}
copy(w.cache.buf[w.cache.length:w.cache.length+uint64(len(w.cache.chunks[i].buf))], w.cache.chunks[i].buf)
w.cache.length += uint64(len(w.cache.chunks[i].buf))
w.cache.offset += int64(len(w.cache.chunks[i].buf))
w.cache.chunks = append(w.cache.chunks[:i], w.cache.chunks[i+1:]...)
i = 0
continue
}
i++
}
if w.cache.length > 0 {
part, err := w.fs.Backend.UploadPart(w.key, w.cache.uploadID, w.cache.num, w.cache.buf[:w.cache.length])
if err != nil {
klog.Errorf("WriteAt buffer error %v", err)
w.cache.errState = true
return err
}
w.cache.part = append(w.cache.part, part)
w.cache.length = 0
w.cache.num = 1
}
err := w.fs.Backend.CompleteUpload(w.key, w.cache.uploadID, w.cache.part)
if err != nil {
klog.Errorf("WriteAt CompleteUpload error %v", err)
w.cache.errState = true
return err
}
return nil
}
func (w *WriterAt) Release() {
w.cache.uploadID = ""
w.cache.part = nil
w.cache.num = 1
w.cache.length = 0
w.cache.chunks = make([]*Chunk, 0)
w.cache.errState = false
}
type ReaderAt struct {
key string
errState bool
fs *FileSystem
cache *ReadCache
}
type ReadCache struct {
start int64
offset int64
size int64
buf []byte
}
func NewReader(key string, fs *FileSystem) CommonReader {
return &ReaderAt{
key: key,
errState: false,
fs: fs,
cache: &ReadCache{
start: 0,
offset: 0,
size: 0,
buf: make([]byte, CacheSize, CacheSize),
},
}
}
func (r *ReaderAt) ReadAt(p []byte, offset int64) (n int, err error) {
if r.errState {
return 0, fmt.Errorf("read is in error state")
}
if offset == 0 {
o, err := r.fs.Backend.Head(r.key)
if err != nil {
r.errState = true
klog.Errorf("Head object %v error %v", r.key, err)
return 0, err
}
r.cache.size = o.Size
}
if offset >= r.cache.size {
klog.Errorf("buffer has download, over")
return len(p), nil
}
// Reload
if offset+int64(len(p)) > r.cache.offset {
if r.cache.offset >= r.cache.size {
newoff := offset - r.cache.start
copy(p, r.cache.buf[newoff:newoff+r.cache.offset-offset])
return len(p), nil
}
n, err = r.fs.Backend.Get(r.key, r.cache.offset, CacheSize, r.cache.buf)
if err != nil {
r.errState = true
klog.Errorf("ReadAt error %v", err)
return 0, err
}
r.cache.start = r.cache.offset
r.cache.offset += int64(n)
}
// Cache hit
if offset >= r.cache.start && offset+int64(len(p)) <= r.cache.offset {
newoff := offset - r.cache.start
copy(p, r.cache.buf[newoff:newoff+int64(len(p))])
return len(p), nil
}
// Single load
n, err = r.fs.Backend.Get(r.key, offset, int64(len(p)), p)
if err != nil {
r.errState = true
klog.Errorf("ReadAt error %v", err)
return 0, err
}
return len(p), nil
}
func (r *ReaderAt) Release() {
r.cache.start = 0
r.cache.offset = 0
r.cache.size = 0
r.errState = false
}
| true
|
c1b2eb4073c8c5c18dd89096899c9f0efc8012ee
|
Go
|
team-e-org/backend
|
/app/mocks/user_test.go
|
UTF-8
| 2,822
| 3.03125
| 3
|
[] |
no_license
|
[] |
no_license
|
package mocks
import (
"app/models"
"reflect"
"testing"
"time"
)
func TestUserMock(t *testing.T) {
ID := 0
users := &UserMock{}
user := &models.User{
ID: ID,
Name: "test user",
Email: "[email protected]",
Icon: "testicon",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
users.CreateUser(user)
got, err := users.GetUser(ID)
if err != nil {
t.Fatalf("An error occurred: %v", err)
}
if !reflect.DeepEqual(*user, *got) {
t.Fatalf("Not equal user")
}
}
func TestUserMockRepository(t *testing.T) {
users := NewUserRepository()
ID := 0
user := &models.User{
ID: ID,
Name: "test user",
Email: "[email protected]",
Icon: "testicon",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
users.CreateUser(user)
got, err := users.GetUser(ID)
if err != nil {
t.Fatalf("An error occurred: %v", err)
}
if !reflect.DeepEqual(*user, *got) {
t.Fatalf("Not equal user")
}
}
func TestUser(t *testing.T) {
users := NewUserRepository()
ID := 0
Email := "[email protected]"
now := time.Now()
user := &models.User{
ID: ID,
Name: "test user",
Email: Email,
Icon: "testicon",
CreatedAt: now,
UpdatedAt: now,
}
users.CreateUser(user)
Email2 := "[email protected]"
user2 := &models.User{
ID: ID,
Name: "test2 user",
Email: Email2,
Icon: "test2icon",
CreatedAt: now,
UpdatedAt: time.Now(),
}
users.UpdateUser(user2)
u, err := users.GetUser(ID)
if err != nil {
t.Fatalf("An error occurred: %v\n", err)
}
users.UpdateUser(user2)
if testCompareUsers(t, user, u) {
t.Fatalf("User did not update")
}
if !testCompareUsers(t, user2, u) {
t.Fatalf("User did not update")
}
u, err = users.GetUserByEmail(Email)
if err == nil {
t.Fatalf("Invalid email, but got user")
}
u, err = users.GetUserByEmail(Email2)
if err != nil {
t.Fatalf("Valid email, but got error")
}
if !testCompareUsers(t, user2, u) {
t.Fatalf("Users don't match")
}
users.DeleteUser(ID)
u, err = users.GetUser(ID)
if err == nil {
t.Fatalf("An error occurred: %v\n", err)
}
if u != nil {
t.Fatalf("User did not delete")
}
}
func testCompareUsers(t *testing.T, user *models.User, user2 *models.User) bool {
if user.ID != user2.ID {
return false
}
if user.Name != user2.Name {
return false
}
if user.Email != user2.Email {
return false
}
if user.HashedPassword != user2.HashedPassword {
return false
}
if user.Icon != user2.Icon {
return false
}
return true
}
func TestUserError(t *testing.T) {
user := &models.User{
ID: 1,
Name: "test name",
Email: "[email protected]",
Icon: "test icon",
}
users := NewUserRepository()
err := users.UpdateUser(user)
if err == nil {
t.Fatalf("An error should occur")
}
err = users.DeleteUser(user.ID)
if err == nil {
t.Fatalf("An error should occur")
}
}
| true
|
6a8bef9a76faab9c3de3d6a190ca05a1ba64089e
|
Go
|
wzq1992/go-leetcode
|
/week-06/lessons/lc63_unique_paths_ii.go
|
UTF-8
| 519
| 2.703125
| 3
|
[] |
no_license
|
[] |
no_license
|
package lessons
func uniquePathsWithObstacles(obstacleGrid [][]int) int {
m, n := len(obstacleGrid), len(obstacleGrid[0])
f := make([][]int, m)
for i := range f {
f[i] = make([]int, n)
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if obstacleGrid[i][j] == 1 {
f[i][j] = 0
} else if i == 0 && j == 0 {
f[i][j] = 1
} else if i == 0 {
f[i][j] = f[i][j-1]
} else if j == 0 {
f[i][j] = f[i-1][j]
} else {
f[i][j] = f[i-1][j] + f[i][j-1]
}
}
}
return f[m-1][n-1]
}
| true
|
3870b129bb9d98e8b2831a2e8a015540486b0ab6
|
Go
|
lwlwilliam/go-notes
|
/translations/yourbasic.org/Standard_library/src/readFull.go
|
UTF-8
| 291
| 2.765625
| 3
|
[] |
no_license
|
[] |
no_license
|
package main
import (
"strings"
"io"
"log"
"fmt"
)
func main() {
r := strings.NewReader("abcde")
buf := make([]byte, 4)
if _, err := io.ReadFull(r, buf); err != nil {
log.Fatal(err)
}
fmt.Printf("%s", buf)
if _, err := io.ReadFull(r, buf); err != nil {
log.Fatal(err)
}
}
| true
|
ac45c13a2caad2e3e648c5cfa42b6d14cdc0564a
|
Go
|
ibilalkayy/Virtual-workspace
|
/entrance/login.go
|
UTF-8
| 430
| 2.59375
| 3
|
[] |
no_license
|
[] |
no_license
|
package entrance
/* Importing libraries */
import (
"fmt"
"github.com/ibilalkayy/VWS/database"
)
/* Function to login */
func Login() {
fmt.Println("--------")
fmt.Println("Log In")
fmt.Println("--------")
fmt.Printf("Enter your email address: ")
fmt.Scanln(&pd.email)
fmt.Printf("Enter your password: ")
fmt.Scanln(&pd.password)
/* Finding login info in database */
database.Findaccount(pd.email, pd.password)
}
| true
|
c2af6ffbbf917ab80999e79ceeb6bc0c8f9a6fb3
|
Go
|
yutank34/go-lang
|
/ch01/ex04/main.go
|
UTF-8
| 1,077
| 3.296875
| 3
|
[] |
no_license
|
[] |
no_license
|
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
counts := make(map[string]int)
fnames := make(map[string][]string)
files := os.Args[1:]
if len(files) == 0 {
countLines(os.Stdin, counts, fnames)
} else {
for _, arg := range files {
f, err := os.Open(arg)
if err != nil {
fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
}
countLines(f, counts, fnames)
f.Close()
}
}
for line, n := range counts {
if n > 1 {
fmt.Printf("%d\t%s: %s\n", n, line, strings.Join(fnames[line][0:], " "))
}
}
}
func countLines(f *os.File, counts map[string]int, fnames map[string][]string) *map[string][]string {
input := bufio.NewScanner(f)
for input.Scan() {
t := input.Text()
if t == "exit" {
break
}
counts[t]++
f := f.Name()
names := fnames[t]
if contain(names, f) {
continue
}
names = append(names, f)
fnames[t] = names
}
// TODO: input.Err()のからのエラー処理
return &fnames
}
func contain(a []string, s string) bool {
for _, x := range a {
if x == s {
return true
}
}
return false
}
| true
|
80dc12d51c51cb429e21c2f3498bebb83902b042
|
Go
|
andresorav/go-tdd
|
/integers/add_test.go
|
UTF-8
| 261
| 2.6875
| 3
|
[] |
no_license
|
[] |
no_license
|
package integers
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func TestAdd(t *testing.T) {
t.Parallel()
res := Add(1, 2)
expected := 3
assert.Equal(t, expected, res)
}
func ExampleAdd() {
fmt.Println(Add(5, 6))
// Output: 11
}
| true
|
b1b8ecb08fa86bb8c17ae905a8e180a7211ca2c1
|
Go
|
growdu/go-work
|
/src/interface/func_interface.go
|
UTF-8
| 477
| 3.796875
| 4
|
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
//声明接口
type test interface {
String(input string)
}
//声明函数echo
type Echo func(input string)
//函数实现接口
func (e Echo) String(input string) {
e(input)
}
func main() {
//使用Echo()将echoInstance转为Echo类型
echo := Echo(echoInstance)
var test1 test = echo
Print(echo)
Print(test1)
}
func Print(test2 test) error {
test2.String("test")
return nil
}
func echoInstance(input string) {
fmt.Println(input)
}
| true
|
1f163c09eeb76215e9d2e44f0139370f2fb7b1f1
|
Go
|
lorenzo-stoakes/euler
|
/7.go
|
UTF-8
| 999
| 3.8125
| 4
|
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"math"
)
const N = 10001
// Taken from 3.go.
// See https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes.
func sieve(n int) []int {
// Populate 2 to n. +1 size so indexes coincide with values for readabililty.
tmp := make([]int, n+1)
for i := 2; i <= n; i++ {
tmp[i] = i
}
curr := 2
for curr < n {
// 0 represents a 'crossed out' value.
for i := 2 * curr; i <= n; i += curr {
tmp[i] = 0
}
// Skip to next prime number.
for curr = curr + 1; curr < n && tmp[curr] == 0; curr++ {
}
}
// Now filter our crossed out set.
var ret []int
for _, n := range tmp {
if n > 0 {
ret = append(ret, n)
}
}
return ret
}
// Get n primes.
func primes(n int) []int {
// The nth prime is roughly n log n.
estimate := n * int(math.Log(float64(n)))
var ret []int
// Double estimate until we have the primes we need.
for len(ret) < n {
ret = sieve(estimate)
estimate *= 2
}
return ret[:n]
}
func main() {
fmt.Println(primes(N)[N-1])
}
| true
|
f492fb1b496fd0020862d0d7021434f67108a319
|
Go
|
MacklinEngineering/grav
|
/docs/examples/receiving_async.go
|
UTF-8
| 727
| 2.875
| 3
|
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package main
import (
"fmt"
"github.com/suborbital/grav/grav"
)
func receiveMessagesAsync() {
g := grav.New()
// create a pod and set a function to be called on each message
// if the msgFunc returns an error, it indicates to the Gav instance that
// the message could not be handled.
p := g.Connect()
p.On(func(msg grav.Message) error {
fmt.Println("message received:", string(msg.Data()))
return nil
})
// create a second pod and set it to receive only messages of a specific type
// errors indicate that a message could not be handled.
p2 := g.Connect()
p2.OnType("grav.specialmessage", func(msg grav.Message) error {
fmt.Println("special message received:", string(msg.Data()))
return nil
})
}
| true
|
f73627c4a70e2ea6d98e42607bea7418b098b0e5
|
Go
|
frankunderw00d/userserver
|
/module/user/user_register.go
|
UTF-8
| 2,116
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package user
import (
"baseservice/model/platform"
"baseservice/model/user"
"encoding/json"
"errors"
"fmt"
"jarvis/base/log"
"jarvis/base/network"
"jarvis/util/rand"
"jarvis/util/regexp"
loginModel "userserver/model/user"
)
// 注册
func (um *userModule) register(ctx network.Context) {
// 反序列化数据
request := loginModel.RegisterRequest{}
if err := json.Unmarshal(ctx.Request().Data, &request); err != nil {
printReplyError(ctx.ServerError(err))
return
}
// 调用业务函数
err := register(request)
if err != nil {
log.ErrorF("register error : %s", err.Error())
printReplyError(ctx.ServerError(err))
return
}
// 返回响应
printReplyError(ctx.Success([]byte("Register succeed")))
}
func register(request loginModel.RegisterRequest) error {
// 验证平台号
if !platform.HExistsPlatformByID(fmt.Sprintf("%d", request.PlatformID)) {
return errors.New("platform id doesn't exists")
}
// 绑定用户登录需要验证账号、秘密
if request.RegisterType == loginModel.RegisterTypeCustomer {
// 账号要求 6-18位,只允许字母数字,不允许数字开头
if !regexp.Match("^[a-zA-Z]+[a-zA-Z0-9]{5,17}$", request.Account) {
return errors.New("require account length must between 6 - 18")
}
// 密码要求 6-18位,只允许字母数字
if !regexp.Match("^[a-zA-Z0-9]{6,18}$", request.Password) {
return errors.New("require password length must between 6 - 18")
}
} else {
// 随机分配账号密码
request.Account = rand.RandomString(10, rand.SeedUCL, rand.SeedLCL) + rand.RandomString(8, rand.SeedNum)
request.Password = rand.RandomString(18, rand.SeedUCL, rand.SeedLCL, rand.SeedNum)
}
// 生成唯一 token
token := rand.RandomString(16)
freshUser := user.FreshUser()
freshUser.Account.Token = token
freshUser.Account.Account = request.Account
freshUser.Account.Password = request.Password
freshUser.Account.AccountType = request.RegisterType
freshUser.Account.Platform = request.PlatformID
freshUser.Info.Name = rand.RandomString(10)
if err := freshUser.Store(); err != nil {
return err
}
return nil
}
| true
|
6af6218ffb40e41a5193a0eab288e635ebc20d17
|
Go
|
fallendusk/wails
|
/runtime.go
|
UTF-8
| 631
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package wails
// Runtime is the Wails Runtime Interface, given to a user who has defined the WailsInit method
type Runtime struct {
Events *RuntimeEvents
Log *RuntimeLog
Dialog *RuntimeDialog
Window *RuntimeWindow
Browser *RuntimeBrowser
FileSystem *RuntimeFileSystem
}
func newRuntime(eventManager *eventManager, renderer Renderer) *Runtime {
return &Runtime{
Events: newRuntimeEvents(eventManager),
Log: newRuntimeLog(),
Dialog: newRuntimeDialog(renderer),
Window: newRuntimeWindow(renderer),
Browser: newRuntimeBrowser(),
FileSystem: newRuntimeFileSystem(),
}
}
| true
|
06337f847ae3645f4f57e6e4546702e93d7eb126
|
Go
|
hyperledger/fabric
|
/gossip/util/pubsub_test.go
|
UTF-8
| 2,163
| 3.078125
| 3
|
[
"Apache-2.0",
"CC-BY-4.0"
] |
permissive
|
[
"Apache-2.0",
"CC-BY-4.0"
] |
permissive
|
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package util
import (
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestNewPubsub(t *testing.T) {
ps := NewPubSub()
// Check a publishing to a topic with a subscription succeeds
sub1 := ps.Subscribe("test", time.Second)
sub2 := ps.Subscribe("test2", time.Second)
require.NotNil(t, sub1)
go func() {
err := ps.Publish("test", 5)
require.NoError(t, err)
}()
item, err := sub1.Listen()
require.NoError(t, err)
require.Equal(t, 5, item)
// Check that a publishing to a topic with no subscribers fails
err = ps.Publish("test3", 5)
require.Error(t, err)
require.Contains(t, "no subscribers", err.Error())
// Check that a listen on a topic that its publish is too late, times out
// and returns an error
go func() {
time.Sleep(time.Second * 2)
ps.Publish("test2", 10)
}()
item, err = sub2.Listen()
require.Error(t, err)
require.Contains(t, "timed out", err.Error())
require.Nil(t, item)
// Have multiple subscribers subscribe to the same topic
subscriptions := []Subscription{}
n := 100
for i := 0; i < n; i++ {
subscriptions = append(subscriptions, ps.Subscribe("test4", time.Second))
}
go func() {
// Send items and fill the buffer and overflow
// it by 1 item
for i := 0; i <= subscriptionBuffSize; i++ {
err := ps.Publish("test4", 100+i)
require.NoError(t, err)
}
}()
wg := sync.WaitGroup{}
wg.Add(n)
for _, s := range subscriptions {
go func(s Subscription) {
time.Sleep(time.Second)
defer wg.Done()
for i := 0; i < subscriptionBuffSize; i++ {
item, err := s.Listen()
require.NoError(t, err)
require.Equal(t, 100+i, item)
}
// The last item that we published was dropped
// due to the buffer being full
item, err := s.Listen()
require.Nil(t, item)
require.Error(t, err)
}(s)
}
wg.Wait()
// Ensure subscriptions are cleaned after use
for i := 0; i < 10; i++ {
time.Sleep(time.Second)
ps.Lock()
empty := len(ps.subscriptions) == 0
ps.Unlock()
if empty {
break
}
}
ps.Lock()
defer ps.Unlock()
require.Empty(t, ps.subscriptions)
}
| true
|
19adb7fb4e82d2cd8453be4d4c72042506411669
|
Go
|
MilosSimic/Blog
|
/NATS/MasterWorker/Master/Master.go
|
UTF-8
| 2,497
| 2.515625
| 3
|
[] |
no_license
|
[] |
no_license
|
package main
import (
"bytes"
"fmt"
"net/http"
"os"
"sync"
"time"
"github.com/cube2222/Blog/NATS/MasterWorker"
"github.com/golang/protobuf/proto"
"github.com/nats-io/nats"
"github.com/satori/go.uuid"
)
var Tasks []Transport.Task
var TaskMutex sync.Mutex
var oldestFinishedTaskPointer int
var nc *nats.Conn
func main() {
if len(os.Args) != 2 {
fmt.Println("Wrong number of arguments. Need NATS server address.")
return
}
var err error
nc, err = nats.Connect(os.Args[1])
if err != nil {
fmt.Println(err)
}
Tasks = make([]Transport.Task, 0, 20)
TaskMutex = sync.Mutex{}
oldestFinishedTaskPointer = 0
initTestTasks()
nc.Subscribe("Work.TaskToDo", func(m *nats.Msg) {
myTaskPointer, ok := getNextTask()
if ok {
data, err := proto.Marshal(myTaskPointer)
if err == nil {
nc.Publish(m.Reply, data)
}
}
})
nc.Subscribe("Work.TaskFinished", func(m *nats.Msg) {
myTask := Transport.Task{}
err := proto.Unmarshal(m.Data, &myTask)
if err == nil {
TaskMutex.Lock()
Tasks[myTask.Id].State = 2
Tasks[myTask.Id].Finisheduuid = myTask.Finisheduuid
TaskMutex.Unlock()
}
})
select {}
}
func getNextTask() (*Transport.Task, bool) {
TaskMutex.Lock()
defer TaskMutex.Unlock()
for i := oldestFinishedTaskPointer; i < len(Tasks); i++ {
if i == oldestFinishedTaskPointer && Tasks[i].State == 2 {
oldestFinishedTaskPointer++
} else {
if Tasks[i].State == 0 {
Tasks[i].State = 1
go resetTaskIfNotFinished(i)
return &Tasks[i], true
}
}
}
return nil, false
}
func resetTaskIfNotFinished(i int) {
time.Sleep(2 * time.Minute)
TaskMutex.Lock()
if Tasks[i].State != 2 {
Tasks[i].State = 0
}
}
func initTestTasks() {
for i := 0; i < 20; i++ {
newTask := Transport.Task{Uuid: uuid.NewV4().String(), State: 0}
fileServerAddressTransport := Transport.DiscoverableServiceTransport{}
msg, err := nc.Request("Discovery.FileServer", nil, 1000*time.Millisecond)
if err == nil && msg != nil {
err := proto.Unmarshal(msg.Data, &fileServerAddressTransport)
if err != nil {
continue
}
}
if err != nil {
continue
}
fileServerAddress := fileServerAddressTransport.Address
data := make([]byte, 0, 1024)
buf := bytes.NewBuffer(data)
fmt.Fprint(buf, "get,my,data,my,get,get,have")
r, err := http.Post(fileServerAddress+"/"+newTask.Uuid, "", buf)
if err != nil || r.StatusCode != http.StatusOK {
continue
}
newTask.Id = int32(len(Tasks))
Tasks = append(Tasks, newTask)
}
}
| true
|
65569021cfe30371653d4050c29a650a07c9d07e
|
Go
|
miku/skate
|
/zipkey/zipkey.go
|
UTF-8
| 2,536
| 3.296875
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package zipkey
import (
"bufio"
"io"
)
// Group groups items by key and will contain the complete records (e.g. line)
// for further processing.
type Group struct {
Key string
G0 []string
G1 []string
}
type (
keyFunc func(string) (string, error)
groupFunc func(*Group) error
)
// ZipRun reads records (separated by sep) from two readers, extracts a key
// from each record with a keyFunc and collects records from the two streams
// into a Group. A callback can be registered, which allows to customize the
// processing of the group.
type ZipRun struct {
r0, r1 *bufio.Reader
kf keyFunc
gf groupFunc
sep byte
}
// New create a new ready to run ZipRun value.
func New(r0, r1 io.Reader, kf keyFunc, gf groupFunc) *ZipRun {
return &ZipRun{
r0: bufio.NewReader(r0),
r1: bufio.NewReader(r1),
kf: kf,
gf: gf,
sep: '\n',
}
}
// Run starts reading from both readers. The process stops, if one reader is
// exhausted or reads from any reader fail.
func (c *ZipRun) Run() error {
var (
k0, k1, c0, c1 string // key: k0, k1; current line: c0, c1
done bool
err error
lineKey = func(r *bufio.Reader) (line, key string, err error) {
if line, err = r.ReadString(c.sep); err != nil {
return
}
key, err = c.kf(line)
return
}
)
for {
if done {
break
}
switch {
case k0 == "" || k0 < k1:
for k0 == "" || k0 < k1 {
c0, k0, err = lineKey(c.r0)
if err == io.EOF {
return nil
}
if err != nil {
return err
}
}
case k1 == "" || k0 > k1:
for k1 == "" || k0 > k1 {
c1, k1, err = lineKey(c.r1)
if err == io.EOF {
return nil
}
if err != nil {
return err
}
}
case k0 == k1:
g := &Group{
G0: []string{c0},
G1: []string{c1},
}
for {
c0, err = c.r0.ReadString(c.sep)
if err == io.EOF {
done = true
break
}
if err != nil {
return err
}
k, err := c.kf(c0)
if err != nil {
return err
}
if k == k0 {
g.G0 = append(g.G0, c0)
k0 = k
} else {
k0 = k
break
}
}
for {
c1, err = c.r1.ReadString(c.sep)
if err == io.EOF {
done = true
break
}
if err != nil {
return err
}
k, err := c.kf(c1)
if err != nil {
return err
}
if k == k1 {
g.G1 = append(g.G1, c1)
k1 = k
} else {
k1 = k
break
}
}
if c.gf != nil {
if err := c.gf(g); err != nil {
return err
}
}
}
}
return nil
}
| true
|
ba72faab9d32c5e225febe85cafced81fa1efd0a
|
Go
|
bluebat1/kdtree
|
/kdrange/range.go
|
UTF-8
| 1,291
| 3.171875
| 3
|
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2020 Dennis Kuhnert
*
* 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 kdrange contains k-dimensional range struct and helpers.
package kdrange
// Range represents a range in k-dimensional space.
type Range [][2]float64
// New creates a new Range.
//
// It accepts a sequence of min/max pairs that define the Range.
// For example a 2-dimensional rectangle with the with 2 and height 3, starting at (1,2):
//
// r := NewRange(1, 3, 2, 5)
//
// I.e.:
// x (dim 0): 1 <= x <= 3
// y (dim 1): 2 <= y <= 5
func New(limits ...float64) Range {
if limits == nil || len(limits)%2 != 0 {
return nil
}
r := make([][2]float64, len(limits)/2)
for i := range r {
r[i] = [2]float64{limits[2*i], limits[2*i+1]}
}
return r
}
| true
|
20bce6fab5a6f828805df27a71f7a5fa50e44baf
|
Go
|
mjm/courier-js
|
/pkg/scraper/scrape.go
|
UTF-8
| 2,488
| 2.78125
| 3
|
[] |
no_license
|
[] |
no_license
|
package scraper
import (
"context"
"errors"
"fmt"
"mime"
"net/http"
"net/url"
"strings"
"github.com/PuerkitoBio/purell"
"go.opentelemetry.io/otel/api/trace"
)
var (
ErrBadStatus = errors.New("unexpected response status")
ErrNoContentType = errors.New("no content type in response")
ErrInvalid = errors.New("not a valid feed")
)
func Scrape(ctx context.Context, u *url.URL, cachingHeaders *CachingHeaders) (*Feed, error) {
ctx, span := tracer.Start(ctx, "scraper.Scrape",
trace.WithAttributes(urlKey(u.String())))
defer span.End()
r, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
if err != nil {
span.RecordError(ctx, err)
return nil, err
}
if cachingHeaders != nil {
span.SetAttributes(
ifNoneMatchKey(cachingHeaders.Etag),
ifModifiedSinceKey(cachingHeaders.LastModified))
r.Header.Set("If-None-Match", cachingHeaders.Etag)
r.Header.Set("If-Modified-Since", cachingHeaders.LastModified)
}
res, err := http.DefaultClient.Do(r)
if err != nil {
span.RecordError(ctx, err)
return nil, err
}
span.SetAttributes(statusKey(res.StatusCode))
if res.StatusCode == http.StatusNotModified {
return nil, nil
}
if res.StatusCode > 299 {
err = fmt.Errorf("%w: %d", ErrBadStatus, res.StatusCode)
span.RecordError(ctx, err)
return nil, err
}
contentType := res.Header.Get("Content-Type")
span.SetAttributes(contentTypeKey(contentType))
if contentType == "" {
span.RecordError(ctx, err)
return nil, ErrNoContentType
}
contentType, _, err = mime.ParseMediaType(contentType)
if err != nil {
span.RecordError(ctx, err)
return nil, err
}
var f *Feed
if strings.Contains(contentType, "json") {
f, err = parseJSONFeed(ctx, res)
}
if strings.Contains(contentType, "atom") || strings.Contains(contentType, "rss") || strings.Contains(contentType, "xml") {
f, err = parseXMLFeed(ctx, res)
}
if err != nil {
span.RecordError(ctx, err)
return nil, err
}
if f != nil {
f.CachingHeaders.Etag = res.Header.Get("Etag")
f.CachingHeaders.LastModified = res.Header.Get("Last-Modified")
span.SetAttributes(etagKey(f.CachingHeaders.Etag), lastModifiedKey(f.CachingHeaders.LastModified))
return f, nil
}
span.RecordError(ctx, ErrInvalid)
return nil, ErrInvalid
}
func NormalizeURL(url string) string {
normalized, err := purell.NormalizeURLString(url, purell.FlagsSafe|purell.FlagAddTrailingSlash|purell.FlagRemoveDotSegments)
if err != nil {
return url
}
return normalized
}
| true
|
9786924f0c1a92cfa9d7aa56a8b5b95abb8e4176
|
Go
|
rkravchik/go-tarantool
|
/pack_data.go
|
UTF-8
| 3,808
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package tarantool
import (
"bytes"
"fmt"
"io"
"gopkg.in/vmihailenco/msgpack.v2"
)
// cache precompiled
type packData struct {
defaultSpace interface{}
packedDefaultSpace []byte
packedDefaultIndex []byte
packedIterEq []byte
packedDefaultLimit []byte
packedDefaultOffset []byte
packedSingleKey []byte
spaceMap map[string]uint64
indexMap map[uint64](map[string]uint64)
primaryKeyMap map[uint64]([]int)
}
func encodeValues2(v1, v2 interface{}) []byte {
var buf bytes.Buffer
encoder := msgpack.NewEncoder(&buf)
encoder.Encode(v1)
encoder.Encode(v2)
return buf.Bytes()
}
func packSelectSingleKey() []byte {
var buf bytes.Buffer
encoder := msgpack.NewEncoder(&buf)
encoder.EncodeUint32(KeyKey)
encoder.EncodeArrayLen(1)
return buf.Bytes()
}
func newPackData(defaultSpace interface{}) *packData {
var packedDefaultSpace []byte
if spaceNo, ok := defaultSpace.(uint64); ok {
packedDefaultSpace = encodeValues2(KeySpaceNo, spaceNo)
}
return &packData{
defaultSpace: defaultSpace,
packedDefaultSpace: packedDefaultSpace,
packedDefaultIndex: encodeValues2(KeyIndexNo, uint32(0)),
packedIterEq: encodeValues2(KeyIterator, IterEq),
packedDefaultLimit: encodeValues2(KeyLimit, DefaultLimit),
packedDefaultOffset: encodeValues2(KeyOffset, 0),
packedSingleKey: packSelectSingleKey(),
spaceMap: make(map[string]uint64),
indexMap: make(map[uint64](map[string]uint64)),
primaryKeyMap: make(map[uint64]([]int)),
}
}
func (data *packData) spaceNo(space interface{}) (uint64, error) {
if space == nil {
space = data.defaultSpace
}
switch value := space.(type) {
default:
return 0, fmt.Errorf("Wrong space %#v", space)
case int:
return uint64(value), nil
case uint:
return uint64(value), nil
case int64:
return uint64(value), nil
case uint64:
return value, nil
case int32:
return uint64(value), nil
case uint32:
return uint64(value), nil
case string:
spaceNo, exists := data.spaceMap[value]
if exists {
return spaceNo, nil
} else {
return 0, fmt.Errorf("Unknown space %#v", space)
}
}
}
func (data *packData) encodeSpace(space interface{}, encoder *msgpack.Encoder) error {
spaceNo, err := data.spaceNo(space)
if err != nil {
return err
}
encoder.EncodeUint32(KeySpaceNo)
encoder.Encode(spaceNo)
return nil
}
func (data *packData) writeSpace(space interface{}, w io.Writer, encoder *msgpack.Encoder) error {
if space == nil && data.packedDefaultSpace != nil {
w.Write(data.packedDefaultSpace)
return nil
}
return data.encodeSpace(space, encoder)
}
func (data *packData) indexNo(space interface{}, index interface{}) (uint64, error) {
if index == nil {
return 0, nil
}
switch value := index.(type) {
default:
return 0, fmt.Errorf("Wrong index %#v", space)
case int:
return uint64(value), nil
case uint:
return uint64(value), nil
case int64:
return uint64(value), nil
case uint64:
return value, nil
case int32:
return uint64(value), nil
case uint32:
return uint64(value), nil
case string:
spaceNo, err := data.spaceNo(space)
if err != nil {
return 0, nil
}
spaceData, exists := data.indexMap[spaceNo]
if !exists {
return 0, fmt.Errorf("No indexes defined for space %#v", space)
}
indexNo, exists := spaceData[value]
if exists {
return indexNo, nil
} else {
return 0, fmt.Errorf("Unknown index %#v", index)
}
}
}
func (data *packData) writeIndex(space interface{}, index interface{}, w io.Writer, encoder *msgpack.Encoder) error {
if index == nil {
w.Write(data.packedDefaultIndex)
return nil
}
indexNo, err := data.indexNo(space, index)
if err != nil {
return err
}
encoder.EncodeUint32(KeyIndexNo)
encoder.Encode(indexNo)
return nil
}
| true
|
8761a4f84ce71726104da6f8338a01cc4aa8fdec
|
Go
|
formicidae-tracker/leto
|
/cmd/leto/byte_rate_estimator.go
|
UTF-8
| 1,192
| 3.3125
| 3
|
[] |
no_license
|
[] |
no_license
|
package main
import (
"math"
"sync"
"time"
)
// byteRateEstimator estimate the mean write speed of a long process
// (several minute / hours / days ) on the disk. It is able to discard
// punctual events.
type byteRateEstimator struct {
mx sync.Mutex
freeStartBytes int64
startTime time.Time
mean float64
}
func NewByteRateEstimator(freeBytes int64, t time.Time) *byteRateEstimator {
return &byteRateEstimator{
freeStartBytes: freeBytes,
startTime: t,
mean: math.NaN(),
}
}
func (e *byteRateEstimator) Estimate(freeBytes int64, t time.Time) int64 {
e.mx.Lock()
defer e.mx.Unlock()
ellapsed := t.Sub(e.startTime)
written := e.freeStartBytes - freeBytes
bps := float64(written) / ellapsed.Seconds()
if math.IsNaN(e.mean) {
e.mean = bps
return int64(bps)
}
if math.Abs((bps-e.mean)/e.mean) > 0.5 {
// more than 50% relative variation, an external event
// happened. We restart the start point and mean estimation.
bps = e.mean
e.startTime = t
e.freeStartBytes = freeBytes
e.mean = math.NaN()
} else {
// we slowly update the mean.
e.mean += 0.8 * (bps - e.mean)
bps = e.mean
}
return int64(bps)
}
| true
|
019661c6f3d4df11ee2fe91410741a75efae8934
|
Go
|
gitter-badger/gedcom
|
/html/column.go
|
UTF-8
| 442
| 3.34375
| 3
|
[] |
no_license
|
[] |
no_license
|
package html
import (
"fmt"
)
// Column is used inside of a row. The row consists of 12 virtual columns and
// each column can specify how many of the columns it represents.
type Column struct {
width int
body fmt.Stringer
}
func NewColumn(width int, body fmt.Stringer) *Column {
return &Column{
width: width,
body: body,
}
}
func (c *Column) String() string {
return NewDiv(fmt.Sprintf("col-%d", c.width), c.body).String()
}
| true
|
d9bc157dfb74a5fe4635ebaf68bf91f837cf6f06
|
Go
|
anoopanooponly/go-learn
|
/maps-ex.go
|
UTF-8
| 533
| 3.6875
| 4
|
[] |
no_license
|
[] |
no_license
|
package main
import "fmt"
func main() {
m := make(map[string] int)
m["k"] = 2
m["l"] = 3
fmt.Println(m)
m1 := make(map[byte] int)
m1['a'] = 2
fmt.Println(m1['a'])
fmt.Println("len:", len(m))
delete(m, "l")
fmt.Println(m)
_, prs := m["k2"]
fmt.Println("prs:", prs) // To check if key present in map
_, prs = m["k"]
fmt.Println("prs:", prs)
mapinit := map[string] int { "a": 1, "b": 2, "c": 3}
fmt.Print(mapinit)
//range example
for k,v := range mapinit {
fmt.Printf("%s -> %v \n", k,v)
}
}
| true
|
dbc9154389a2a19ec865b4d878096f63746338f8
|
Go
|
lvzhenchao/Go-advanced
|
/demo5_copy.go
|
UTF-8
| 1,448
| 3.421875
| 3
|
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"io"
"io/ioutil"
"os"
)
func main() {
srcFile := "E:/GoPath/src/a/1.png"
desFile := "E:/GoPath/src/a/222.png"
//total,err := CopyFile1(srcFile, desFile)
//total,err := CopyFile2(srcFile, desFile)
total,err := CopyFile3(srcFile, desFile)
fmt.Println(total, err)
}
func CopyFile3(srcFile, destFile string)(int, error) {
bs,err := ioutil.ReadFile(srcFile)
if err != nil {
return 0,err
}
err = ioutil.WriteFile(destFile,bs,0777)
if err != nil {
return 0,err
}
return len(bs), nil
}
func CopyFile2(srcFile, destFile string)(int64, error) {
file1,err := os.Open(srcFile)
if err != nil {
return 0, err
}
file2,err := os.OpenFile(destFile,os.O_WRONLY|os.O_CREATE,os.ModePerm)
if err != nil {
return 0, err
}
defer file1.Close()
defer file2.Close()
return io.Copy(file2, file1)
}
func CopyFile1(srcFile, destFile string)(int, error) {
file1,err := os.Open(srcFile)
if err != nil {
return 0, err
}
file2,err := os.OpenFile(destFile,os.O_WRONLY|os.O_CREATE,os.ModePerm)
if err != nil {
return 0, err
}
defer file1.Close()
defer file2.Close()
//读写
bs := make([]byte, 1024, 1024)
n := -1 //读取的数据量
total := 0
for{
n,err = file1.Read(bs)
if err == io.EOF || n == 0 {
fmt.Println("拷贝完毕")
break
} else if err != nil {
fmt.Println("报错了:", err)
return total, err
}
total += n
file2.Write(bs[:n])
}
return total,nil
}
| true
|
421a8471d76626a13afb8242547c4ce78c85aef8
|
Go
|
zworld-apps/zworld-web
|
/fileserver.go
|
UTF-8
| 2,668
| 3.125
| 3
|
[] |
no_license
|
[] |
no_license
|
package main
import (
"fmt"
"io"
"net/http"
"os"
"strings"
"github.com/go-chi/chi"
)
// Got from https://stackoverflow.com/questions/49589685/good-way-to-disable-directory-listing-with-http-fileserver-in-go
//
// Creates a custom filesystem for the FileServer function so it doesn't serve folders as a listing of files and,
// instead serve a 404 error
type CustomFilesystem struct {
http.FileSystem
readDirBatchSize int
}
func (fs *CustomFilesystem) Open(name string) (http.File, error) {
f, err := fs.FileSystem.Open(name)
if err != nil {
return nil, err
}
return &NeuteredStatFile{File: f, readDirBatchSize: fs.readDirBatchSize}, nil
}
type NeuteredStatFile struct {
http.File
readDirBatchSize int
}
func (e *NeuteredStatFile) Stat() (os.FileInfo, error) {
s, err := e.File.Stat()
if err != nil {
return nil, err
}
if s.IsDir() {
LOOP:
for {
fl, err := e.File.Readdir(e.readDirBatchSize)
switch err {
case io.EOF:
break LOOP
case nil:
for _, f := range fl {
if f.Name() == "index.html" {
return s, err
}
}
default:
return nil, err
}
}
return nil, os.ErrNotExist
}
return s, err
}
// Got from https://github.com/go-chi/chi/blob/master/_examples/fileserver/main.go
//
// FileServer conveniently sets up a http.FileServer handler to serve
// static files from a http.FileSystem.
func FileServer(router *chi.Mux, path string, root string) {
if strings.ContainsAny(path, "{}*") {
panic("FileServer does not permit URL parameters.")
}
fs := http.StripPrefix(path, http.FileServer(
&CustomFilesystem{
FileSystem: http.Dir(root),
readDirBatchSize: 2,
},
))
// redirect to / terminated urls
if path != "/" && path[len(path)-1] != '/' {
router.Get(path, http.RedirectHandler(path+"/", 301).ServeHTTP)
path += "/"
}
path += "*"
router.Get(path, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// check if url has GET parameters
if strings.Contains(r.RequestURI, "?") {
// trim parameters as server is not gonna parse them
r.RequestURI = r.RequestURI[:strings.LastIndex(r.RequestURI, "?")]
fmt.Println(r.RequestURI)
}
info, err := os.Stat(fmt.Sprintf("%s%s", root, r.RequestURI))
if err == nil && info.IsDir() {
_, err = os.Stat(fmt.Sprintf("%s%s/index.html", root, r.RequestURI))
}
if os.IsNotExist(err) {
router.NotFoundHandler().ServeHTTP(w, r)
} else {
w.Header().Set("Cache-Control", "max-age=3600")
fs.ServeHTTP(w, r)
}
}))
}
func ServeZIP(w http.ResponseWriter, file io.ReadCloser) error {
w.Header().Set("Content-Type", "application/zip")
_, err := io.Copy(w, file)
return err
}
| true
|
c86ca843804a309378cb7d0c15e67b16bf8571a0
|
Go
|
noobwu/go-cms
|
/controllers/sys/role_dept.go
|
UTF-8
| 5,098
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
[
"Apache-2.0"
] |
permissive
|
package sys
import (
"github.com/astaxie/beego/validation"
"github.com/xiya-team/helpers"
"go-cms/controllers"
"encoding/json"
"go-cms/models"
"go-cms/pkg/e"
"go-cms/pkg/util"
"log"
"reflect"
"strings"
)
type RoleDeptController struct {
controllers.BaseController
}
func (c *RoleDeptController) Prepare() {
}
/**
获取列表数据
*/
func (c *RoleDeptController) Index() {
if c.Ctx.Input.IsPost() {
model := models.NewRoleDept()
data := c.Ctx.Input.RequestBody
//json数据封装到user对象中
err := json.Unmarshal(data, &model)
if err != nil {
c.JsonResult(e.ERROR, err.Error())
}
dataMap := make(map[string]interface{}, 0)
//开始时间
if !helpers.Empty(model.StartTime) {
dataMap["start_time"] = model.StartTime
}
//结束时间
if !helpers.Empty(model.EndTime) {
dataMap["end_time"] = model.EndTime
}
//查询字段
if !helpers.Empty(model.Fields) {
dataMap["fields"] = model.Fields
}
if helpers.Empty(model.Page) {
model.Page = 1
}else{
if model.Page <= 0 {
model.Page = 1
}
}
if helpers.Empty(model.PageSize) {
model.PageSize = 10
}else {
if model.Page <= 0 {
model.Page = 10
}
}
var orderBy string
if !helpers.Empty(model.OrderColumnName) && !helpers.Empty(model.OrderType){
orderBy = strings.Join([]string{model.OrderColumnName,model.OrderType}," ")
}else {
orderBy = "created_at DESC"
}
result, count,err := models.NewRoleDept().FindByMap((model.Page-1)*model.PageSize, model.PageSize, dataMap,orderBy)
if err != nil{
c.JsonResult(e.ERROR, "获取数据失败")
}
if !helpers.Empty(model.Fields){
fields := strings.Split(model.Fields, ",")
lists := c.FormatData(fields,result)
c.JsonResult(e.SUCCESS, "ok", lists, count, model.Page, model.PageSize)
}else {
c.JsonResult(e.SUCCESS, "ok", result, count, model.Page, model.PageSize)
}
}
}
/**
创建数据
*/
func (c *RoleDeptController) Create() {
if c.Ctx.Input.IsPut() {
model := models.NewRoleDept()
data := c.Ctx.Input.RequestBody
//1.压入数据 json数据封装到对象中
err := json.Unmarshal(data, model)
if err != nil {
c.JsonResult(e.ERROR, err.Error())
}
if err := c.ParseForm(model); err != nil {
c.JsonResult(e.ERROR, "赋值失败")
}
//2.验证
valid := validation.Validation{}
if b, _ := valid.Valid(model); !b {
for _, err := range valid.Errors {
log.Println(err.Key, err.Message)
}
c.JsonResult(e.ERROR, "验证失败")
}
//3.插入数据
if _, err := model.Create(); err != nil {
c.JsonResult(e.ERROR, "创建失败")
}
c.JsonResult(e.SUCCESS, "添加成功")
}
}
/**
更新数据
*/
func (c *RoleDeptController) Update() {
model := models.NewRoleDept()
data := c.Ctx.Input.RequestBody
//json数据封装到对象中
err := json.Unmarshal(data, model)
if err != nil {
c.JsonResult(e.ERROR, err.Error())
}
if c.Ctx.Input.IsPut() {
post, err := models.NewRoleDept().FindById(model.Id)
if err != nil||helpers.Empty(post) {
c.JsonResult(e.ERROR, "没找到数据")
}
valid := validation.Validation{}
if b, _ := valid.Valid(model); !b {
for _, err := range valid.Errors {
log.Println(err.Key, err.Message)
}
c.JsonResult(e.ERROR, "验证失败")
}
if _, err := model.Update(); err != nil {
c.JsonResult(e.ERROR, "修改失败")
}
c.JsonResult(e.SUCCESS, "修改成功")
}
//get
if c.Ctx.Input.IsPost() {
res,err := model.FindById(model.Id)
if err != nil{
c.JsonResult(e.ERROR, "获取失败")
}
c.JsonResult(e.SUCCESS, "获取成功",res)
}
}
/**
删除数据
*/
func (c *RoleDeptController) Delete() {
if c.Ctx.Input.IsDelete() {
model := models.NewRoleDept()
data := c.Ctx.Input.RequestBody
//json数据封装到user对象中
err := json.Unmarshal(data, model)
if err != nil {
c.JsonResult(e.ERROR, err.Error())
}
post, err := models.NewRoleDept().FindById(model.Id)
if err != nil||helpers.Empty(post) {
c.JsonResult(e.ERROR, "没找到数据")
}
if err := model.Delete(); err != nil {
c.JsonResult(e.ERROR, "删除失败")
}
c.JsonResult(e.SUCCESS, "删除成功")
}
}
func (c *RoleDeptController) BatchDelete() {
model := models.NewRoleDept()
var ids []int
if err := c.Ctx.Input.Bind(&ids, "ids"); err != nil {
c.JsonResult(e.ERROR, "赋值失败")
}
if err := model.DelBatch(ids); err != nil {
c.JsonResult(e.ERROR, "删除失败")
}
c.JsonResult(e.SUCCESS, "删除成功")
}
func (c *RoleDeptController) FormatData(fields []string,result []models.RoleDept) (res interface{}) {
lists := make([]map[string]interface{},0)
for key,item:=range fields {
fields[key] = util.ToFirstWordsUp(item)
}
for _, value := range result {
tmp := make(map[string]interface{}, 0)
t := reflect.TypeOf(value)
v := reflect.ValueOf(value)
for k := 0; k < t.NumField(); k++ {
if helpers.InArray(t.Field(k).Name,fields){
tmp[util.ToFirstWordsDown(t.Field(k).Name)] = v.Field(k).Interface()
}
}
lists = append(lists,tmp)
}
return lists
}
| true
|
f623625352ea4e391f368aec3517bbaf18a5fef4
|
Go
|
hima-del/Image-gallery-application
|
/04_assembled_codes/main.go
|
UTF-8
| 660
| 2.65625
| 3
|
[] |
no_license
|
[] |
no_license
|
package main
import (
"database/sql"
"fmt"
"net/http"
_ "github.com/lib/pq"
)
var db *sql.DB
func init() {
var err error
db, err = sql.Open("postgres", "postgres://himaja:password@localhost/image_gallery?sslmode=disable")
if err != nil {
panic(err)
}
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Println("you are connected to database")
}
func main() {
http.HandleFunc("/signup", signup)
http.HandleFunc("/login", login)
http.HandleFunc("/api/images/", getImages)
http.HandleFunc("/api/images/id/", getImage)
http.HandleFunc("/api/images/id/", deleteImage)
http.HandleFunc("/logout", logout)
http.ListenAndServe(":8080", nil)
}
| true
|
ea41eefbb1ad0c0461b71c69f3b3c36167bfa96b
|
Go
|
wgqi1126/ssp
|
/ssp/auction.go
|
UTF-8
| 826
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package ssp
import (
"fmt"
"log"
"net/http"
"strings"
)
const (
Currency = "USD"
)
type Auction struct {
ID string
PlacementID string
PlacementType Type
UserID string
FloorCPM float64
Width, Height int
UserAgent string
IP string
PriceCPM float64
AdMarkup string
NotificationURL string
}
func NewAuction() *Auction {
return &Auction{
ID: RandomID(42),
}
}
// Won will call the notication callback, if any
func (a *Auction) Won() {
n := a.NotificationURL
if n == "" {
return
}
url := strings.Replace(n, "${AUCTION_PRICE}", fmt.Sprintf("%0.2f", a.PriceCPM), -1)
go func() {
// TODO: retry?
res, err := http.Get(url)
if err != nil {
log.Printf("notification err: %s", err)
return
}
defer res.Body.Close()
}()
}
| true
|
a3f4fed0734f5c42ca14067c5cdff032f1111c4b
|
Go
|
yimeng/guestbook-demo
|
/main.go
|
UTF-8
| 398
| 2.65625
| 3
|
[] |
no_license
|
[] |
no_license
|
package main
import (
"github.com/gin-gonic/gin"
"os"
)
func main() {
hostname , err := os.Hostname()
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
if err != nil{
c.JSON(500, gin.H{
"message": "get hostname error",
})
}else {
c.JSON(200, gin.H{
"message": hostname,
})
}
})
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
| true
|
06682c87610f600555a62eab98059ba50e1e3988
|
Go
|
sapawarga/auth
|
/repository/mysql/mysql.go
|
UTF-8
| 4,182
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package mysql
import (
"bytes"
"context"
"database/sql"
"github.com/jmoiron/sqlx"
"github.com/sapawarga/auth/lib/constant"
"github.com/sapawarga/auth/model"
)
type Auth struct {
conn *sqlx.DB
}
func NewAuth(conn *sqlx.DB) *Auth {
return &Auth{
conn: conn,
}
}
// GetActorCurrentLoginByUsername ...
func (r *Auth) GetActorCurrentLoginByUsername(ctx context.Context, username string) (*model.Actor, error) {
user, err := r.getUserByUsername(ctx, username)
if err != nil {
return nil, err
}
return &model.Actor{
ID: user.ID,
Username: user.Username,
RoleLabel: model.RoleLabel[user.Role],
}, nil
}
// GetActorDetailByUsername ...
func (r *Auth) GetActorDetailByUsername(ctx context.Context, username string) (*model.UserDetail, error) {
user, err := r.getUserByUsername(ctx, username)
if err != nil {
return nil, err
}
mapLocations, err := r.getDetailLocationOfUser(ctx, user)
if err != nil {
return nil, err
}
return &model.UserDetail{
ID: user.ID, Username: user.Username, Name: user.Name,
Email: user.Email.String, Phone: user.Phone.String, Address: user.Address.String,
Role: user.Role,
RoleLabel: model.RoleLabel[user.Role],
RT: user.RT.String, RW: user.RW.String,
VillageID: mapLocations[constant.VILLAGE_KEY].ID,
Village: mapLocations[constant.VILLAGE_KEY].Name,
DistrictID: mapLocations[constant.DISTRICT_KEY].ID,
District: mapLocations[constant.DISTRICT_KEY].Name,
RegencyID: mapLocations[constant.REGENCY_KEY].ID,
Regency: mapLocations[constant.REGENCY_KEY].Name,
Latitude: user.Latitude.String,
Longitude: user.Longitude.String,
BirthDate: user.BirthDate.Time,
PhotoUrl: user.PhotoUrl.String,
}, nil
}
func (r *Auth) getDetailLocationOfUser(ctx context.Context, user *model.User) (map[string]*model.Location, error) {
var mapLocation = make(map[string]*model.Location)
if user.KelurahanID.Valid {
kelurahan, err := r.getLocationByID(ctx, user.KelurahanID.Int64)
if err != nil {
return nil, err
}
mapLocation[constant.VILLAGE_KEY] = kelurahan
}
if user.KecamatanID.Valid {
kecamatan, err := r.getLocationByID(ctx, user.KecamatanID.Int64)
if err != nil {
return nil, err
}
mapLocation[constant.DISTRICT_KEY] = kecamatan
}
if user.KabKotaID.Valid {
kabKota, err := r.getLocationByID(ctx, user.KabKotaID.Int64)
if err != nil {
return nil, err
}
mapLocation[constant.REGENCY_KEY] = kabKota
}
return mapLocation, nil
}
func (r *Auth) getUserByUsername(ctx context.Context, username string) (*model.User, error) {
var query bytes.Buffer
var err error
var result = &model.User{}
query.WriteString(` SELECT id, username, email, last_login_at, role, name, phone, address, job_type_id, education_level_id,
birth_date, rt, rw, kel_id, kec_id, kabkota_id, lat, lon, photo_url, facebook, twitter, instagram, password_updated_at,
profile_updated_at, last_access_at
FROM user WHERE username = ? AND status = ?`)
if ctx != nil {
err = r.conn.GetContext(ctx, result, query.String(), username, 10)
} else {
err = r.conn.Get(result, query.String(), username, 10)
}
if err == sql.ErrNoRows || err != nil {
return nil, err
}
return result, nil
}
func (r *Auth) getLocationByID(ctx context.Context, id int64) (*model.Location, error) {
var query bytes.Buffer
var err error
var result = &model.Location{}
query.WriteString(` SELECT id, name FROM areas WHERE id = ? and status = 1`)
if ctx != nil {
err = r.conn.GetContext(ctx, result, query.String(), id)
} else {
err = r.conn.Get(result, query.String(), id)
}
if err != sql.ErrNoRows || err != nil {
return nil, err
}
return result, nil
}
// func (r *Auth) getJobTypeByID(ctx context.Context, id int64) (*model.Job, error) {
// var query bytes.Buffer
// var err error
// var result = &model.Job{}
// query.WriteString(`SELECT id, title FROM job_types WHERE id = ? AND status = 10`)
// if ctx != nil {
// err = r.conn.GetContext(ctx, result, query.String(), id)
// } else {
// err = r.conn.Get(result, query.String(), id)
// }
// if err != sql.ErrNoRows || err != nil {
// return nil, err
// }
// return result, nil
// }
| true
|
9a4b3f9eba948206d9c126aa523fc66ddcf00b21
|
Go
|
ceramicyu/web2
|
/src/github.com/mikespook/golib/debug/goroutine.go
|
UTF-8
| 1,330
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package debug
import (
"fmt"
"io"
"os"
"runtime"
"strings"
)
func PrintGoroutines(allFrame bool) {
FprintGoroutines(os.Stderr, allFrame)
}
func FprintGoroutines(w io.Writer, allFrame bool) {
ng := runtime.NumGoroutine()
p := make([]runtime.StackRecord, ng)
n, ok := runtime.GoroutineProfile(p)
if !ok {
panic("The slice is too small too put all records")
return
}
for i := 0; i < n; i++ {
printStackRecord(w, i, p[i].Stack(), allFrame)
}
}
// stolen from `runtime/pprof`
func printStackRecord(w io.Writer, index int, stk []uintptr, allFrame bool) {
wasPanic := false
for i, pc := range stk {
f := runtime.FuncForPC(pc)
if f == nil {
fmt.Fprintf(w, "#\t%#x\n", pc)
wasPanic = false
} else {
tracepc := pc
// Back up to call instruction.
if i > 0 && pc > f.Entry() && !wasPanic {
if runtime.GOARCH == "386" || runtime.GOARCH == "amd64" {
tracepc--
} else {
tracepc -= 4 // arm, etc
}
}
file, line := f.FileLine(tracepc)
name := f.Name()
wasPanic = name == "runtime.panic"
if name == "runtime.goexit" || !allFrame && (strings.HasPrefix(name, "runtime.") || name == "bgsweep" || name == "runfinq" || name == "main.printGoroutines") {
continue
}
fmt.Fprintf(w, "%d.\t%#x\t%s+%#x\t%s:%d\n", index, pc, name, pc-f.Entry(), file, line)
}
}
}
| true
|
7a4408e585b27dfa57e1af862619867da4dae49b
|
Go
|
kerenbenzion/provision
|
/models/role_test.go
|
UTF-8
| 7,678
| 3.015625
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
package models
import (
"log"
"testing"
)
func twoClaims(frags ...string) []*Claim {
if len(frags) != 6 {
panic("Need 6 args")
}
log.Printf("Making %v and %v", frags[0:3], frags[3:6])
return makeClaims(frags...)
}
func claimContains(t *testing.T, c []*Claim) {
t.Helper()
a, b := c[0], c[1]
if a.Contains(b) {
t.Logf("Claim '%s' contains '%s'", a, b)
} else if b.Contains(a) {
t.Errorf("ERROR: Claim '%s' does not contain '%s'", a, b)
} else {
t.Errorf("ERROR: Claims '%s' and '%s' are disjoint", a, b)
}
}
func claimDoesNotContain(t *testing.T, c []*Claim) {
t.Helper()
a, b := c[0], c[1]
if a.Contains(b) {
t.Errorf("ERROR Claim '%s' contains '%s'", a, b)
} else {
t.Logf("Claim '%s' does not contain '%s'", a, b)
}
}
func claimsAreDisjoint(t *testing.T, c []*Claim) {
t.Helper()
a, b := c[0], c[1]
if a.Contains(b) {
t.Errorf("ERROR: Claim '%s' contains '%s'", a, b)
} else if b.Contains(a) {
t.Errorf("ERROR: Claim '%s' contains '%s'", b, a)
} else {
t.Logf("Claims '%s' and '%s' are disjoint", a, b)
}
}
func claimsAreOrdered(t *testing.T, c []*Claim) {
t.Helper()
a, b := c[0], c[1]
if a.Contains(b) && !b.Contains(a) {
t.Logf("Claims '%s' and '%s' are ordered", a, b)
} else {
t.Errorf("ERROR: Claims '%s' and '%s' are not ordered", a, b)
}
}
func claimsAreEqual(t *testing.T, c []*Claim) {
t.Helper()
a, b := c[0], c[1]
if a.Contains(b) && b.Contains(a) {
t.Logf("Claims '%s' and '%s' are equal", a, b)
} else {
t.Errorf("ERROR: Claims '%s' and '%s' are not equal", a, b)
}
}
func TestRoleClaims(t *testing.T) {
claimContains(t, twoClaims("*", "*", "*", "", "", ""))
claimsAreOrdered(t, twoClaims("*", "*", "*", "", "", ""))
claimDoesNotContain(t, twoClaims("", "", "", "*", "*", "*"))
claimsAreDisjoint(t, twoClaims("machines", "*", "*", "bootenvs", "*", "*"))
claimsAreOrdered(t, twoClaims("*", "*", "*", "machines", "delete", "foo"))
claimsAreOrdered(t, twoClaims("machines", "*", "*", "machines", "delete", "foo"))
claimsAreOrdered(t, twoClaims("machines", "delete", "*", "machines", "delete", "foo"))
claimsAreOrdered(t, twoClaims("machines", "delete", "foo,bar", "machines", "delete", "foo"))
claimsAreEqual(t, twoClaims("machines", "delete", "foo", "machines", "delete", "foo"))
claimsAreDisjoint(t, twoClaims("machines", "delete", "bar", "machines", "delete", "foo"))
claimsAreEqual(t, twoClaims("machines", "update:/Foo/Bar/Baz", "foo", "machines", "update:/Foo/Bar/Baz", "foo"))
claimsAreOrdered(t, twoClaims("machines", "update:/Foo/Bar", "foo", "machines", "update:/Foo/Bar/Baz", "foo"))
claimsAreOrdered(t, twoClaims("machines", "update:/Foo", "foo", "machines", "update:/Foo/Bar/Baz", "foo"))
claimsAreOrdered(t, twoClaims("machines", "update:", "foo", "machines", "update:/Foo/Bar/Baz", "foo"))
claimsAreOrdered(t, twoClaims("machines", "update", "foo", "machines", "update:/Foo/Bar/Baz", "foo"))
claimsAreDisjoint(t, twoClaims("machines", "update:/", "foo", "machines", "update:/Foo/Bar/Baz", "foo"))
claimsAreDisjoint(t, twoClaims("machines", "update:/Bar", "foo", "machines", "update:/Foo/Bar/Baz", "foo"))
claimsAreDisjoint(t, twoClaims("machines", "update:/Foo/Baz", "foo", "machines", "update:/Foo/Bar/Baz", "foo"))
claimsAreDisjoint(t, twoClaims("machines", "update:/Foo/Baz/Bar", "foo", "machines", "update:/Foo/Bar/Baz", "foo"))
claimsAreEqual(t, twoClaims("machines", "action:spike", "foo", "machines", "action:spike", "foo"))
claimsAreOrdered(t, twoClaims("machines", "action", "foo", "machines", "action:spike", "foo"))
}
func roleContains(t *testing.T, a, b *Role) {
t.Helper()
if a.Contains(b) {
t.Logf("Role '%s' contains '%s'", a.Name, b.Name)
} else if b.Contains(a) {
t.Errorf("ERROR: Role '%s' does not contain '%s'", a.Name, b.Name)
} else {
t.Errorf("ERROR: Roles '%s' and '%s' are disjoint", a.Name, b.Name)
}
}
func roleDoesNotContain(t *testing.T, a, b *Role) {
t.Helper()
if a.Contains(b) {
t.Errorf("ERROR Role '%s' contains '%s'", a.Name, b.Name)
} else {
t.Logf("Role '%s' does not contain '%s'", a.Name, b.Name)
}
}
func rolesAreDisjoint(t *testing.T, a, b *Role) {
t.Helper()
if a.Contains(b) {
t.Errorf("ERROR: Role '%s' contains '%s'", a.Name, b.Name)
} else if b.Contains(a) {
t.Errorf("ERROR: Role '%s' contains '%s'", b.Name, a.Name)
} else {
t.Logf("Roles '%s' and '%s' are disjoint", a.Name, b.Name)
}
}
func rolesAreOrdered(t *testing.T, a, b *Role) {
t.Helper()
if a.Contains(b) && !b.Contains(a) {
t.Logf("Roles '%s' and '%s' are ordered", a.Name, b.Name)
} else {
t.Errorf("ERROR: Roles '%s' and '%s' are not ordered", a.Name, b.Name)
}
}
func rolesAreEqual(t *testing.T, a, b *Role) {
t.Helper()
if a.Contains(b) && b.Contains(a) {
t.Logf("Roles '%s' and '%s' are equal", a.Name, b.Name)
} else {
t.Errorf("ERROR: Roles '%s' and '%s' are not equal", a.Name, b.Name)
}
}
func TestRoles(t *testing.T) {
roleContains(t, MakeRole("a", "*", "*", "*"), MakeRole("b", "", "", ""))
roleDoesNotContain(t, MakeRole("b", "", "", ""), MakeRole("a", "*", "*", "*"))
rolesAreOrdered(t, MakeRole("a", "*", "*", "*"), MakeRole("b", "", "", ""))
roleContains(t, MakeRole("a", "*", "*", "*"), MakeRole("b",
"machines", "*", "*",
"bootenvs", "*", "*"))
rolesAreEqual(t, MakeRole("a",
"bootenvs", "*", "*",
"machines", "*", "*"),
MakeRole("b",
"machines", "*", "*",
"bootenvs", "*", "*"))
rolesAreOrdered(t,
MakeRole("a", "*", "*", "*"),
MakeRole("b",
"bootenvs", "update:/Foo", "foo",
"bootenvs", "update:/Bar", "foo",
"bootenvs", "update:/Baz", "foo"))
rolesAreOrdered(t,
MakeRole("a", "bootenvs", "*", "*"),
MakeRole("b",
"bootenvs", "update:/Foo", "foo",
"bootenvs", "update:/Bar", "foo",
"bootenvs", "update:/Baz", "foo"))
rolesAreOrdered(t,
MakeRole("a", "bootenvs", "update", "*"),
MakeRole("b",
"bootenvs", "update:/Foo", "foo",
"bootenvs", "update:/Bar", "foo",
"bootenvs", "update:/Baz", "foo"))
rolesAreOrdered(t,
MakeRole("a", "bootenvs", "update:", "*"),
MakeRole("b",
"bootenvs", "update:/Foo", "foo",
"bootenvs", "update:/Bar", "foo",
"bootenvs", "update:/Baz", "foo"))
rolesAreOrdered(t,
MakeRole("a",
"bootenvs", "update:/Foo", "*",
"bootenvs", "update:/Bar", "*",
"bootenvs", "update:/Baz", "*"),
MakeRole("b",
"bootenvs", "update:/Foo", "foo",
"bootenvs", "update:/Bar", "foo",
"bootenvs", "update:/Baz", "foo"))
rolesAreOrdered(t,
MakeRole("a",
"bootenvs", "update:/Foo", "*",
"bootenvs", "update:/Bar", "*",
"bootenvs", "update:/Baz", "*"),
MakeRole("b",
"bootenvs", "update:/Bar", "foo",
"bootenvs", "update:/Baz", "foo"))
rolesAreOrdered(t,
MakeRole("a",
"bootenvs", "update:/Foo", "*",
"bootenvs", "update:/Bar", "*",
"bootenvs", "update:/Baz", "*"),
MakeRole("b",
"bootenvs", "update:/Baz", "foo"))
rolesAreEqual(t,
MakeRole("a",
"bootenvs", "update:/Foo", "foo",
"bootenvs", "update:/Bar", "foo",
"bootenvs", "update:/Baz", "foo"),
MakeRole("b",
"bootenvs", "update:/Foo", "foo",
"bootenvs", "update:/Bar", "foo",
"bootenvs", "update:/Baz", "foo"))
rolesAreDisjoint(t,
MakeRole("a",
"bootenvs", "update:/Foo", "foo",
"bootenvs", "update:/Bark", "foo",
"bootenvs", "update:/Baz", "foo"),
MakeRole("b",
"bootenvs", "update:/Foo", "foo",
"bootenvs", "update:/Bar", "foo",
"bootenvs", "update:/Baz", "foo"))
rolesAreDisjoint(t,
MakeRole("a",
"bootenvs", "update:/Foo", "foo",
"bootenvs", "update:/Bar", "bar",
"bootenvs", "update:/Baz", "foo"),
MakeRole("b",
"bootenvs", "update:/Foo", "foo",
"bootenvs", "update:/Bar", "foo",
"bootenvs", "update:/Baz", "foo"))
}
| true
|
16c4f2cdad7fb997d60501090577a20be4dcd044
|
Go
|
ironzhang/zerone
|
/rpc/context.go
|
UTF-8
| 684
| 2.6875
| 3
|
[] |
no_license
|
[] |
no_license
|
package rpc
import "context"
type keyTraceID struct{}
func WithTraceID(ctx context.Context, traceID string) context.Context {
return context.WithValue(ctx, keyTraceID{}, traceID)
}
func ParseTraceID(ctx context.Context) (string, bool) {
value := ctx.Value(keyTraceID{})
if traceID, ok := value.(string); ok {
return traceID, true
}
return "", false
}
type keyVerbose struct{}
func WithVerbose(ctx context.Context, verbose int) context.Context {
return context.WithValue(ctx, keyVerbose{}, verbose)
}
func ParseVerbose(ctx context.Context) (int, bool) {
value := ctx.Value(keyVerbose{})
if verbose, ok := value.(int); ok {
return verbose, true
}
return 0, false
}
| true
|
f65a717ea850989c566180dd91debe6f7ad9a990
|
Go
|
rebuy-de/aws-nuke
|
/resources/sagemaker-models.go
|
UTF-8
| 1,059
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package resources
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sagemaker"
)
type SageMakerModel struct {
svc *sagemaker.SageMaker
modelName *string
}
func init() {
register("SageMakerModel", ListSageMakerModels)
}
func ListSageMakerModels(sess *session.Session) ([]Resource, error) {
svc := sagemaker.New(sess)
resources := []Resource{}
params := &sagemaker.ListModelsInput{
MaxResults: aws.Int64(30),
}
for {
resp, err := svc.ListModels(params)
if err != nil {
return nil, err
}
for _, model := range resp.Models {
resources = append(resources, &SageMakerModel{
svc: svc,
modelName: model.ModelName,
})
}
if resp.NextToken == nil {
break
}
params.NextToken = resp.NextToken
}
return resources, nil
}
func (f *SageMakerModel) Remove() error {
_, err := f.svc.DeleteModel(&sagemaker.DeleteModelInput{
ModelName: f.modelName,
})
return err
}
func (f *SageMakerModel) String() string {
return *f.modelName
}
| true
|
19023d4996634aec1896a06eeac19cbbd84a7354
|
Go
|
amortaza/bsn-flux-drivers
|
/stdsql/row_inserter.go
|
UTF-8
| 1,242
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
[
"MIT"
] |
permissive
|
package stdsql
import (
"fmt"
"github.com/amortaza/bsn/flux"
"github.com/amortaza/bsn/flux/normalization"
"github.com/amortaza/bsn/flux/utils"
)
type RowInserter struct {
sqlRunner *SQLRunner
}
func NewRowInserter(sqlRunner *SQLRunner) *RowInserter {
return &RowInserter{
sqlRunner,
}
}
func (inserter *RowInserter) Insert(table string, values *flux.RecordMap) (string, error) {
newId := utils.NewUUID()
sql := inserter.generateSQL(table, newId, values)
return newId, inserter.sqlRunner.Run(sql)
}
func (inserter *RowInserter) generateSQL(table string, newId string, values *flux.RecordMap) string {
columnsSQL := "`" + normalization.PrimaryKeyFieldname + "`"
valuesSQL := fmt.Sprintf("'%s'", newId)
for column, value := range values.Data {
sqlValue := inserter.valueToSQL(value)
columnsSQL = fmt.Sprintf("%s, `%s`", columnsSQL, column)
valuesSQL = fmt.Sprintf("%s, %s", valuesSQL, sqlValue)
}
return fmt.Sprintf("INSERT INTO `%s` (%s) VALUES(%s);", table, columnsSQL, valuesSQL)
}
func (inserter *RowInserter) valueToSQL(value interface{}) string {
sql := ""
if stringValue, ok := value.(string); ok {
sql = fmt.Sprintf("'%s'", stringValue)
} else {
sql = fmt.Sprintf("%v", value)
}
return sql
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.