_id
stringlengths
40
40
text
stringlengths
81
2.19k
title
stringclasses
1 value
f301ec621764427bbc53654300256c89df257fc6
--- +++ @@ -3,9 +3,9 @@ import ( "flag" "fmt" + "io" "net/http" "os" - "github.com/gorilla/handlers" ) const VERSION = "0.1.0" @@ -32,11 +32,25 @@ fmt.Println(err) os.Exit(1) } - - http.Handle("/", handlers.CombinedLoggingHandler(os.Stdout, http.FileServer(http.Dir(clientDir)))) + + http.Handle("/", LoggingHandler(os.Stdout, http.FileServer(http.Dir(clientDir)))) if err := http.ListenAndServe(":"+os.Getenv("PORT"), nil); err != nil { fmt.Println(err) os.Exit(1) } } + +type loggingHandler struct { + writer io.Writer + handler http.Handler +} + +func (h loggingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + fmt.Fprintf(h.writer, "%s %s %s", r.Method, r.RequestURI, r.Header.Get("User-Agent")) + h.handler.ServeHTTP(w, r) +} + +func LoggingHandler(w io.Writer, h http.Handler) http.Handler { + return loggingHandler{w, h} +}
8491877a9019062c68e21a05a7cf0b73f29b49c7
--- +++ @@ -5,6 +5,7 @@ "fmt" _ "v.io/core/veyron/profiles" + "v.io/core/veyron2" "v.io/core/veyron2/rt" "pingpong" @@ -16,8 +17,8 @@ panic(err) } defer runtime.Cleanup() - - log := runtime.Logger() + ctx := runtime.NewContext() + log := veyron2.GetLogger(ctx) s := pingpong.PingPongClient("pingpong") pong, err := s.Ping(runtime.NewContext(), "PING")
82d6616b8cff53de886f1d5fc9cca64ee9e68deb
--- +++ @@ -1,22 +1,29 @@ package octokit import ( - "github.com/lostisland/go-sawyer" + "github.com/jtacoma/uritemplates" "net/url" ) + +// TODO: use sawyer.Hyperlink type M map[string]interface{} type Hyperlink string -// TODO: find out a way to not wrapping sawyer.Hyperlink like this func (l *Hyperlink) Expand(m M) (u *url.URL, err error) { - link := sawyer.Hyperlink(string(*l)) - sawyerM := sawyer.M{} - for k, v := range m { - sawyerM[k] = v + template, e := uritemplates.Parse(string(*l)) + if e != nil { + err = e + return } - u, err = link.Expand(sawyerM) + expanded, e := template.Expand(m) + if e != nil { + err = e + return + } + + u, err = url.Parse(expanded) return }
3ecb98129a0d5191969bc4c4046aa0a8d893852d
--- +++ @@ -2,6 +2,7 @@ import ( "flag" + "fmt" "os" "os/exec" "os/signal" @@ -15,7 +16,15 @@ flgIgnoreSigPipe = flag.Bool("i", false, "ignore SIGPIPE") flgClearErrorHandler = flag.Bool("c", false, "clear error handler") flgStdout = flag.Bool("s", false, "output to stdout") + flgWriteThrough = flag.Bool("w", false, "use WriteThrough") ) + +func printError(e error) { + if e == nil { + return + } + fmt.Fprintf(os.Stderr, "error: %T %#v\n", e, e) +} func main() { flag.Parse() @@ -45,7 +54,11 @@ } for { - logger.Error("foo", nil) + if *flgWriteThrough { + printError(logger.WriteThrough([]byte("foo\n"))) + } else { + printError(logger.Error("foo", nil)) + } time.Sleep(time.Second) } }
69b70fc86ecf34bdee61e7e0a0f4a4574dde2c3d
--- +++ @@ -5,11 +5,13 @@ "github.com/neliseev/logger" ) -// Defaults +// Defaults vars +var msgSep = byte(":") + +// Constants const maxTCPQueries int = 256 const tcpIdleTimeout time.Duration = 60 * time.Second const rtimeout time.Duration = 2 * time.Second // Socket read timeout -const msgSep []byte = []byte(":") const udpMsgSize int = 508 // RFC 791 (Min IP Size - Max IP Header Size - UDP Header Size) const maxMsgSize int = 128 // ToDo Set configurable?
946342bf0d34850bec4be1cd5ac94977112edc8e
--- +++ @@ -11,6 +11,15 @@ DbName string TokenTable string UserTable string + } + Ssl struct { + Key string + Sertificate string + } + Router struct { + Register string + Login string + Validate string } }
b5cf04e6709bca6c29d1b42d4ae9a0fa6d02c222
--- +++ @@ -1 +1,15 @@ package negronicache + +func TestCache_NewMemoryCache(t testing.T) { + c := NewMemoryCache() + assert.NotNil(t, c.fs) + assert.NotNil(t, c.stale) +} + +func TestCache_NewDiskCache(t testing.T) { + c, err := NewDiskCache("./cache") + assert.Nil(t, err) + + assert.NotNil(t, c.fs) + assert.NotNil(t, c.stale) +}
81a277da2b320e5a73164436fd62a41f30a9beaf
--- +++ @@ -18,3 +18,8 @@ _, err = s.Announce(ih, 0, true) require.EqualError(t, err, "no initial nodes") } + +func TestDefaultTraversalBloomFilterCharacteristics(t *testing.T) { + bf := newBloomFilterForTraversal() + t.Logf("%d bits with %d hashes per item", bf.Cap(), bf.K()) +}
9b343d990ef728f08e23c6fee299bcf30e59b039
--- +++ @@ -16,8 +16,13 @@ } for _, c := range cases { got, _ := ParseMaintainer(c.in) - if got != c.want { - t.Errorf("ParseMaintainer(%q) == %v, want %v", c.in, got, c.want) + if got.Name != c.want.Name { + t.Errorf( + "ParseMaintainer(%q).Name == %q, want %q", + c.in, + got.Name, + c.want.Name, + ) } } }
51f6ea9733e0df4a123b27448f58325e1a8bb8c4
--- +++ @@ -11,7 +11,7 @@ "runtime" "testing" - "github.com/hyperledger/fabric/common/tools/cryptogen/metadata" + "github.com/hyperledger/fabric/common/tools/configtxlator/metadata" "github.com/stretchr/testify/assert" )
5e6214b12d9a839ade379a270690b51ec41e7195
--- +++ @@ -6,8 +6,8 @@ "io/ioutil" "os" - "github.com/robertkrimen/otto" "github.com/robertkrimen/otto/underscore" + "github.com/xyproto/otto" ) var flag_underscore *bool = flag.Bool("underscore", true, "Load underscore into the runtime environment")
42fb45fefb1a055b29a684fb30515e4d87822cbd
--- +++ @@ -12,7 +12,10 @@ var port string func main() { - var config mint.Config + config := mint.Config{ + SendSessionTickets: true, + } + config.Init(false) flag.StringVar(&port, "port", "4430", "port")
de80557a1bd3e2ff1e06e8a1d8d382b4fff9b8d6
--- +++ @@ -13,26 +13,24 @@ // FindArtNetIP finds the matching interface with an IP address inside of the addressRange func FindArtNetIP() (net.IP, error) { - var ip net.IP - _, cidrnet, _ := net.ParseCIDR(addressRange) addrs, err := net.InterfaceAddrs() if err != nil { - return ip, fmt.Errorf("error getting ips: %s", err) + return nil, fmt.Errorf("error getting ips: %s", err) } for _, addr := range addrs { - ip = addr.(*net.IPNet).IP + ip := addr.(*net.IPNet).IP if strings.Contains(ip.String(), ":") { continue } if cidrnet.Contains(ip) { - break + return ip, nil } } - return ip, nil + return nil, nil }
1761a581e0bc09861d13260de44102f90046c324
--- +++ @@ -16,20 +16,7 @@ // FileEntry helps reading a torrent file. type FileEntry struct { *torrent.File - Reader *torrent.Reader -} - -// Seek seeks to the correct file position, paying attention to the offset. -func (f FileEntry) Seek(offset int64, whence int) (int64, error) { - return (*f.Reader).Seek(offset+f.File.Offset(), whence) -} - -func (f FileEntry) Read(p []byte) (n int, err error) { - return (*f.Reader).Read(p) -} - -func (f FileEntry) Close() error { - return (*f.Reader).Close() + torrent.Reader } // NewFileReader sets up a torrent file for streaming reading. @@ -44,6 +31,6 @@ return &FileEntry{ File: f, - Reader: &reader, + Reader: reader, }, err }
8359b7406152a9b7562584686e2d7a7ce5bbfe50
--- +++ @@ -1,6 +1,9 @@ package alertsv2 -import "net/url" +import ( + "net/url" + "errors" +) type ExecuteCustomActionRequest struct { *Identifier @@ -13,6 +16,9 @@ func (r *ExecuteCustomActionRequest) GenerateUrl() (string, url.Values, error) { path, params, err := r.Identifier.GenerateUrl() + if r.ActionName == "" { + return "", nil, errors.New("ActionName should be provided") + } return path + "/actions/" + r.ActionName, params, err; }
2fdb6907e6b959e6257e086604f84a905d9c6ac7
--- +++ @@ -1,6 +1,7 @@ package main import ( + "code.google.com/p/go.crypto/ssh/terminal" flags "github.com/jessevdk/go-flags" "github.com/monochromegane/the_platinum_searcher/search" "github.com/monochromegane/the_platinum_searcher/search/option" @@ -18,6 +19,11 @@ args, _ := flags.Parse(&opts) + if !terminal.IsTerminal(int(os.Stdout.Fd())) { + opts.NoColor = true + opts.NoGroup = true + } + var root = "." if len(args) == 0 {
b0ef20d4f8883925ae2bf38282395b3a21a81497
--- +++ @@ -19,7 +19,7 @@ port := os.Getenv("DEEVA_MANAGER_PORT") if len(port) == 0 { - port = "9090" + port = "8080" } log.Printf("Starting in %s mode on port %s\n", gin.Mode(), port)
919e17af9fabd8520e38922fadc9484e6a1234a5
--- +++ @@ -1,19 +1,21 @@ package sss import ( - "testing" + "fmt" ) -func TestRoundtrip(t *testing.T) { +func Example() { + // split into 30 shares, of which only 2 are required to combine n := 30 k := 2 - expected := "well hello there!" - shares, err := Split(n, k, []byte(expected)) + secret := "well hello there!" + shares, err := Split(n, k, []byte(secret)) if err != nil { - t.Error(err) + fmt.Println(err) } + // select a random subset of the total shares subset := make(map[int][]byte, k) for x, y := range shares { subset[x] = y @@ -22,8 +24,6 @@ } } - actual := string(Combine(subset)) - if actual != expected { - t.Errorf("Expected %v but was %v", expected, actual) - } + fmt.Println(string(Combine(subset))) + // Output: well hello there! }
9fae8b28922bca7469dba400b6d945c259a78f70
--- +++ @@ -6,6 +6,7 @@ "log" "net/http" "os" + "strings" ) const aURL = "http://artii.herokuapp.com" @@ -21,9 +22,10 @@ switch args[0] { case "fonts": fmt.Printf("%v", fontList()) + return } - fmt.Println(draw(args[0])) + fmt.Println(draw(args)) } func fontList() string { @@ -44,8 +46,10 @@ return s } -func draw(s string) string { - url := fmt.Sprintf("%s/make?text=%s", aURL, s) +func draw(s []string) string { + f := strings.Split(s[0], " ") + js := strings.Join(f, "+") + url := fmt.Sprintf("%s/make?text=%s", aURL, js) resp, err := http.Get(url) if err != nil {
88c5041300ef4670d5a6f2887f92243b57fa6be8
--- +++ @@ -1,6 +1,7 @@ package main import ( + "io/ioutil" "os" slackreporter "github.com/ariarijp/horenso-reporter-slack/reporter" @@ -11,8 +12,13 @@ token := os.Getenv("SLACK_TOKEN") groupName := os.Getenv("SLACK_GROUP") + stdin, err := ioutil.ReadAll(os.Stdin) + if err != nil { + panic(err) + } + api := slack.New(token) - r := slackreporter.GetReport([]byte(os.Args[1])) + r := slackreporter.GetReport(stdin) slackreporter.NotifyToGroup(*api, r, groupName) }
d104ebdf619fd589c1e69edcdb1086e65e28c64d
--- +++ @@ -2,7 +2,7 @@ // DiscountParams is the set of parameters that can be used when deleting a discount. type DiscountParams struct { - Params + Params } // Discount is the resource representing a Stripe discount. @@ -15,4 +15,3 @@ Sub string `json:"subscription"` Deleted bool `json:"deleted"` } -
0c643d4144cbffd995d76da04052656aa81b9f62
--- +++ @@ -1,7 +1,7 @@ package main -// safe -- 7.01ns/op -// unsafe -- 0.60ns/op +// safe -- 15.9ns/op +// unsafe -- 1.6ns/op import ( "fmt" @@ -12,9 +12,13 @@ // can we unsafe cast to unwrap all the interface layers? Or is the value in // memory different now? No! We have a new layer of indirection... func unsafeErr(err error) uintptr { - p1 := (uintptr)(unsafe.Pointer(&err)) - p2 := (*uintptr)(unsafe.Pointer(p1+8)) - return *(*uintptr)(unsafe.Pointer(*p2)) + if err != nil { + p1 := (uintptr)(unsafe.Pointer(&err)) + p2 := (*uintptr)(unsafe.Pointer(p1+8)) + return *(*uintptr)(unsafe.Pointer(*p2)) + } else { + return 0 + } } // Safe way, type assertion
bb6d294cb978864b28d05d12308867039509c87f
--- +++ @@ -3,6 +3,30 @@ import "Jira__backend/models" var UsersListFromFakeDB = models.Users{ - models.User{Name: "User1", Data: "21.08.1997", Phone: "8(999)999-99-99"}, - models.User{Name: "User2", Data: "10.01.1997", Phone: "8(999)999-99-99"}, + models.User{ + Email: "mbazley1@a8.net", FirstName: "Jeremy", LastName: "Moore", + Tasks: models.Tasks{}, Password: "??04*products*GRAIN*began*58??", + Bio: `Spent childhood selling wooden tops in Pensacola, FL. In 2008 I +was testing the market for sheep in Miami, FL. Was quite successful at promoting +yard waste in Tampa, FL. Spent 2001-2006 implementing bullwhips in the government +sector. Had a brief career buying and selling bullwhips in Edison, NJ. A real dynamo +when it comes to selling action figures for farmers.`}, + + models.User{ + Email: "rcattermull0@storify.com", FirstName: "Crawford", LastName: "Eustis", + Tasks: models.Tasks{}, Password: "//56.belong.SURE.fresh.16//", + Bio: `Once had a dream of creating marketing channels for jigsaw puzzles in +Gainesville, FL. Spent 2001-2008 building bathtub gin for the government. What gets +me going now is consulting about Yugos on Wall Street. Earned praise for marketing +jack-in-the-boxes in Mexico. At the moment I'm selling dogmas with no outside help. +Enthusiastic about getting my feet wet with tobacco in Jacksonville, FL.`}, + + models.User{ + Email: "bputtan6@discovery.com", FirstName: "Kurtis", LastName: "Chambers", + Tasks: models.Tasks{}, Password: "--06$last$REST$prepared$76--", + Bio: `Spent childhood licensing banjos in Salisbury, MD. Spent 2001-2008 +analyzing puppets in Ohio. Once had a dream of implementing mosquito repellent on +Wall Street. Managed a small team investing in hugs in New York, NY. Was quite +successful at supervising the production of glucose in Naples, FL. Have a strong +interest in getting my feet wet with psoriasis in Fort Lauderdale, FL.`}, }
6938b44bb96b0f0c057aafb1cc81c159fc8def48
--- +++ @@ -1,16 +1,5 @@ package main -import ( - "github.com/grsakea/kappastat/backend" -) - func main() { - launchBackend() launchFrontend() } - -func launchBackend() *backend.Controller { - c := backend.SetupController("twitch") - go c.Loop() - return c -}
706570f82a9a921be943e0c196049969c3eaf25e
--- +++ @@ -5,6 +5,7 @@ "os" "github.com/jutkko/mindown/input" + "github.com/jutkko/mindown/output" "github.com/urfave/cli" ) @@ -18,15 +19,22 @@ Value: "input.txt", Usage: "input file name", }, + cli.StringFlag{ + Name: "output-file", + Value: "output.txt", + Usage: "output file name", + }, } app.Action = func(c *cli.Context) error { fmt.Printf("Input file name: %s\n", c.String("input-file")) + fmt.Printf("Input file name: %s\n", c.String("output-file")) graph, err := input.ParseOpml(c.String("input-file")) if err != nil { panic(err.Error()) } + err = output.WriteMarkdown(c.String("output-file"), graph) if err != nil { panic(err.Error()) }
d6f916303eba4957b5c5708457513266df4d917a
--- +++ @@ -3,9 +3,10 @@ import ( "github.com/XenoPhex/jibber_jabber" - // . "github.com/cloudfoundry-incubator/cf-test-helpers/cf" + . "github.com/cloudfoundry-incubator/cf-test-helpers/cf" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + . "github.com/onsi/gomega/gbytes" ) var _ = Describe("i18n support and language detection", func() { @@ -15,7 +16,7 @@ Expect(userLocale).To(Equal("fr-FR"), "This test can only be run when the system's language is set to french") }) - It("does nothing yet", func() { - + It("returns the french translation for cf quota", func() { + Eventually(Cf("help", "quota")).Should(Say("Montrez l'information de quota")) }) })
f6cf282fdcf0af6609047fa373938c3350866c7e
--- +++ @@ -15,4 +15,18 @@ r, _ = Eval(Filter(""), todoist.Item{}) assert.Equal(t, r, true, "they should be equal") + + r, _ = Eval(Filter("p1 | p2"), todoist.Item{Priority: 1}) + assert.Equal(t, r, true, "they should be equal") + r, _ = Eval(Filter("p1 | p2"), todoist.Item{Priority: 2}) + assert.Equal(t, r, true, "they should be equal") + r, _ = Eval(Filter("p1 | p2"), todoist.Item{Priority: 3}) + assert.Equal(t, r, false, "they should be equal") + + r, _ = Eval(Filter("p1 & p2"), todoist.Item{Priority: 1}) + assert.Equal(t, r, false, "they should be equal") + r, _ = Eval(Filter("p1 & p2"), todoist.Item{Priority: 2}) + assert.Equal(t, r, false, "they should be equal") + r, _ = Eval(Filter("p1 & p2"), todoist.Item{Priority: 3}) + assert.Equal(t, r, false, "they should be equal") }
1e5d8c8871e28166eb7b51fc38bcce6cda47978d
--- +++ @@ -7,13 +7,7 @@ ) func WithDummyCredentials(fn func(dir string)) { - if _, err := ioutil.ReadDir("temp"); err != nil { - if err := os.Mkdir("temp", 0755); err != nil { - panic(err) - } - } - - dir, err := ioutil.TempDir("temp", "dummy-credentials") + dir, err := ioutil.TempDir("", "dummy-credentials") if err != nil { panic(err)
8a36ce8d736bbd3465f7da937cb574d9f5cb5195
--- +++ @@ -2,7 +2,6 @@ import ( "encoding/json" - "fmt" "io" "log" "net/http" @@ -24,7 +23,7 @@ func handleAlivePost(rw http.ResponseWriter, request *http.Request) { aliverequest := parseAlivePost(request.Body) - fmt.Printf("DeviceID: %s, Timeout: %d", aliverequest.DeviceID, aliverequest.Timeout) + log.Printf("DeviceID: %s, Timeout: %d\n", aliverequest.DeviceID, aliverequest.Timeout) } func parseAlivePost(body io.ReadCloser) AliveRequest { @@ -41,7 +40,7 @@ } func main() { - fmt.Println("Starting AliveIM service...") + log.Println("Starting AliveIM service...") http.HandleFunc("/", handleAlivePost) http.ListenAndServe("localhost:5000", nil) }
0d36314b5179a3251459cba07315a606af06d13a
--- +++ @@ -30,8 +30,8 @@ a1 := ops.NewAttr(in, "root:10") a2 := ops.NewAttr(in, "magic:boll") a3 := ops.NewAttr(in, "status:active") - q := ops.NewIntersection(a1, a2, a3) - + q := ops.NewIntersection(a1, a2) + q.Add(a3) var d *index.IbDoc for true { d = q.NextDoc(d)
9a0cb7bfca2739ea39a12569f517c77cb99188b1
--- +++ @@ -39,7 +39,7 @@ } if err := reposTemplate.Execute(w, repos); err != nil { - log.Printf("failse to render repos/index with %d entries (%s)", len(repos), err) + log.Printf("failed to render repos/index with %d entries (%s)", len(repos), err) } else { log.Printf("rendered repos/index with %d entries [%s]", len(repos), time.Since(startTime)) }
7bc14ca50665ba407c83c9ee7552ce58efc5b411
--- +++ @@ -4,8 +4,11 @@ // MetaStore represents a metadata store. type MetaStore interface { - // AddUpdateImport adds or updates an Import. - AddUpdateImport(m *models.Import) error + // AddUpdateImport adds an Import if it doesn't exist. + AddImportIfNotExists(m *models.Import) error + + // UpdateImport updates an import. + UpdateImport(m *models.Import) error // AddVersion adds a Version to an import. AddVersion(v *models.Version) error
9e6d298502bf2888503b0146e8812c51ce62799e
--- +++ @@ -25,7 +25,7 @@ // Publish puts the thing in the redis queue func (connection *Connection) Publish(data []byte) { - redisPool.Publish(connection.redisURI, connection.redisQueueName, data) + go redisPool.Publish(connection.redisURI, connection.redisQueueName, data) } // String will be called by loggers inside Vulcand and command line tool.
95c30f519bfcbbb7af6df834b0121a2d039efc92
--- +++ @@ -22,7 +22,7 @@ if lr.Total, err = b.db.C(collection).Find(query).Count(); err != nil { return } - lr.Pages = (lr.Total / limit) + 1 + lr.Pages = (lr.Total / limit) if skip < lr.Total { if err = b.db.C(collection).Find(query).Skip(skip).Limit(limit).All(lr.List); err != nil { return
ac28e919d444f4a9caed968d4f0fab03bee49e44
--- +++ @@ -4,10 +4,13 @@ "bufio" "io" "log" + "regexp" "time" "github.com/logplex/logplexc" ) + +var prefix = regexp.MustCompile(`^(\[\d*\] [^-*#]+|.*)`) func lineWorker(die dieCh, r *bufio.Reader, cfg logplexc.Config, sr *serveRecord) { cfg.Logplex = sr.u @@ -26,8 +29,10 @@ } l, _, err := r.ReadLine() + l = prefix.ReplaceAll(l, []byte("")) if len(l) > 0 { - target.BufferMessage(134, time.Now(), "app", "redis", l) + target.BufferMessage(134, time.Now(), "redis", + sr.Name, l) } if err != nil {
a8f977f5a09e3981f918dabc78b84028a03051a3
--- +++ @@ -4,6 +4,7 @@ "log" "reflect" "testing" + "time" ) func TestParseConfig(t *testing.T) { @@ -20,7 +21,7 @@ Driver: "test_type", Host: "localhost", Port: 1234, - Timeout: 2, + Timeout: 2 * time.Second, }, }, }
bc8fc4ea9c764a79ea4e6817653100eb09b22677
--- +++ @@ -1,3 +1,4 @@ +//Simple Product controller package main import ( @@ -6,6 +7,19 @@ "net/http" "fmt" ) + +type Product struct { + Id string `json:"id"` + Name string `json:"name"` + Email string `json:"email"` +} + +var products = make([]Product, 10) + +//populate test users +func init() { + createTestUsers() +} func main() { r := mux.NewRouter() @@ -22,6 +36,7 @@ func productsHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Products") + fmt.Fprintf(w, "The product is %v", products) } func productHandler(w http.ResponseWriter, r *http.Request) { @@ -29,3 +44,9 @@ productId := vars["productId"] fmt.Fprintf(w, "You selected %s", productId) } + +func createTestUsers() { + products[0] = Product{"1", "Daniel", "daniel.bryant@test.com"} + products[1] = Product{"2", "Ashley", "ashley@test.com"} + products[2] = Product{"3", "Rusty", "rusty@test.com"} +}
98e8d99412bb14c8b70a45d35a92e77948910c55
--- +++ @@ -14,7 +14,7 @@ "appName": c.App.Name, }).Info("Running periodically") - var period time.Duration = 1 * time.Second + period := 1 * time.Second for { go func() {
337f5fe789330cbaed5593c40a2dd52a924a4179
--- +++ @@ -3,6 +3,8 @@ import( "fmt" "os" + "io/ioutil" + "path/filepath" ) const( @@ -14,6 +16,32 @@ fmt.Println("Usage: lunchy [start|stop|restart|list|status|install|show|edit] [options]") } +func findPlists(path string) []string { + result := []string{} + files, err := ioutil.ReadDir(path) + + if err != nil { + return result + } + + for _, file := range files { + if (filepath.Ext(file.Name())) == ".plist" { + result = append(result, file.Name()) + } + } + + return result +} + +func printList() { + path := fmt.Sprintf("%s/Library/LaunchAgents", os.Getenv("HOME")) + files := findPlists(path) + + for _, file := range files { + fmt.Println(file) + } +} + func main() { args := os.Args @@ -21,4 +49,6 @@ printUsage() os.Exit(1) } + + printList() }
c6a6a0cfc1752b48763d764c92b8caf74b0cf522
--- +++ @@ -15,3 +15,14 @@ } return usr.HomeDir } + +/*GetLocalhost returns the localhost name of the current computer. + *If there is an error, it returns a default string. + */ +func GetLocalhost() string { + lhost, err := os.Hostname() + if err != nil { + return "DefaultHostname" + } + return lhost +}
e48a9fb49874f322386d04b7cee4e8789154677a
--- +++ @@ -11,17 +11,21 @@ r.AddSpec(engine.DescribeClock) r.AddSpec(engine.DescribeTimeSpan) + r.AddSpec(engine.DescribeDirection) r.AddSpec(engine.DescribeWorldCoord) + r.AddSpec(engine.DescribeCollision) r.AddSpec(engine.DescribeAABB) - r.AddSpec(engine.DescribeMockEntities) + r.AddSpec(engine.DescribePathAction) r.AddSpec(engine.DescribeMoveAction) r.AddSpec(engine.DescribeMovableEntity) - r.AddSpec(engine.DescribeCollision) + r.AddSpec(engine.DescribeMockEntities) + r.AddSpec(engine.DescribeQuad) + r.AddSpec(engine.DescribeWorldState) r.AddSpec(engine.DescribeSimulation) - r.AddSpec(engine.DescribeWorldState) + r.AddSpec(engine.DescribePlayer) r.AddSpec(engine.DescribeInputCommands)
2cfc85c8b300c5a727f7caebc8530a8db4e96c43
--- +++ @@ -19,18 +19,11 @@ package dockershim import ( - "context" "fmt" runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1alpha2" ) -// ContainerStats returns stats for a container stats request based on container id. -func (ds *dockerService) ContainerStats(_ context.Context, r *runtimeapi.ContainerStatsRequest) (*runtimeapi.ContainerStatsResponse, error) { +func (ds *dockerService) getContainerStats(containerID string) (*runtimeapi.ContainerStats, error) { return nil, fmt.Errorf("not implemented") } - -// ListContainerStats returns stats for a list container stats request based on a filter. -func (ds *dockerService) ListContainerStats(_ context.Context, r *runtimeapi.ListContainerStatsRequest) (*runtimeapi.ListContainerStatsResponse, error) { - return nil, fmt.Errorf("not implemented") -}
1fde712fbc41aa9c056dc00b943b540246e61405
--- +++ @@ -13,7 +13,7 @@ func openBrowser(url string) { cmd := exec.Command("cmd", "/c", "start", url) - err = cmd.Run() + err := cmd.Run() if err != nil { fmt.Printf("%v\n", url) }
6227aa67e6f74b9af53907d7c97d4b3f3558bd41
--- +++ @@ -1,29 +1,21 @@ package statsdurl import ( + "net/url" "os" - "fmt" - "net/url" - "strings" + "github.com/quipo/statsd" ) -func Connect() (*statsd.StatsdClient, error) { +func Connect(prefix string) (*statsd.StatsdClient, error) { return ConnectToURL(os.Getenv("STATSD_URL")) } -func ConnectToURL(s string) (c *statsd.StatsdClient, err error) { +func ConnectToURL(s string, prefix string) (c *statsd.StatsdClient, err error) { statsdUrl, err := url.Parse(s) if err != nil { - return - } - - prefix := "" - - if len(statsdUrl.Path) > 1 { - prefix = strings.TrimPrefix(statsdUrl.Path, "/") - prefix = fmt.Sprintf("/%v", prefix) + return statsdUrl, err } c = statsd.NewStatsdClient(statsdUrl.Host, prefix)
5ea9c92c063fb7365eba4cb023e635057ca9d5b2
--- +++ @@ -6,3 +6,22 @@ Name string Args []token.Token } + +type List interface { + Length() int +} + +type Empty struct{} + +func (e *Empty) Length() int { + return 0 +} + +type Cons struct { + Head string + Tail List +} + +func (c *Cons) Length() int { + return 1 + c.Tail.Length() +}
325714ab560d5fbfd76b90813381cec444758552
--- +++ @@ -28,7 +28,7 @@ } func (nc *NetdConfig) AddFlags(fs *pflag.FlagSet) { - fs.BoolVar(&nc.EnablePolicyRouting, "enable-policy-routing", true, + fs.BoolVar(&nc.EnablePolicyRouting, "enable-policy-routing", false, "Enable policy routing.") fs.BoolVar(&nc.EnableMasquerade, "enable-masquerade", true, "Enable masquerade.")
252b3c6a8a49b2d9457ae9e2c335970aef2d6753
--- +++ @@ -4,16 +4,20 @@ "testing" ) -type doubleOnce struct { +// This component interface is common for many test cases +type intInAndOut struct { In <-chan int Out chan<- int } + +type doubleOnce intInAndOut func (c *doubleOnce) Process() { i := <-c.In c.Out <- 2*i } +// Test a simple component that runs only once func TestSimpleComponent(t *testing.T) { in := make(chan int) out := make(chan int) @@ -34,3 +38,39 @@ <-wait } +type doubler intInAndOut + +func (c *doubler) Process() { + for i := range c.In { + c.Out <- 2*i + } +} + +func TestSimpleLongRunningComponent(t *testing.T) { + data := map[int]int{ + 12: 24, + 7: 14, + 400: 800, + } + in := make(chan int) + out := make(chan int) + c := &doubler{ + in, + out, + } + + wait := Run(c) + + for src, expected := range data { + in <- src + actual := <- out + + if actual != expected { + t.Errorf("%d != %d", actual, expected) + } + } + + // We have to close input for the process to finish + close(in) + <-wait +}
330e205512f849e85a0e01e7c82246eb5aac5927
--- +++ @@ -22,21 +22,7 @@ Layers []Layer } -/* -func NewFFNet (filePath string) *FFNet { - f := FFNet{} - //f.Layers = make([]InputLayer, 1) // Change to interface{} - _, err := ioutil.ReadFile(filePath) - - if err != nil { - panic("failed to load" + filePath) - } - - return (&f) -} -*/ - -func FromJson (filepath string) (*FFNet, error) { +func NewFFNet (filepath string) (*FFNet, error) { b, err := ioutil.ReadFile(filepath) if err != nil {
f504ff8640d2d5e41feb43665e0168f445db88dd
--- +++ @@ -10,39 +10,10 @@ Id bson.ObjectId `json:"id" bson:"_id,omitempty"` Userid bson.ObjectId Name string - Secret string + Secret string Description string } - -/* -func (m *Application) serialize() map[string]interface{} { - return map[string]interface{}{ - "name": m.Name, - "appid": } -}*/ -/* -func init() { - c := Collection("app") - c.EnsureIndex(mgo.Index{ - Key: []string{"name"}, - Unique: true, - DropDups: true, - Background: true, // See notes. - Sparse: true, - }) - c.EnsureIndex(mgo.Index{ - Key: []string{"Userid"}, - DropDups: true, - Background: true, // See notes. - Sparse: true, - }) -}*/ - func (m *Application) Save(session *mgo.Session) error { return AppCollection(session).Insert(m) } - -func Get(fromDate, toDate time.Time) interface{} { - return nil -}
818c54a2ca38f1ec38a03467e2ea573f19fbcd20
--- +++ @@ -7,7 +7,7 @@ "golang.org/x/net/context" ) -// Ping pings the server and returns the value of the "Docker-Experimental" & "API-Version" headers +// Ping pings the server and returns the value of the "Docker-Experimental", "OS-Type" & "API-Version" headers func (cli *Client) Ping(ctx context.Context) (types.Ping, error) { var ping types.Ping req, err := cli.buildRequest("GET", fmt.Sprintf("%s/_ping", cli.basePath), nil, nil) @@ -26,5 +26,7 @@ ping.Experimental = true } + ping.OSType = serverResp.header.Get("OSType") + return ping, nil }
8ece3997df405eff6df0120a7d3d7b24bf4ec3a2
--- +++ @@ -28,7 +28,7 @@ log.Fatal(err) } - Iago.Hostname = config.StringFromSection("Iago", "Hostname", "") + Iago.Hostname = config.StringFromSection("Iago", "Hostname", "localhost") Iago.Protocol = config.StringFromSection("Iago", "Protocol", "http") Iago.Path = config.StringFromSection("Iago", "Path", "/") Iago.Port = config.IntegerFromSection("Iago", "Port", 0)
de7434595e538eaad5408277add41eef13b4a2d0
--- +++ @@ -1,4 +1,10 @@ package models + +import ( + "github.com/gojp/nihongo/app/helpers" + "regexp" + "strings" +) type Word struct { Romaji string @@ -15,3 +21,37 @@ Tags []string Pos []string } + +// Wrap the query in <strong> tags so that we can highlight it in the results +func (w *Word) HighlightQuery(query string) { + // make regular expression that matches the original query + re := regexp.MustCompile(`\b` + regexp.QuoteMeta(query) + `\b`) + // convert original query to kana + h, k := helpers.ConvertQueryToKana(query) + // wrap the query in strong tags + queryHighlighted := helpers.MakeStrong(query) + hiraganaHighlighted := helpers.MakeStrong(h) + katakanaHighlighted := helpers.MakeStrong(k) + + // if the original input is Japanese, then the original input converted + // to hiragana and katakana will be equal, so just choose one + // to highlight so that we only end up with one pair of strong tags + if hiraganaHighlighted == katakanaHighlighted { + w.JapaneseHL = strings.Replace(w.Japanese, h, hiraganaHighlighted, -1) + } else { + // The original input is romaji, so we convert it to hiragana and katakana + // and highlight both. + w.JapaneseHL = strings.Replace(w.Japanese, h, hiraganaHighlighted, -1) + w.JapaneseHL = strings.Replace(w.JapaneseHL, k, katakanaHighlighted, -1) + } + + // highlight the furigana too, same as above + w.FuriganaHL = strings.Replace(w.Furigana, h, hiraganaHighlighted, -1) + w.FuriganaHL = strings.Replace(w.FuriganaHL, k, katakanaHighlighted, -1) + // highlight the query inside the list of English definitions + w.EnglishHL = []string{} + for _, e := range w.English { + e = re.ReplaceAllString(e, queryHighlighted) + w.EnglishHL = append(w.EnglishHL, e) + } +}
0e2ca28f15f35ace2f4ee78ff7413de5c1909ab7
--- +++ @@ -6,10 +6,10 @@ s := []int{} v := sync.Pool{} - v.Put(s) // MATCH /Non-pointer type / + v.Put(s) // MATCH /non-pointer type/ v.Put(&s) p := &sync.Pool{} - p.Put(s) // MATCH /Non-pointer type / + p.Put(s) // MATCH /non-pointer type/ p.Put(&s) }
0617eaf0de27bd30c0dc1a3b78e6a1c9d2aeaa25
--- +++ @@ -1,10 +1,15 @@ package common + +// The following `enum` definitions are in line with the corresponding +// ones in InChI 1.04 software. A notable difference is that we DO +// NOT provide for specifying bond stereo with respect to the second +// atom in the pair. // Radical represents possible radical configurations of an atom. type Radical uint8 const ( - RadicalNone Radical = 0 + RadicalNone Radical = iota RadicalSinglet RadicalDoublet RadicalTriplet @@ -15,9 +20,44 @@ type BondType uint8 const ( - BondTypeNone BondType = 0 + BondTypeNone BondType = iota BondTypeSingle BondTypeDouble BondTypeTriple BondTypeAltern // InChI says 'avoid by all means'! ) + +// BondStereo defines the possible stereo orientations of a given +// bond, when 2-D coordinates are given. +type BondStereo uint8 + +const ( + BondStereoNone BondStereo = 0 + BondStereoUp BondStereo = 1 + BondStereoEither BondStereo = 4 + BondStereoDown BondStereo = 6 + BondStereoDoubleEither BondStereo = 3 +) + +// StereoType specifies the nature of the origin of the stereo +// behaviour. +type StereoType uint8 + +const ( + StereoTypeNone StereoType = iota + StereoTypeDoubleBond + StereoTypeTetrahedral + StereoTypeAllene +) + +// StereoParity defines the possible stereo configurations, given a +// particular stereo centre (atom or bond). +type StereoParity uint8 + +const ( + StereoParityNone StereoParity = iota + StereoParityOdd + StereoParityEven + StereoParityUnknown + StereoParityUndefined +)
ddeacdfa2e7a1098419650d7dc9ea9bf62ddd250
--- +++ @@ -14,7 +14,7 @@ package main -import "./cmd" +import "github.com/tereshkin/parsec-ec2/cmd" func main() { cmd.Execute()
63dfe5fa377844a5e2fca137bc9ab8d0562ddc38
--- +++ @@ -19,14 +19,14 @@ func readHosts() { f, err := os.Open(filename) if err != nil { - log.Println(err) + log.Fatal(err) } defer f.Close() scanner := bufio.NewScanner(f) for scanner.Scan() { hosts = append(hosts, host{name: scanner.Text()}) - // TODO: parse for urls, set host.protocol and host.endpoint + // TODO: parse for urls, set host.protocol and host.endpoint. net/url.Parse seems like a good fit. } if err := scanner.Err(); err != nil { log.Printf("error reading hosts from %s:%s\n", filename, err) @@ -48,4 +48,6 @@ // TODO: host method for ICMP // TODO: figure out how to represent responses. // TODO: store responses in google sheets. + // TODO: cache writes to google sheets if network is unavailable. + // TODO: rewrite host request methods as goroutines. }
d6672b6f71ee214a72c3c1a11748aa4d4f90a97b
--- +++ @@ -8,7 +8,7 @@ attr string } -func main() { +func issue1() { fmt.Println(&test{ attr: "test", })
8beca790d3797d63dccc71d645645c9aee9045b9
--- +++ @@ -13,11 +13,11 @@ ) // onMessage receives messages, logs them, and echoes a response. -func onMessage(from string, d gcm.Data) error { - toylog.Infoln("Message, from:", from, "with:", d) +func onMessage(cm gcm.CcsMessage) error { + toylog.Infoln("Message, from:", cm.From, "with:", cm.Data) // Echo the message with a tag. - d["echoed"] = true - m := gcm.HttpMessage{To: from, Data: d} + cm.Data["echoed"] = true + m := gcm.HttpMessage{To: cm.From, Data: cm.Data} r, err := gcm.SendHttp(*serverKey, m) if err != nil { toylog.Errorln("Error sending message.", err)
2276e12adf11903225eec3ee2b33c6195685eab0
--- +++ @@ -27,7 +27,7 @@ return errors.New("Describe not supported for this binary") } -func Explore(serviceName string, logger *logrus.Logger) error { +func Explore(lambdaAWSInfos []*LambdaAWSInfo, port int, logger *logrus.Logger) error { logger.Error("Explore() not supported in AWS Lambda binary") return errors.New("Explore not supported for this binary") }
0a933492b0feee22f3b5f73fa6eb432d8d217348
--- +++ @@ -8,17 +8,18 @@ "github.com/ivan1993spb/snake-server/world" ) +const chanSnakeObserverEventsBuffer = 32 + type SnakeObserver struct{} func (SnakeObserver) Observe(stop <-chan struct{}, w *world.World, logger logrus.FieldLogger) { go func() { - // TODO: Create buffer const. - for event := range w.Events(stop, 32) { + for event := range w.Events(stop, chanSnakeObserverEventsBuffer) { if event.Type == world.EventTypeObjectDelete { if s, ok := event.Payload.(*snake.Snake); ok { - // TODO: Handle error. - c, err := corpse.NewCorpse(w, s.GetLocation()) - if err == nil { + if c, err := corpse.NewCorpse(w, s.GetLocation()); err != nil { + logger.WithError(err).Error("cannot create corpse") + } else { c.Run(stop) } }
0bb38f07e118c8d6e6bb1f85ab199b3530ac6060
--- +++ @@ -40,11 +40,15 @@ } func (this *SharedWriter) Commit(lower, upper int64) { - // POTENTIAL TODO: start from upper and work toward lower - // this may have the effect of keeping a batch together which - // might otherwise be split up... - for lower <= upper { - this.committed[lower&this.mask] = int32(lower >> this.shift) - lower++ + if lower == upper { + this.committed[upper&this.mask] = int32(upper >> this.shift) + } else { + // working down the array keeps all items in the commit together + // otherwise the reader(s) could split up the group + for upper >= lower { + this.committed[upper&this.mask] = int32(upper >> this.shift) + upper-- + } + } }
fb9bfd1541e59b435738cf4f62f72d90e0f4dcb2
--- +++ @@ -13,9 +13,9 @@ // // type ExampleModule struct { // alice.BaseModule -// Foo Foo `alice:""` // associated by type -// Bar Bar `alice:"Bar"` // associated by name -// URL string // not associated. Provided by creating the module. +// Foo Foo `alice:""` // associated by type +// Bar Bar `alice:"Bar"` // associated by name +// URL string // not associated. Provided by creating the module. // } // // func (m *ExampleModule) Baz() Baz {
2f585443eac8c7ca26be923542fcf933b9e84baf
--- +++ @@ -5,6 +5,22 @@ "golang.org/x/net/context" ) + +/* + +type Foo struct { + S string +} + +sp := some.SingletonProvider{} + +foo := Foo{S:"hello"} +err1 := sp.WriteSingleton(ctx, "Foo_007", &foo) + +foo2 := Foo{} +err2 := sp.ReadSingleton(ctx, "Foo_007", &foo2) + +*/ var( ErrNoSuchEntity = errors.New("util/singleton: no such entity")
20401860635e0ab0f225f60d3bd54f1b6f945e29
--- +++ @@ -1,55 +1,16 @@ package memory import ( - "bufio" - "errors" - "fmt" - "os" - "strings" + "github.com/Symantec/Dominator/lib/meminfo" ) -var filename string = "/proc/meminfo" - func (p *prober) probe() error { - file, err := os.Open(filename) - if err != nil { + if info, err := meminfo.GetMemInfo(); err != nil { return err + } else { + p.available = info.Available + p.free = info.Free + p.total = info.Total } - defer file.Close() - scanner := bufio.NewScanner(file) - for scanner.Scan() { - if err := p.processMeminfoLine(scanner.Text()); err != nil { - return err - } - } - return scanner.Err() -} - -func (p *prober) processMeminfoLine(line string) error { - splitLine := strings.SplitN(line, ":", 2) - if len(splitLine) != 2 { - return nil - } - meminfoName := splitLine[0] - meminfoDataString := strings.TrimSpace(splitLine[1]) - var ptr *uint64 - switch meminfoName { - case "MemAvailable": - ptr = &p.available - case "MemFree": - ptr = &p.free - case "MemTotal": - ptr = &p.total - default: - return nil - } - var meminfoData uint64 - var meminfoUnit string - fmt.Sscanf(meminfoDataString, "%d %s", &meminfoData, &meminfoUnit) - if meminfoUnit != "kB" { - return errors.New(fmt.Sprintf("unknown unit: %s for: %s", - meminfoUnit, meminfoName)) - } - *ptr = meminfoData * 1024 return nil }
d1d27cccd1df27afc49874cc9408e301dc94f971
--- +++ @@ -7,13 +7,18 @@ "runtime" ) -// main starts a slow HTTP server that responds with errors. +// main starts a server. func main() { - // GOMAXPROCS call is ignored if NumCPU returns 1 (GOMAXPROCS(0) doesn't change anything) - runtime.GOMAXPROCS(runtime.NumCPU() / 2) + useSeveralCPU() config := NewConfigFromArgs() server := NewServer(config) log.Fatal(server.ListenAndServe()) } + +func useSeveralCPU() { + if runtime.NumCPU() > 1 { + runtime.GOMAXPROCS(runtime.NumCPU() / 2) + } +}
ee2d48c1aa78d1ef9aa227d03629298cf4e87e44
--- +++ @@ -11,9 +11,26 @@ } func (c *CreateReq) Validate() error { - if len(c.Actions) == 0 { + err := validateActions(c.Actions) + if err != nil { + return err + } + err = validateTriggers(c.Triggers) + if err != nil { + return err + } + return nil +} + +func validateActions(actions []Action) error { + if len(actions) == 0 { return fmt.Errorf("Actions: non-zero value required.") - } else if len(c.Triggers) == 0 { + } + return nil +} + +func validateTriggers(triggers []Trigger) error { + if len(triggers) == 0 { return fmt.Errorf("Triggers: non-zero value required.") } return nil
6c4726e879b3e8662632615c24cf1ca9bf906d6d
--- +++ @@ -3,10 +3,69 @@ import ( "reflect" "testing" + "time" + "github.com/hoop33/limo/model" "github.com/stretchr/testify/assert" ) + +var text Text func TestTextDoesRegisterItself(t *testing.T) { assert.Equal(t, "*output.Text", reflect.TypeOf(ForName("text")).String()) } + +func ExampleText_Info() { + text.Info("This is info") + // Output: This is info +} + +func ExampleText_Tick() { + text.Tick() + // Output: . +} + +func ExampleText_StarLine() { + fullName := "hoop33/limo" + language := "Go" + star := &model.Star{ + FullName: &fullName, + Stargazers: 1000000, + Language: &language, + } + text.StarLine(star) + // Output: hoop33/limo (*: 1000000) (Go) +} + +func ExampleText_Star() { + fullName := "hoop33/limo" + language := "Go" + description := "A CLI for managing starred Git repositories" + homepage := "https://github.com/hoop33/limo" + url := "https://github.com/hoop33/limo.git" + star := &model.Star{ + FullName: &fullName, + Stargazers: 1000000, + Language: &language, + Description: &description, + Homepage: &homepage, + URL: &url, + StarredAt: time.Date(2016, time.June, 21, 14, 56, 5, 0, time.UTC), + Tags: []model.Tag{ + { + Name: "cli", + }, + { + Name: "git", + }, + }, + } + text.Star(star) + // Output: + // hoop33/limo (*: 1000000) (Go) + // cli, git + // A CLI for managing starred Git repositories + // Home page: https://github.com/hoop33/limo + // URL: https://github.com/hoop33/limo.git + // Starred at Tue Jun 21 14:56:05 UTC 2016 +}
444d3b0904aca36fd000db277829d3a5cc8e618f
--- +++ @@ -1,8 +1,26 @@ package main import ( + "fmt" + "os" + "path/filepath" "testing" + + "github.com/mitchellh/go-homedir" ) + +var ( + home, errInit = homedir.Dir() + dotvim = filepath.Join(home, ".vim") +) + +func TestMain(m *testing.M) { + if errInit != nil { + fmt.Fprintln(os.Stderr, "vub:", errInit) + os.Exit(1) + } + os.Exit(m.Run()) +} var sourceURITests = []struct { src string
b18307394e8b3b2c96d409a5abd74fd2456baf4f
--- +++ @@ -1,9 +1,6 @@ package adapters import "regexp" - -// TODO: handle installing js assets? -// [error] Could not start node watcher because script "/Users/richard/workspace/moocode/hoot/apps/web/assets/node_modules/brunch/bin/brunch" does not exist. Your Phoenix application is still running, however assets won't be compiled. You may fix this by running "cd assets && npm install" const phoenixShellCommand = `exec bash -c ' cd %s @@ -15,13 +12,13 @@ // TODO: look at the mix.exs file and determine which version of phoenix // we're starting and use the correct start command - restart, nil := regexp.Compile("You must restart your server") + mixFileChanged, nil := regexp.Compile("You must restart your server") return &AppProxyAdapter{ Host: host, Dir: dir, ShellCommand: phoenixShellCommand, - RestartPatterns: []*regexp.Regexp{restart}, + RestartPatterns: []*regexp.Regexp{mixFileChanged}, EnvPortName: "PHX_PORT", readyChan: make(chan struct{}), }, nil
c7039772a09f1b10bd64950446e5c56c45508694
--- +++ @@ -1,9 +1,10 @@ package health import ( - "log" "net/http" "os" + + log "github.com/F5Networks/k8s-bigip-ctlr/pkg/vlogger" ) type HealthChecker struct { @@ -22,7 +23,8 @@ w.Write([]byte("Ok")) return } - log.Println(err) + + log.Errorf(err.Error()) } w.WriteHeader(http.StatusInternalServerError)
356ce08f4fdb669e7e942abf81a62f0ee87deda2
--- +++ @@ -19,7 +19,7 @@ } func (controller *PostCreateController) Handle(conn net.Conn, request *gopher.Request, params map[string]string) { - post := Post{Body:params["body"]} + post := Post{Body:request.Body} post.Save() response := BuildResponse(
8e011d250ef58cec6432025a823a86f722c8542a
--- +++ @@ -11,7 +11,8 @@ "github.com/stretchr/testify/assert" ) -func TestMemoryAllocationAttack(t *testing.T) { +// TODO: Research how to integrate this test correctly so if doesn't fail the 50% of the times. +func _TestMemoryAllocationAttack(t *testing.T) { assert := assert.New(t) var size uint64 = 200 * MiB
b9068c56bd52f75b1c68a6b141a50b6da291013c
--- +++ @@ -7,11 +7,12 @@ "github.com/goadesign/goa/eval" ) -const ( - description = "test description" -) -func TestDescription(t *testing.T) { +func TestDescription(t *testing.T) { + const ( + description = "test description" + ) + cases := map[string]struct { Expr eval.Expression Desc string
6ac9735e4a5b47830bdb2cdaf30bc0c20437157b
--- +++ @@ -1,8 +1,38 @@ package dmm -// Base may not be needed, but the idea is that there are some functions that -// could be abstracted out to the general DMM. -type Base interface { - DCVolts() (v float64, err error) - ACVolts() (v float64, err error) +// MeasurementFunction provides the defined values for the Measurement Function defined in +// Section 4.2.1 of IVI-4.2: IviDmm Class Specification. +type MeasurementFunction int + +// The MeasurementFunction defined values are the available measurement functions. +const ( + DCVolts MeasurementFunction = iota + ACVolts + DCCurrent + ACCurrent + TwoWireResistance + FourWireResistance + ACPlusDCVolts + ACPlusDCCurrent + Frequency + Period + Temperature +) + +var measurementFunctions = map[MeasurementFunction]string{ + DCVolts: "DC Volts", + ACVolts: "AC Volts", + DCCurrent: "DC Current", + ACCurrent: "AC Current", + TwoWireResistance: "2-wire Resistance", + FourWireResistance: "4-wire Resistance", + ACPlusDCVolts: "AC Plus DC Volts", + ACPlusDCCurrent: "AC Plus DC Current", + Frequency: "Frequency", + Period: "Period", + Temperature: "Temperature", } + +func (f MeasurementFunction) String() string { + return measurementFunctions[f] +}
db25a136ea869458dba25f36cf2c650114a5170b
--- +++ @@ -34,14 +34,9 @@ sig := make(chan os.Signal) signal.Notify(sig, os.Interrupt) - forever: - for { - select { - case <-sig: - log.Printf("geodns: signal received, stopping") - break forever - } - } + <-sig + log.Printf("geodns: signal received, stopping") + os.Exit(0) } }
d05bfb08733e4d0a95fc576aa695c74a0af12e83
--- +++ @@ -1,3 +1,29 @@ +/* +Package types implements support for the types used in the Navitia API (see doc.navitia.io), simplified and modified for idiomatic Go use. + +This package was and is developped as a supporting library for the gonavitia API client (https://github.com/aabizri/gonavitia) but can be used to build other API clients. + +This support includes or will include, for each type. + - JSON Unmarshalling via UnmarshalJSON(b []byte), in the format of the navitia.io API + - Validity Checking via Check() + - Pretty-printing via String() + +This package is still a work in progress. It is not API-Stable, and won't be until the v1 release. + +Currently supported types + - Journey ["journey"] + - Section ["section"] + - Region ["region"] + - Place (This is an interface for your ease-of-use, which is implemented by the five following types) + - Address ["address"] + - StopPoint ["stop_point"] + - StopArea ["stop_area"] + - AdministrativeRegion ["administrative_region"] + - POI ["poi"] + - Line ["line"] + - Route ["route"] + - And others, such as DisplayInformations ["display_informations"], PTDateTime ["pt-date-time"], StopTime ["stop_time"], Coordinates ["coord"]. +*/ package types // DataFreshness codes for a specific data freshness requirement: realtime or base_schedule
15f52f3dcb328650c7357f654ae6d5391ca9362f
--- +++ @@ -1,6 +1,10 @@ package b2 -import () +import ( + "encoding/json" + "io/ioutil" + "net/http" +) type B2 struct { AccountID string @@ -10,6 +14,46 @@ DownloadUrl string } +type authResponse struct { + AccountID string `json:"accountId"` + AuthorizationToken string `json:"authorizationToken"` + ApiUrl string `json:"apiUrl"` + DownloadUrl string `json:"downloadUrl"` +} + func MakeB2(accountId, appKey string) (*B2, error) { - return &B2{}, nil + req, err := http.NewRequest("GET", + "https://api.backblaze.com/b2api/v1/b2_authorize_account", nil) + if err != nil { + return &B2{}, err + } + + req.SetBasicAuth(accountId, appKey) + + c := http.Client{} + resp, err := c.Do(req) + if err != nil { + return &B2{}, err + } + defer resp.Body.Close() + + // TODO handle response errors + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return &B2{}, err + } + + authJson := authResponse{} + if err := json.Unmarshal(body, authJson); err != nil { + return &B2{}, err + } + + return &B2{ + AccountID: authJson.AccountID, + ApplicationKey: appKey, + AuthorizationToken: authJson.AuthorizationToken, + ApiUrl: authJson.ApiUrl, + DownloadUrl: authJson.DownloadUrl, + }, nil }
57c13b6cee64250e4b101f91d357f5b5b9ad3ce5
--- +++ @@ -12,7 +12,7 @@ ) // Version is the GopherJS compiler version string. -const Version = "1.16.1+go1.16.3" +const Version = "1.16.2+go1.16.4" // GoVersion is the current Go 1.x version that GopherJS is compatible with. const GoVersion = 16
ad8616bf2c88d174c110a14caa62d586c0222f9f
--- +++ @@ -10,7 +10,7 @@ type Orchestrator interface { GetHandler() *handler.Conplicity GetVolumes() ([]*volume.Volume, error) - LaunchContainer(image string, env map[string]string, cmd []string, v []*volume.Volume) (state int, stdout string, err error) + LaunchContainer(image string, env map[string]string, cmd []string, volumes []*volume.Volume) (state int, stdout string, err error) GetMountedVolumes() ([]*volume.MountedVolumes, error) ContainerExec(containerID string, command []string) error }
818de6e7da67a15639653699d03281b9471715aa
--- +++ @@ -10,9 +10,9 @@ // header.Length bytes. func VerifyPadding(r io.Reader) (err error) { // Verify up to 4 kb of padding each iteration. - buf := make([]byte, 4096) + var buf [4096]byte for { - n, err := r.Read(buf) + n, err := r.Read(buf[:]) if err != nil { if err == io.EOF { break @@ -26,10 +26,6 @@ return nil } -/// ### [ note ] ### -/// - Might trigger unnecessary errors. -/// ### [/ note ] ### - // isAllZero returns true if the value of each byte in the provided slice is 0, // and false otherwise. func isAllZero(buf []byte) bool {
b90e4837fbb0c1c1be17a712e3390beef9015057
--- +++ @@ -4,10 +4,30 @@ package markdown -import "strings" - -func isTerminatorChar(ch byte) bool { - return strings.IndexByte("\n!#$%&*+-:<=>@[\\]^_`{}~", ch) != -1 +var terminatorCharTable = [256]bool{ + '\n': true, + '!': true, + '#': true, + '$': true, + '%': true, + '&': true, + '*': true, + '+': true, + '-': true, + ':': true, + '<': true, + '=': true, + '>': true, + '@': true, + '[': true, + '\\': true, + ']': true, + '^': true, + '_': true, + '`': true, + '{': true, + '}': true, + '~': true, } func ruleText(s *StateInline, silent bool) bool { @@ -15,7 +35,7 @@ max := s.PosMax src := s.Src - for pos < max && !isTerminatorChar(src[pos]) { + for pos < max && !terminatorCharTable[src[pos]] { pos++ } if pos == s.Pos {
a9d7dee03864dcea888e4ed0700af40a8d45d1ce
--- +++ @@ -9,10 +9,10 @@ ) type ClientLocketConfig struct { - LocketAddress string `json:"locket_address,omitempty"` - LocketCACertFile string `json:"locket_ca_cert_file,omitempty"` - LocketClientCertFile string `json:"locket_client_cert_file,omitempty"` - LocketClientKeyFile string `json:"locket_client_key_file,omitempty"` + LocketAddress string `json:"locket_address,omitempty" yaml:"locket_address,omitempty"` + LocketCACertFile string `json:"locket_ca_cert_file,omitempty" yaml:"locket_ca_cert_file,omitempty"` + LocketClientCertFile string `json:"locket_ca_cert_file,omitempty" yaml:"locket_client_cert_file,omitempty"` + LocketClientKeyFile string `json:"locket_client_key_file,omitempty" yaml:"locket_client_key_file,omitempty"` } func NewClient(logger lager.Logger, config ClientLocketConfig) (models.LocketClient, error) {
8bfd3a54a4142c397cab69bfa9699e5b5db9b40b
--- +++ @@ -23,7 +23,9 @@ func TestEncodePage(t *testing.T) { t.Parallel() - templ := `{{ index .Site.RegularPages 0 | jsonify }}` + templ := `Page: |{{ index .Site.RegularPages 0 | jsonify }}| +Site: {{ site | jsonify }} +` b := newTestSitesBuilder(t) b.WithSimpleConfigFile().WithTemplatesAdded("index.html", templ)
6c722ebf604bf266d42cf2ba2227ef6812ddac7f
--- +++ @@ -5,6 +5,7 @@ . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "path/filepath" + "path" ) var _ = Describe("AppFiles", func() { @@ -31,8 +32,8 @@ } Expect(paths).To(Equal([]string{ - filepath.Join("dir1", "child-dir", "file3.txt"), - filepath.Join("dir1", "file1.txt"), + path.Join("dir1", "child-dir", "file3.txt"), + path.Join("dir1", "file1.txt"), })) }) })
dfc421824ce6c146ff9d9062ad25748c0f8c9990
--- +++ @@ -1,50 +1,33 @@ package torrent -import ( - rbm "github.com/RoaringBitmap/roaring" - roaring "github.com/RoaringBitmap/roaring/BitSliceIndexing" -) - type pendingRequests struct { - m *roaring.BSI + m []int } func (p *pendingRequests) Dec(r RequestIndex) { - _r := uint64(r) - prev, _ := p.m.GetValue(_r) + prev := p.m[r] if prev <= 0 { panic(prev) } - p.m.SetValue(_r, prev-1) + p.m[r]-- } func (p *pendingRequests) Inc(r RequestIndex) { - _r := uint64(r) - prev, _ := p.m.GetValue(_r) - p.m.SetValue(_r, prev+1) + p.m[r]++ } func (p *pendingRequests) Init(maxIndex RequestIndex) { - p.m = roaring.NewDefaultBSI() -} - -var allBits rbm.Bitmap - -func init() { - allBits.AddRange(0, rbm.MaxRange) + p.m = make([]int, maxIndex) } func (p *pendingRequests) AssertEmpty() { - if p.m == nil { - panic(p.m) - } - sum, _ := p.m.Sum(&allBits) - if sum != 0 { - panic(sum) + for _, count := range p.m { + if count != 0 { + panic(count) + } } } func (p *pendingRequests) Get(r RequestIndex) int { - count, _ := p.m.GetValue(uint64(r)) - return int(count) + return p.m[r] }
5209babfa1cec876c5798c6a4d6b396d7a4c4615
--- +++ @@ -5,8 +5,8 @@ type Clue []int const ( - White Square = iota - Black + White Square = false + Black Square = true ) type Grid struct {
867d25f21f55fa6400e68e2bf82f98159fbc97f6
--- +++ @@ -22,10 +22,11 @@ } func (builder *ObjectWriteChannelBuilder) GetChannel(offset int64) (io.WriteCloser, error) { - f, err := os.OpenFile(builder.name, os.O_WRONLY, defaultPermissions) + f, err := os.OpenFile(builder.name, os.O_WRONLY | os.O_CREATE, os.ModePerm) if err != nil { return nil, err } + f.Seek(offset, io.SeekStart) return f, nil }
871f9265c92d361e33efef58bb075ccb0189225a
--- +++ @@ -12,7 +12,7 @@ "github.com/instana/testify/assert" ) -func TestTimer_Stop(t *testing.T) { +func TestTimer_Stop_Restart(t *testing.T) { var fired int64 timer := internal.NewTimer(0, 60*time.Millisecond, func() { atomic.AddInt64(&fired, 1) @@ -24,7 +24,7 @@ assert.EqualValues(t, 1, atomic.LoadInt64(&fired)) time.Sleep(200 * time.Millisecond) - assert.EqualValues(t, 1, atomic.LoadInt64(&fired)) + assert.EqualValues(t, 1, atomic.LoadInt64(&fired), "a stopped timer should not be restarted") } func TestTimer_Sleep_Stopped(t *testing.T) {
241c0115a1d1a7414bbe22408635276581270787
--- +++ @@ -1,6 +1,12 @@ +// Run these tests with -race package main -import "testing" +import ( + "math/rand" + "sync" + "testing" + "time" +) type testVisitor struct { start int @@ -26,3 +32,41 @@ t.Errorf("end got %v, want %v", v.end, 5) } } + +type testVisitorDelay struct { + start int + end int +} + +func (v *testVisitorDelay) Start(i int) { + time.Sleep(time.Duration(1+rand.Intn(5)) * time.Millisecond) + v.start = i +} + +func (v *testVisitorDelay) End(a, b int) { + time.Sleep(time.Duration(1+rand.Intn(5)) * time.Millisecond) + v.end = a + b +} + +func TestConcurrent(t *testing.T) { + var wg sync.WaitGroup + + worker := func(i int) { + var v testVisitorDelay + GoTraverse("foo", &v) + if v.start != 100 { + t.Errorf("start got %v, want %v", v.start, 100) + } + if v.end != 5 { + t.Errorf("end got %v, want %v", v.end, 5) + } + wg.Done() + } + + for i := 0; i < 200; i++ { + wg.Add(1) + go worker(i) + } + + wg.Wait() +}
e219224a98297212369e5576f5b203f498a8ea13
--- +++ @@ -7,30 +7,45 @@ "os" ) -func Smudge(writer io.Writer, sha string) error { // stdout, sha +func Smudge(writer io.Writer, sha string) error { mediafile := gitmedia.LocalMediaPath(sha) - reader, err := gitmediaclient.Get(mediafile) - if err != nil { - return &SmudgeError{sha, mediafile, err.Error()} - } - defer reader.Close() + if stat, err := os.Stat(mediafile); err != nil || stat == nil { + reader, err := gitmediaclient.Get(mediafile) + if err != nil { + return &SmudgeError{sha, mediafile, err.Error()} + } + defer reader.Close() - mediaWriter, err := os.Create(mediafile) - defer mediaWriter.Close() + mediaWriter, err := os.Create(mediafile) + if err != nil { + return &SmudgeError{sha, mediafile, err.Error()} + } + defer mediaWriter.Close() - if err != nil { - return &SmudgeError{sha, mediafile, err.Error()} - } + if err := copyFile(reader, writer, mediaWriter); err != nil { + return &SmudgeError{sha, mediafile, err.Error()} + } + } else { + reader, err := os.Open(mediafile) + if err != nil { + return &SmudgeError{sha, mediafile, err.Error()} + } + defer reader.Close() - multiWriter := io.MultiWriter(writer, mediaWriter) - - _, err = io.Copy(multiWriter, reader) - if err != nil { - return &SmudgeError{sha, mediafile, err.Error()} + if err := copyFile(reader, writer); err != nil { + return &SmudgeError{sha, mediafile, err.Error()} + } } return nil +} + +func copyFile(reader io.ReadCloser, writers ...io.Writer) error { + multiWriter := io.MultiWriter(writers...) + + _, err := io.Copy(multiWriter, reader) + return err } type SmudgeError struct {
7c14876990f9fa0b204a25aa1333613e75296611
--- +++ @@ -4,13 +4,39 @@ "fmt" "log" "net/http" + "sync" ) +var mu sync.Mutex +var count int + func main() { + log.Print("Server running...") http.HandleFunc("/", handler) + http.HandleFunc("/count", counter) log.Fatal(http.ListenAndServe("localhost:8000", nil)) } func handler(w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path) + mu.Lock() + count++ + mu.Unlock() + fmt.Fprintf(w, "%s %s %s\n", r.Method, r.URL, r.Proto) + for k, v := range r.Header { + fmt.Fprintf(w, "Header[%q]: %q\n", k, v) + } + fmt.Fprintf(w, "Host: %q\n", r.Host) + fmt.Fprintf(w, "RemoteAddr: %q\n", r.RemoteAddr) + if err := r.ParseForm(); err != nil { + log.Print(err) + } + for k, v := range r.Form { + fmt.Fprintf(w, "Form[%q]: %q\n", k, v) + } } + +func counter(w http.ResponseWriter, r *http.Request) { + mu.Lock() + fmt.Fprintf(w, "Count: %d\n", count) + mu.Unlock() +}
5055dad156db126036f5456bdb5800fca2782403
--- +++ @@ -3,7 +3,7 @@ import ( "errors" - "strings" + "path/filepath" ) // getContentType returns the http header safe content-type attribute for the @@ -13,13 +13,11 @@ // BUG(george-e-shaw-iv) Does not cover the bulk of encountered content types on the web func GetContentType(path string) (string, error) { var contentType string - splitPath := strings.Split(path, ".") + fileType := filepath.Ext(path) - if len(splitPath) == 1 && splitPath[0] == path { + if fileType == "" { return contentType, errors.New("Invalid path, contained no period-separated content-type") } - - fileType := splitPath[len(splitPath)-1] switch fileType { case "html":
cc30bf92c079553cbf9fefea70820d5e4f8aa5ee
--- +++ @@ -10,10 +10,10 @@ return reflect.DeepEqual(node, other) } -func (node AscendingNode) Direction() string { +func (node *AscendingNode) Direction() string { return "ASC" } -func (node AscendingNode) Reverse() *DescendingNode { +func (node *AscendingNode) Reverse() *DescendingNode { return &DescendingNode{Expr: node.Expr} }
dafdbc0508f7052c5c32e92413a88289597d39f5
--- +++ @@ -1,7 +1,12 @@ package main import ( + "bytes" + "fmt" + "io" + "log" "os" + "os/exec" "time" tm "github.com/buger/goterm" @@ -9,15 +14,60 @@ func main() { command := os.Args[1:] + tm.Clear() + tm.MoveCursor(0,0) + loop(1*time.Second, func() { - render(command) + + output, err := run(command) + safe(err) + + render(output) + }) } -func render(command []string) { - tm.MoveCursor(0,0) - tm.Println(command) +func run(command []string) (bytes.Buffer, error) { + name := command[0] + args := command[1:] + cmd := exec.Command(name, args...) + + cmdPipe, err := cmd.StdoutPipe() + if err != nil { + return bytes.Buffer{}, err; + } + + if err := cmd.Start(); err != nil { + return bytes.Buffer{}, err; + } + + pipeReader, pipeWriter := io.Pipe() + + go func() { + _, err := io.Copy(pipeWriter, cmdPipe) + // fixme: return error through a channel + safe(err) + pipeWriter.Close() + } () + + var buf bytes.Buffer + _, err2 := io.Copy(&buf, pipeReader) + safe(err2) + + return buf, nil +} + +func l (s string) { fmt.Println(s) } + +func safe(err error) { + if err != nil { + log.Fatal(err) + } +} + +func render(output bytes.Buffer) { + tm.Println(output.String()) tm.Flush() }
cffa5b6b50d25a48b20754af5fc9a5154d516c5e
--- +++ @@ -2,13 +2,18 @@ package dns import ( + "context" "net" "github.com/micro/go-micro/network/resolver" + "github.com/miekg/dns" ) // Resolver is a DNS network resolve -type Resolver struct{} +type Resolver struct { + // The resolver address to use + Address string +} // Resolve assumes ID is a domain name e.g micro.mu func (r *Resolver) Resolve(name string) ([]*resolver.Record, error) { @@ -22,14 +27,29 @@ host = "localhost" } - addrs, err := net.LookupHost(host) + if len(r.Address) == 0 { + r.Address = "1.0.0.1:53" + } + + m := new(dns.Msg) + m.SetQuestion(dns.Fqdn(host), dns.TypeA) + rec, err := dns.ExchangeContext(context.Background(), m, r.Address) if err != nil { return nil, err } - records := make([]*resolver.Record, 0, len(addrs)) + var records []*resolver.Record - for _, addr := range addrs { + for _, answer := range rec.Answer { + h := answer.Header() + // check record type matches + if h.Rrtype != dns.TypeA { + continue + } + + arec, _ := answer.(*dns.A) + addr := arec.A.String() + // join resolved record with port address := net.JoinHostPort(addr, port) // append to record set
6a551765b2f511639e525e8ac40ae9069b843157
--- +++ @@ -12,8 +12,8 @@ ) var ( - source = flag.String("source", "", "Source") - destination = flag.String("destination", "", "Destination") + source = flag.String("in", "", "Source") + destination = flag.String("out", "", "Destination") ) func main() {
519db61795ec27a909dd67809e36d63b980ecc83
--- +++ @@ -19,3 +19,12 @@ } return strings.Join(result, ",") } + +//FormatSwarmNetworks returns the string representation of the given slice of NetworkAttachmentConfig +func FormatSwarmNetworks(networks []swarm.NetworkAttachmentConfig) string { + result := []string{} + for _, network := range networks { + result = append(result, network.Target) + } + return strings.Join(result, ",") +}
c9f22a6baed84ae48fc91a326f4a0fc4b4a1b596
--- +++ @@ -10,6 +10,21 @@ EventTypeObjectChecked ) +var eventsLabels = map[EventType]string{ + EventTypeError: "error", + EventTypeObjectCreate: "create", + EventTypeObjectDelete: "delete", + EventTypeObjectUpdate: "update", + EventTypeObjectChecked: "checked", +} + +func (event EventType) String() string { + if label, ok := eventsLabels[event]; ok { + return label + } + return "unknown" +} + type Event struct { Type EventType Payload interface{}
7598c409732afa6d8b1c6e20527cb475c216a20d
--- +++ @@ -1,7 +1,15 @@ package main -import "testing" +import ( + "strings" + "testing" +) -func TestFoo(t *testing.T) { - +func TestMarkDownLinkWithDeprecatedNote(t *testing.T) { + s := "* [go-lang-idea-plugin](https://github.com/go-lang-plugin-org/go-lang-idea-plugin) (deprecated) - The previous Go plugin for IntelliJ (JetBrains) IDEA, now replaced by the official plugin (above)." + parts := strings.Split(s, " - ") + pkg := getNameAndDesc(parts[0], parts[1]) + if pkg.pkg != "github.com/go-lang-plugin-org/go-lang-idea-plugin" { + t.Errorf("parser failed to parse %s. Got: %s", s, pkg.pkg) + } }
b2f43945768d7ef24b8cad9666f0a06f0141e8f7
--- +++ @@ -23,5 +23,11 @@ t.Errorf("Expected value at foo to be bar, go %v", value) } + kv.Delete([]byte("foo")) + value = kv.Get([]byte("foo")) + if string(value) != "" { + t.Errorf("Expected value at foo to be empty, got %v", value) + } + os.Remove("test.db") }