_id
stringlengths
40
40
text
stringlengths
81
2.19k
title
stringclasses
1 value
4660d7d17f163b506ad8d8a410efe7fdc7ed06b6
--- +++ @@ -48,7 +48,7 @@ func toPort(p string) int { ps, err := strconv.Atoi(p) if err != nil { - log.Printf("[ERROR] Invalid port number: %d", p) + log.Printf("[ERROR] Invalid port number: %s", p) } return ps
809e04f2d16c4bac5b7d38f13537d3debfe0d914
--- +++ @@ -5,7 +5,7 @@ "github.com/mcroydon/goplayground/similarity" ) -func ExampleUse() { +func Example() { // Create a similarity engine sim := similarity.New()
1e106de4ea1789a593dfc207470e844f7b911e0a
--- +++ @@ -16,13 +16,13 @@ Body []byte } -func (uk UnknownFrame) Size() int { - return len(uk.Body) +func (uf UnknownFrame) Size() int { + return len(uf.Body) } -func (uk UnknownFrame) WriteTo(w io.Writer) (n int64, err error) { +func (uf UnknownFrame) WriteTo(w io.Writer) (n int64, err error) { var i int - i, err = w.Write(uk.Body) + i, err = w.Write(uf.Body) return int64(i), err }
ee0bb560054d6a1f103a1600838cf8e18c28bd88
--- +++ @@ -4,6 +4,7 @@ "fmt" "github.com/anaminus/rbxmk" + "github.com/robloxapi/types" ) // registry contains registered Formats. @@ -21,5 +22,8 @@ // cannotEncode returns an error indicating that v cannot be encoded. func cannotEncode(v interface{}) error { + if v, ok := v.(types.Value); ok { + return fmt.Errorf("cannot encode %s", v.Type()) + } return fmt.Errorf("cannot encode %T", v) }
d904cf0beee88aeb9a4094ec119de958621b1856
--- +++ @@ -24,7 +24,7 @@ var Resource = &core.Resource{ Name: "bridge", ServiceType: reflect.TypeOf(&bridge.Service{}), - Category: core.ResourceCategoryStorage, + Category: core.ResourceCategoryNetworking, CommandCategories: []core.Category{ { Key: "basic",
b7f2285ba304b0473025902fd6508a175cf51420
--- +++ @@ -22,7 +22,7 @@ return manager } -func (manager emailManager) send(to string, subject string, content string) { +func (manager emailManager) Send(to string, subject string, content string) { auth := smtp.PlainAuth("", manager.Login, manager.Password, manager.Host) recipients := []string{to}
0e93f1795a8a479ce4ac381d103727b55f68b1e4
--- +++ @@ -3,6 +3,7 @@ import ( "flag" "github.com/zenazn/goji" + "github.com/zenazn/goji/web" "github.com/zenazn/goji/web/middleware" "net/http" ) @@ -18,6 +19,8 @@ if conf.Proxy { goji.Insert(middleware.RealIP, middleware.Logger) } + + goji.Use(serveLapitar) register("/skin/:player", serveSkin) @@ -36,3 +39,11 @@ goji.Get(pattern+".png", handler) goji.Get(pattern, handler) } + +func serveLapitar(c *web.C, h http.Handler) http.Handler { + fn := func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Server", "Lapitar") // TODO: Version + h.ServeHTTP(w, r) + } + return http.HandlerFunc(fn) +}
04b72b4a7ddd37d4615f4fcc125211ee93518780
--- +++ @@ -15,15 +15,11 @@ func (t TemplateGenerator) Generate(state storage.State) string { return fmt.Sprintf(` variable "vsphere_subnet" {} -variable "jumpbox_ip" { - default = "" -} +variable "jumpbox_ip" {} variable "internal_gw" {} variable "network_name" {} variable "vcenter_cluster" {} -variable "bosh_director_internal_ip" { - default = "" -} +variable "bosh_director_internal_ip" {} output "internal_cidr" { value = "${var.vsphere_subnet}" } output "internal_gw" { value = "${var.internal_gw}" }
3125d02cf6b842700239ca67ef5b7f96951d28b7
--- +++ @@ -3,6 +3,7 @@ import ( "fmt" "net" + "strings" ) const ( @@ -27,18 +28,8 @@ // Build list of "host:port" strings. for _, a := range addrs { - target := parseTargetDomainName(a.Target) + target := strings.TrimRight(a.Target, ".") addr = append(addr, fmt.Sprintf("%s:%d", target, a.Port)) } return } - -// Remove the last dot in the domain name if exist -func parseTargetDomainName(domainName string) (ret string) { - if domainName[len(domainName)-1] == '.' { - ret = parseTargetDomainName(domainName[:len(domainName)-1]) - } else { - ret = domainName - } - return -}
84494e3ce36f35807ca004f44b0c8936f78ed835
--- +++ @@ -1,6 +1,8 @@ package wats import ( + "time" + . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gexec" @@ -25,7 +27,8 @@ It("doesn't die when printing 32MB", func() { beforeId := helpers.CurlApp(appName, "/id") - Expect(helpers.CurlAppWithTimeout(appName, "/logspew/32000", DEFAULT_TIMEOUT)). + loggingTimeout := 2 * time.Minute + Expect(helpers.CurlAppWithTimeout(appName, "/logspew/32000", loggingTimeout)). To(ContainSubstring("Just wrote 32000 kbytes to the log")) Consistently(func() string {
0f81fc87f193ce12bf44bdbef149514ced6ad36e
--- +++ @@ -5,6 +5,7 @@ "os" ) +// ParseUsername returns an array of user strings or an error if no arguments provided func ParseUsername() ([]string, error) { args := os.Args @@ -12,7 +13,5 @@ log.Fatal("Please supply at least one GitHub username") } - // username := args[0] - // return username, nil return args, nil }
927939dfc6d6612f488da7a189b4f2299e99eea7
--- +++ @@ -4,7 +4,7 @@ "net/url" ) -var GitTreesURL = Hyperlink("repos/{owner}/{repo}/git/trees/{/sha}{?recursive}") +var GitTreesURL = Hyperlink("repos/{owner}/{repo}/git/trees/{sha}{?recursive}") func (c *Client) GitTrees(url *url.URL) (trees *GitTreesService) { trees = &GitTreesService{client: c, URL: url}
4a0e50ddd5da0ad298b0807f3ea0cb5adc4693b5
--- +++ @@ -29,5 +29,19 @@ Eventually(session).Should(Say("OK")) Eventually(session).Should(Exit(0)) }) + + When("the user already has the desired role", func() { + BeforeEach(func() { + session := helpers.CF("set-org-role", username, orgName, "OrgManager") + Eventually(session).Should(Say("Assigning role OrgManager to user %s in org %s as admin...", username, orgName)) + Eventually(session).Should(Exit(0)) + }) + + It("is idempotent", func() { + session := helpers.CF("set-org-role", username, orgName, "OrgManager") + Eventually(session).Should(Say("Assigning role OrgManager to user %s in org %s as admin...", username, orgName)) + Eventually(session).Should(Exit(0)) + }) + }) }) })
84776c4e432013fb267fb5084740be416116e699
--- +++ @@ -1,7 +1,6 @@ package restic import ( - "log" "net" "os" ) @@ -34,7 +33,6 @@ // Close closes both streams. func (s *StdioConn) Close() error { - log.Printf("Server.Close()\n") err1 := s.stdin.Close() err2 := s.stdout.Close() if err1 != nil {
a13ef780694f22260e1b0bb5ef80b7aff4eb0b24
--- +++ @@ -14,7 +14,7 @@ var v1 int = i; if foo1(v1) != 1 { panicln(1) } var v2 int32 = i.(int).(int32); - if foo1(v2) != 1 { panicln(2) } + if foo2(v2) != 1 { panicln(2) } var v3 int32 = i; // This implicit type conversion should fail at runtime. - if foo1(v3) != 1 { panicln(3) } + if foo2(v3) != 1 { panicln(3) } }
51870c87146b68ef2184494b0617118468871481
--- +++ @@ -3,7 +3,46 @@ import ( "os" "fmt" + "io/ioutil" + "log" + "encoding/json" + "flag" ) + +type RepositorySettings struct { + LandingPage string // TODO unmarshal into enum like type + Private bool + MainBranch string + Forks string // TODO: Unmarshal 'forks' into an enum like type + DeployKeys []struct { + Name string + Key string + } + PostHooks []string + BranchManagement struct { + PreventDelete []string + PreventRebase []string + AllowPushes []struct { + BranchName string + Groups []string + Users []string + } + } + + AccessManagement struct { + Users []struct { + User string + Permission string // TODO unmarshal permission into an enum like type (read, write, adming) + } + Groups []struct { + Group string + Permission string // TODO unmarshal permission into an enum like type (read, write, adming) + } + } +} + +var configFile = flag.String("config", "golive.json", "the configfile to read") +var verbose = flag.Bool("v", false, "print more output") func main() { oauth_key := os.Getenv("BITBUCKET_ENFORCER_KEY") @@ -12,3 +51,19 @@ fmt.Println("key:", oauth_key) fmt.Println("pass:", oauth_pass) } + +func parseConfig(configFile string) RepositorySettings { + config_raw, err := ioutil.ReadFile(configFile) + if err != nil { + log.Fatal(err) + } + + var config RepositorySettings + json.Unmarshal(config_raw, &config) + + if *verbose { + log.Print("Loaded config: ", config) + } + + return config +}
dd8265b042b9a9194eb792bdb1611f0096c05b62
--- +++ @@ -13,7 +13,11 @@ ) func NewClient(cfg *config.Config) (*dockerClient.Client, error) { - client, err := dockerClient.NewClient(cfg.DockerEndpoint) + endpoint := "unix:///var/run/docker.sock" + if cfg != nil { + endpoint = cfg.DockerEndpoint + } + client, err := dockerClient.NewClient(endpoint) if err != nil { return nil, err }
ff05bb523b574b14c16dc8ac5744ab2d7a08a9b7
--- +++ @@ -11,11 +11,11 @@ // // If the scores file is empty, the returned entries are empty. func (c *Config) ReadEntries() (*scoring.Entries, error) { - var entries *scoring.Entries + var entries scoring.Entries scoresFile, err := c.scoresFile() if err != nil { - return entries, nil + return &entries, nil } defer closeLockedFile(scoresFile) @@ -25,11 +25,11 @@ if err := decoder.Decode(&entries); err == io.EOF { break } else if err != nil { - return entries, err + return &entries, err } } - return entries, nil + return &entries, nil } // WriteEntries the input scoring entries to a file.
68fe9c1000e3e6cf3fba586ee4f319f62feeecb3
--- +++ @@ -1,8 +1,6 @@ package cmd import ( - "syscall" - "github.com/spf13/cobra" ) @@ -11,13 +9,11 @@ Short: "Stop a daemon", Long: "", RunE: func(cmd *cobra.Command, args []string) error { - - syscall.Kill(syscall.Getpid(), syscall.SIGTERM) - - return nil + _, err := restClient.R().Post("/api/v1/stop") + return err }, } func init() { - daemon.AddCommand() + daemon.AddCommand(daemonStopCmd) }
20b747c3fbd9d547dbb232c8560630e102f11e45
--- +++ @@ -1,7 +1,7 @@ package controllers import ( - "github.com/anonx/sunplate/skeleton/assets/views" + v "github.com/anonx/sunplate/skeleton/assets/views" "github.com/anonx/sunplate/action" ) @@ -18,14 +18,14 @@ // Index is an action that is used for generation of a greeting form. func (c *App) Index() action.Result { - return c.RenderTemplate(views.Paths.App.IndexHTML) + return c.RenderTemplate(v.Paths.App.IndexHTML) } // PostGreet prints received user fullname. If it is not valid, // user is redirected back to index page. func (c *App) PostGreet(name string) action.Result { c.Context["name"] = name - return c.RenderTemplate(views.Paths.App.GreetHTML) + return c.RenderTemplate(v.Paths.App.GreetHTML) } // After is a magic method that is executed after every request.
8ba5485db6ebfa824458df98db6df29cbe128332
--- +++ @@ -19,7 +19,7 @@ fields := make([]zapcore.Field, len(data)) i := 0 for k, v := range data { - fields[i] = zap.Reflect(k, v) + fields[i] = zap.Any(k, v) i++ }
2c0a355ba4328baae3e266d06f2b29c9efff996e
--- +++ @@ -6,13 +6,18 @@ "github.com/Cepave/open-falcon-backend/cmd" "github.com/spf13/cobra" - flag "github.com/spf13/pflag" ) var versionFlag bool var RootCmd = &cobra.Command{ Use: "open-falcon", + Run: func(cmd *cobra.Command, args []string) { + if versionFlag { + fmt.Printf("Open-Falcon version %s, build %s\n", Version, GitCommit) + os.Exit(0) + } + }, } func init() { @@ -22,17 +27,13 @@ RootCmd.AddCommand(cmd.Check) RootCmd.AddCommand(cmd.Monitor) RootCmd.AddCommand(cmd.Reload) + + RootCmd.Flags().BoolVarP(&versionFlag, "version", "v", false, "show version") cmd.Start.Flags().BoolVar(&cmd.PreqOrderFlag, "preq-order", false, "start modules in the order of prerequisites") cmd.Start.Flags().BoolVar(&cmd.ConsoleOutputFlag, "console-output", false, "print the module's output to the console") - flag.BoolVarP(&versionFlag, "version", "v", false, "show version") - flag.Parse() } func main() { - if versionFlag { - fmt.Printf("Open-Falcon version %s, build %s\n", Version, GitCommit) - os.Exit(0) - } if err := RootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1)
f53e12216c70c4fc0a423cd873eb76d50e2a1e2f
--- +++ @@ -7,10 +7,18 @@ // HelpForHelp shows overall usage information for the BigV client, including a list of available commands. func (cmds *CommandSet) HelpForHelp() { - // TODO(telyn): write real usage information fmt.Println("bigv command-line client (the new, cool one)") fmt.Println() - fmt.Println("There would be some usage output here if I had actually written any.") + fmt.Println("Usage") + fmt.Println() + fmt.Println(" go-bigv [flags] <command> [flags] [args]") + fmt.Println() + fmt.Println("Commands available") + fmt.Println() + fmt.Println(" help, config, create, debug, delete, list, show") + fmt.Println(" AND MAYBE MORE OR FEWER - THIS LIST IS NOT FINAL") + fmt.Println() + fmt.Println("See `go-bigv help <command>` for help specific to a command") fmt.Println() }
c3a633c440d6658490191a819be4f33b909f808a
--- +++ @@ -1,18 +1,17 @@ package main import ( -// "bufio" -// "fmt" -// "os" -// "regexp" + "bufio" + "fmt" + "os" + "regexp" ) func findDeviceFromMount (mount string) (string, error) { // stub for Mac devel - return "/dev/xvda", nil - /* + //return "/dev/xvda", nil var device string = "" // Serious Linux-only stuff happening here... file := "/proc/mounts" @@ -38,7 +37,6 @@ return device, fmt.Errorf("No device found for mount %s", mount) } return device, nil - */ } func verifyInstance(instance string) (string, error) {
eb4c0f0437eb7d8ffd678f9ce0bde2f8e2651e1f
--- +++ @@ -7,11 +7,6 @@ "testing" gitjujutesting "github.com/juju/testing" - jc "github.com/juju/testing/checkers" - gc "gopkg.in/check.v1" - "gopkg.in/mgo.v2" - - "github.com/juju/juju/mongo" ) // MgoTestPackage should be called to register the tests for any package @@ -19,28 +14,3 @@ func MgoTestPackage(t *testing.T) { gitjujutesting.MgoTestPackage(t, Certs) } - -// NewServerReplSet returns a new mongo server instance to use in -// testing with replicaset. The caller is responsible for calling -// inst.Destroy() when done. -func NewServerReplSet(c *gc.C) *gitjujutesting.MgoInstance { - inst := &gitjujutesting.MgoInstance{Params: []string{"--replSet", mongo.ReplicaSetName}} - err := inst.Start(Certs) - c.Assert(err, jc.ErrorIsNil) - - // Verify the server is up before returning. - - session, err := inst.DialDirect() - if err != nil { - inst.Destroy() - c.Fatalf("error dialing mongo server: %v", err.Error()) - } - defer session.Close() - - session.SetMode(mgo.Monotonic, true) - if err = session.Ping(); err != nil { - inst.Destroy() - c.Fatalf("error pinging mongo server: %v", err.Error()) - } - return inst -}
fec55e7fe9f34ab5ea4eb54df8c945dc5ab46e70
--- +++ @@ -15,12 +15,8 @@ // Mapping holding all of the UIs that can be learned. The mapping // holds a generator to generate the UI. -var allUI map[string]func() (UI, error) - -func init() { - allUI = make(map[string]func() (UI, error)) - - Register("simple", newSimpleUI) +var allUI = map[string]func() (UI, error){ + "simple": newSimpleUI, } // Register adds a new user interface. Any database with the given
9608a88347f547e8ba767ad34f24b5fd61688eae
--- +++ @@ -5,12 +5,13 @@ "github.com/eris-ltd/erisdb/server" "os" "github.com/gin-gonic/gin" + "path" ) func main() { gin.SetMode(gin.ReleaseMode) - baseDir := os.Getenv("HOME") + "/.edbservers" + baseDir := path.Join(os.TempDir(), "/.edbservers") ss := ess.NewServerServer(baseDir) proc := server.NewServeProcess(nil, ss) err := proc.Start()
ed0a57ba99d9cdab0167e4df1851f8755fd5217d
--- +++ @@ -2,6 +2,7 @@ import ( "flag" + "fmt" "github.com/anchor/picolog" "github.com/fractalcat/emogo" zmq "github.com/pebbe/zmq4" @@ -9,6 +10,17 @@ ) var Logger *picolog.Logger + +func readFrames(e *emogo.EmokitContext, out chan *emogo.EmokitFrame) { + for { + f, err := e.WaitGetFrame() + if err != nil { + fmt.Printf("error reading frame: %v", err) + return + } + out <- f + } +} func main() { listen := flag.String("listen", "tcp://*:9424", "ZMQ URI to listen on.") @@ -26,5 +38,13 @@ if err != nil { Logger.Fatalf("Could not bind to %s: %v", listen, err) } - _ = eeg + frameChan := make(chan *emogo.EmokitFrame, 0) + readFrames(eeg, frameChan) + for { + f := <-frameChan + _, err := sock.SendBytes(f.Raw(), 0) + if err != nil { + fmt.Printf("Error sending raw frame: %v", err) + } + } }
4653497dc470d2d9e10d16bf8450d83a47abd522
--- +++ @@ -5,10 +5,10 @@ ) func TestUpdate(t *testing.T) { - s1 := Update(users, Values{"name": "client"}) + stmt := Update(users, Values{"name": "client"}) expectedSQL( t, - s1, + stmt, `UPDATE "users" SET "name" = $1`, 1, ) @@ -18,19 +18,25 @@ "password": "blank", } - s2 := Update(users, values).Where(users.C["id"].Equals(1)) + stmt = Update(users, values).Where(users.C["id"].Equals(1)) expectedSQL( t, - s2, + stmt, `UPDATE "users" SET "name" = $1 AND "password" = $2 WHERE "users"."id" = $3`, 3, ) - // The statement should have an error if a values key does not have an - // associated column - s3 := Update(users, Values{}) - _, err := s3.Compile(&defaultDialect{}, Params()) + // The statement should have an error if the values map is empty + stmt = Update(users, Values{}) + _, err := stmt.Compile(&defaultDialect{}, Params()) if err == nil { t.Fatalf("No error returned from column-less UPDATE") } + + // Attempt to update values with keys that do not correspond to columns + stmt = Update(users, Values{"nope": "what"}) + _, err = stmt.Compile(&defaultDialect{}, Params()) + if err == nil { + t.Fatalf("no error returned from UPDATE without corresponding column") + } }
794b4dcd83c62ded650d58a198f3764f5fcc74b7
--- +++ @@ -32,7 +32,7 @@ if p.CorrectAnswer == "NA" { fmt.Println("Problem", p.ID, "has not been solved yet.") } else { - fmt.Println("Answer to problem", p.ID, "is", p.Solver()) + fmt.Println("Answer to problem", p.ID, "is", p.Solver(), "(took", p.Attempts, "attempts)") } }
a6ac84b7c8d5c2de2d5f2dc735503f07325ce9c1
--- +++ @@ -32,7 +32,7 @@ func handleSigTerm() { // shutdown - c := make(chan os.Signal) + c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, syscall.SIGTERM) go func() { <-c
12c14bfd34be16ffe6796b24ef7693cfe63ee109
--- +++ @@ -20,7 +20,7 @@ */ server.Get("/v1/users", common.CheckAuth, Login) server.Post("/v1/users", CreateUser) - server.Put("/v1/users", common.CheckAuth, UpdateUser) + server.Put("/v1/users/:username", common.CheckAuth, UpdateUser) /* User repository routes
622f62c62b102a7e2a71688d9163b90fcd55326c
--- +++ @@ -11,12 +11,12 @@ func Control(network, address string, c syscall.RawConn) error { var err error c.Control(func(fd uintptr) { - err = syscall.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1) + err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1) if err != nil { return } - err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, syscall.SO_REUSEPORT, 1) + err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1) if err != nil { return }
bd82db83810aa98ca78bbe742b1f95f3413a4073
--- +++ @@ -4,6 +4,9 @@ "goa.design/goa/v3/eval" "goa.design/goa/v3/expr" ) + +// Val is an alias for expr.Val. +type Val expr.Val // Value sets the example value. //
82573bb49c3a80fa55616f0d3b0fee563b0cef17
--- +++ @@ -2,6 +2,10 @@ import ( "encoding/json" + "time" + + "code.google.com/p/go-uuid/uuid" + "iotrules/mylog" ) @@ -27,6 +31,8 @@ defer func() { mylog.Debugf("exit NewNotifFromCB (%+v,%v)\n", n, err) }() n = &Notif{Data: map[string]interface{}{}} + n.ID = uuid.New() + n.Received = time.Now() var ncr NotifyContextRequest err = json.Unmarshal(ngsi, &ncr)
16bf85fc85d292271efdd3b9fcbc91abe1e2c4de
--- +++ @@ -26,6 +26,11 @@ for hostname, sub := range herd.subsByName { if sub.hostname == "" { subsToDelete = append(subsToDelete, hostname) + if sub.connection != nil { + // Destroying a Client doesn't free up all the memory, so call + // the Close() method to free up the memory. + sub.connection.Close() + } } } for _, hostname := range subsToDelete {
a97b09ce55a0be3ad5a34c2b4a92cd324924809b
--- +++ @@ -13,9 +13,11 @@ import "unsafe" +func init() { + C.pg_query_init() +} + func Parse(input string) string { - C.pg_query_init() - input_c := C.CString(input) defer C.free(unsafe.Pointer(input_c))
46688a6f88fdf54ed64b0669386cda3024c080c7
--- +++ @@ -15,12 +15,14 @@ } func (c *catalogServices) CommandFlags() *flag.FlagSet { - return newFlagSet() + f := newFlagSet() + + c.addDatacenterFlag(f) + c.addOutputFlags(f, false) + c.addConsistencyFlags(f) + + return f } - -// addDatacenterOption(cmd) -// addTemplateOption(cmd) -// addConsistencyOptions(cmd) func (c *catalogServices) Run(args []string) error { client, err := c.newCatalog()
e377444404f140bb5eff13b9cc38d8cc4b362b50
--- +++ @@ -21,6 +21,12 @@ return err } + // Darken background area + err = exec.Command( + "gsettings", "set", "org.gnome.desktop.background", + "primary-color", "#000000", + ).Run() + // Set the background (gnome3 only atm) err = exec.Command( "gsettings", "set", "org.gnome.desktop.background",
de2a451f9c30ada011f0b5e471fd04a3770f9be1
--- +++ @@ -22,6 +22,19 @@ } } +func (vb *VirtualBox) CreateHardDisk(format, location string) (*Medium, error) { + vb.Logon() + + request := vboxwebsrv.IVirtualBoxcreateHardDisk{This: vb.managedObjectId, Format: format, Location: location} + + response, err := vb.IVirtualBoxcreateHardDisk(&request) + if err != nil { + return nil, err // TODO: Wrap the error + } + + return &Medium{virtualbox: vb, managedObjectId: response.Returnval}, nil +} + func (vb *VirtualBox) Logon() error { if vb.managedObjectId != "" { // Already logged in @@ -42,16 +55,3 @@ return nil } - -func (vb *VirtualBox) CreateHardDisk(format, location string) (*Medium, error) { - vb.Logon() - - request := vboxwebsrv.IVirtualBoxcreateHardDisk{This: vb.managedObjectId, Format: format, Location: location} - - response, err := vb.IVirtualBoxcreateHardDisk(&request) - if err != nil { - return nil, err // TODO: Wrap the error - } - - return &Medium{virtualbox: vb, managedObjectId: response.Returnval}, nil -}
430a6a56aaa63b8236a9b71fb4e4c07d31b68cf9
--- +++ @@ -28,6 +28,12 @@ const OpenStackJumpboxKeystoneV3Ops = `--- - type: remove + path: /instance_groups/name=jumpbox/networks/name=public + +- type: remove + path: /networks/name=public + +- type: remove path: /cloud_provider/properties/openstack/tenant - type: replace
605ca2cc43ff3ac0971da11ca974738000896fd1
--- +++ @@ -22,7 +22,7 @@ func main() { d := net.Dialer{Timeout: 10 * time.Second} - p := make(chan bool, 500) // make 500 parallel connection + p := make(chan struct{}, 500) // make 500 parallel connection wg := sync.WaitGroup{} c := func(port int) { @@ -37,7 +37,7 @@ wg.Add(65536) for i := 0; i < 65536; i++ { - p <- true + p <- struct{}{} go c(i) }
bed13b0916edd31ad1e85bd74bea71dd8b4276fb
--- +++ @@ -1,9 +1,32 @@ package config import ( + "errors" + "fmt" "os" "syscall" ) + +type closedError struct { + flockErr error + fileErr error +} + +func (ce closedError) Error() string { + return fmt.Sprintf("%s, %s", ce.fileErr.Error(), ce.flockErr.Error()) +} + +func newClosedError(flockErr, fileErr error) error { + if fileErr == nil { + fileErr = errors.New("no file errors") + } + + if flockErr == nil { + flockErr = errors.New("no lock errors") + } + + return closedError{flockErr, fileErr} +} func createOrOpenLockedFile(name string) (file *os.File, err error) { if _, err := os.Stat(name); os.IsNotExist(err) { @@ -16,14 +39,20 @@ return } - if flerr := syscall.Flock(int(file.Fd()), syscall.LOCK_EX); flerr != nil { - return file, flerr + if flockErr := syscall.Flock(int(file.Fd()), syscall.LOCK_EX); flockErr != nil { + err = flockErr } return } func closeLockedFile(file *os.File) error { - syscall.Flock(int(file.Fd()), syscall.LOCK_UN) - return file.Close() + flockErr := syscall.Flock(int(file.Fd()), syscall.LOCK_UN) + fileErr := file.Close() + + if flockErr != nil || fileErr != nil { + return newClosedError(flockErr, fileErr) + } + + return nil }
72babd93910d2458ce8764451125e6642149392c
--- +++ @@ -2,6 +2,7 @@ import ( "encoding/json" + "fmt" "io" "github.com/hackebrot/turtle" @@ -13,8 +14,24 @@ } // NewJSONWriter creates a new JSONWriter -func NewJSONWriter(w io.Writer) *JSONWriter { - return &JSONWriter{e: json.NewEncoder(w)} +func NewJSONWriter(w io.Writer, options ...func(*JSONWriter) error) (*JSONWriter, error) { + j := &JSONWriter{e: json.NewEncoder(w)} + + for _, option := range options { + if err := option(j); err != nil { + return nil, fmt.Errorf("error applying option: %v", err) + } + } + + return j, nil +} + +// WithIndent sets an indent on adds a separator to a thread +func WithIndent(prefix, indent string) func(*JSONWriter) error { + return func(j *JSONWriter) error { + j.e.SetIndent(prefix, indent) + return nil + } } // WriteEmoji to an io.Writer
d5f261bf4aa0d589cce6d27662b9a313845600f8
--- +++ @@ -16,20 +16,17 @@ // Day returns a time.Time referencing the beginning of the next day func Day(t time.Time) time.Time { - t = t.AddDate(0, 0, 1) - return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()) + return time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, t.Location()) } // Week returns a time.Time referencing the beginning of the next week Sun->Sat func Week(t time.Time) time.Time { weekRemainder := 7 - int(t.Weekday()) - nextWeek := t.AddDate(0, 0, weekRemainder) - return time.Date(nextWeek.Year(), nextWeek.Month(), nextWeek.Day(), 0, 0, 0, 0, t.Location()) + return time.Date(t.Year(), t.Month(), t.Day()+weekRemainder, 0, 0, 0, 0, t.Location()) } // Month returns a time.Time referencing the beginning of the next month func Month(t time.Time) time.Time { // truncate starting time back to beginning of the month - t = time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location()) - return t.AddDate(0, 1, 0) + return time.Date(t.Year(), t.Month()+1, 1, 0, 0, 0, 0, t.Location()) }
cb82e4bba6b3e526ffdd7cf607474ce3ea9ab953
--- +++ @@ -1,31 +1,39 @@ package main import ( - "math/big" "testing" ) -func sumOfPrimesBelow(x int64) int64 { - var i int64 - var sum int64 = 0 - for i = 2; i < x; i++ { - if i > 2 && i%2 == 0 { +func sumOfPrimesBelow(x int) int { + sieve := make([]bool, x) + for i:=0; i<x; i++ { + sieve[i] = true + } + sieve[0] = false + sieve[1] = false + + for i:=2; i<x; i++ { + if sieve[i] == false { continue } + for j:=2*i; j<x; j+=i { + sieve[j] = false + } + + } - j := big.NewInt(i) - if !j.ProbablyPrime(10) { - continue + sum := 0 + for i:=2; i<x; i++ { + if sieve[i] { + sum += i; } - sum += i - } return sum } func TestSumOfPrimesBelow2M(t *testing.T) { x := sumOfPrimesBelow(2000000) - var answer int64 = 142913828922 + answer := 142913828922 if x != answer { t.Errorf("result = %v, want %v", x, answer) }
5241cdb4403e99e6debd06c2d6ed2d8e4d1f3bfd
--- +++ @@ -1,6 +1,9 @@ package main -import "net/http" +import ( + "net/http" + "strings" +) // Wiki represents the entire Wiki, contains the db type Wiki struct { @@ -25,16 +28,21 @@ path := r.URL.Path action := queryValues.Get("action") + isDir := len(wiki.store.GetPageList(path)) > 0 || len(wiki.store.DirList(path)) > 0 + + if isDir && !strings.HasSuffix(path, "/") { + http.Redirect(w, r, path+"/", http.StatusSeeOther) + return + } + switch { case r.PostFormValue("update") == "update": wiki.Update(w, r) case action == "edit": wiki.Edit(w, r) + case isDir: + wiki.Dir(w, r) default: - if len(wiki.store.GetPageList(path)) > 0 || len(wiki.store.DirList(path)) > 0 { - wiki.Dir(w, r) - } else { - wiki.Show(w, r) - } + wiki.Show(w, r) } }
fcf2e07e569963afcf198464186b423217f0294b
--- +++ @@ -2,6 +2,7 @@ import ( "os" + "strings" . "github.com/cloudfoundry/cli/testhelpers/io" . "github.com/onsi/ginkgo" @@ -10,10 +11,12 @@ var _ = Describe("io helpers", func() { It("will never overflow the pipe", func() { - str := "" + characters := make([]string, 0, 75000) for i := 0; i < 75000; i++ { - str += "abc" + characters = append(characters, "z") } + + str := strings.Join(characters, "") output := CaptureOutput(func() { os.Stdout.Write([]byte(str))
213c80bc286672657ced52e03374b528f20a965e
--- +++ @@ -7,7 +7,7 @@ func main() { router := NewRouter() - err := http.ListenAndServe(":8080", router) + err := http.ListenAndServe(":" + os.Getenv("PORT"), router) if err != nil { log.Fatal("ListenAndServe Error: ", err) }
8a139b3b78298bca28de8e558297800413eaf186
--- +++ @@ -21,3 +21,17 @@ // mount_gcsfuse does not daemonize, and therefore must be used with a wrapper // that performs daemonization if it is to be used directly with mount(8). package main + +import ( + "log" + "os" +) + +func main() { + // Print out each argument. + for i, arg := range os.Args { + log.Printf("Arg %d: %q", i, arg) + } + + os.Exit(1) +}
ba1e8ad5e4b20b92684f9b7c4bf3efb35a2fe0e1
--- +++ @@ -13,8 +13,7 @@ // are UPPERCASE, and any dashes are replaced by underscores. Environment // variables additionally are prefixed by the given string followed by // and underscore. For example, if prefix=PREFIX: some-flag => PREFIX_SOME_FLAG -func SetFlagsFromEnv(fs *flag.FlagSet, prefix string) error { - var err error +func SetFlagsFromEnv(fs *flag.FlagSet, prefix string) (err error) { alreadySet := make(map[string]bool) fs.Visit(func(f *flag.Flag) { alreadySet[f.Name] = true
8fb49dc9153c4593b739a5950ae2bc8cbddc758f
--- +++ @@ -1,19 +1,32 @@ package v1 import ( + "net/http" + "time" + "github.com/codegangsta/martini" "github.com/coopernurse/gorp" "github.com/hackedu/backend/v1/model" "github.com/hackedu/backend/v1/route" "github.com/martini-contrib/binding" + "github.com/zachlatta/cors" ) func Setup(m *martini.ClassicMartini) { // TODO: Only apply middleware on /v1/** routes - m.Use(allowCORS) + m.Use(cors.Allow(&cors.Options{ + AllowAllOrigins: true, + AllowMethods: []string{"GET", "POST"}, + MaxAge: 5 * time.Minute, + })) m.MapTo(Dbm, (*gorp.SqlExecutor)(nil)) m.Get("/v1/schools", route.GetSchools) m.Post("/v1/users", binding.Bind(model.User{}), route.AddUser) + + // OPTIONS catchall for CORS. + m.Options("/**", func() int { + return http.StatusOK + }) }
50c1804b294cfdebf84285c312124583867d3e34
--- +++ @@ -3,11 +3,12 @@ import ( "log" "net/http" + "os" ) func main() { var g GMHook - err := http.ListenAndServe("localhost:4000", g) + err := http.ListenAndServe(":"+os.Getenv("PORT"), g) if err != nil { log.Fatal(err) }
c031a75a5033c732635f0d66032a2bb0d7f709ed
--- +++ @@ -16,4 +16,9 @@ assert.Panics(t, func() { noGenerationKey.GetUID() }, "Panic expected if key is incorrect") assert.Panics(t, func() { noGenerationKey.GetGeneration() }, "Panic expected if key is incorrect") + + invalidGenerationKey := Key("72b062c1-7fcf-11e7-ab09-acde48001122$bad") + + assert.Equal(t, util.UID("72b062c1-7fcf-11e7-ab09-acde48001122"), correctKey.GetUID(), "Correct UID expected") + assert.Panics(t, func() { invalidGenerationKey.GetGeneration() }, "Panic expected if key is incorrect") }
50bcc11856a4cf4951234cb29a56993789d69c7e
--- +++ @@ -20,6 +20,8 @@ func CheckAuth(req *f.Request, res *f.Response, next func()) { auth := req.Get("authorization") + req.Map["_uid"] = -1 + req.Map["_admin"] = false if len(auth) == 0 { res.Send("No authorization provided.", 401) @@ -37,4 +39,5 @@ res.Send("Unauthorized", 401) } req.Map["_uid"] = u.Id + req.Map["_admin"] = u.Admin }
68d16c936752d5c43f330b981bbd4b215654d13b
--- +++ @@ -2,7 +2,7 @@ package version const ( - version = "0.2.0" + version = "0.2.1" ) // return the current application version
bb1c4db925a715716fdf7293051fa810858cd4a9
--- +++ @@ -6,6 +6,7 @@ "restrictSources", "userToken", "validUntil", + "referers", ); err != nil { return err } @@ -20,6 +21,11 @@ case "validUntil": if _, ok := v.(int); !ok { return invalidType(k, "int") + } + + case "referers": + if _, ok := v.([]string); !ok { + return invalidType(k, "[]string") } default:
ea9e6806e8f708aee08267b358de0cb6e9990925
--- +++ @@ -6,6 +6,9 @@ func Ue(data Interface) int { len := data.Len() + if len == 0 { + return 0 + } i, j := 0, 1 // find the first duplicate for j < len && data.Less(i, j) {
4d9393ae0de684f654ea0eb61e9712317b0dde3a
--- +++ @@ -1,4 +1,8 @@ package schedule + +import ( + "time" +) type ScheduleEntries int @@ -11,10 +15,35 @@ TWO ScheduleEntries = 2 THREE ScheduleEntries = 3 FOUR ScheduleEntries = 4 + + NUM_WEEK_DAYS = 7 ) +// BuildCommitSchedule returns an empty CommitSchedule, where all fiels are +// initialized with EMPTY except those which are not in the range of days. +// The CommitSchedule is a table of ints. func BuildCommitSchedule(days []time.Time) CommitSchedule { // get weeks, which determine width and height is seven // fill entries with EMPTY or NOT_A_FIELD - return nil + schedule := make(CommitSchedule, 0) // TODO figure out num weeks + // firstWeek := buildFirstWeek(days[0].Weekday()) + // lastWeek := buildLastWeek(days[len(days)-1].Weekday()) + // TODO get days inbetween first and last week and join them + return schedule } + +func buildFirstWeek(day time.Weekday) []int { + var firstWeek []int + for i := 0; i < NUM_WEEK_DAYS; i++ { + firstWeek = append(firstWeek, i) + } + return firstWeek +} + +func buildLastWeek(day time.Weekday) []int { + var lastWeek []int + for i := 0; i < NUM_WEEK_DAYS; i++ { + lastWeek = append(lastWeek, i) + } + return lastWeek +}
66e0d54c023596c02e0a6e01a3a46d6e9ffcd295
--- +++ @@ -20,10 +20,11 @@ // Default parameter values. const ( - DclMaxMemoCharacters uint64 = authtypes.DefaultMaxMemoCharacters - DclTxSigLimit uint64 = authtypes.DefaultTxSigLimit - DclTxSizeCostPerByte uint64 = 0 // gas is not needed in DCL - DclSigVerifyCostED25519 uint64 = 0 // gas is not needed in DCL - DclSigVerifyCostSecp256k1 uint64 = 0 // gas is not needed in DCL - AccountApprovalsPercent float64 = 0.66 + DclMaxMemoCharacters uint64 = authtypes.DefaultMaxMemoCharacters + DclTxSigLimit uint64 = authtypes.DefaultTxSigLimit + DclTxSizeCostPerByte uint64 = 0 // gas is not needed in DCL + DclSigVerifyCostED25519 uint64 = 0 // gas is not needed in DCL + DclSigVerifyCostSecp256k1 uint64 = 0 // gas is not needed in DCL + AccountApprovalsPercent float64 = 0.66 + VendorAccountApprovalsPercent float64 = 0.33 )
ce572432f91d48f35559925bfa4a15f8dbbce30a
--- +++ @@ -14,6 +14,7 @@ COLLECTION Type = "<collection>" CONTAINER Type = "<container>" HASHER Type = "<hasher>" + ANY Type = "<any>" /* Normal Types */ NUMBER Type = "<number>" @@ -32,6 +33,10 @@ ) func is(obj Object, t Type) bool { + if t == ANY { + return true + } + if t == COLLECTION { _, ok := obj.(Collection) return ok @@ -47,9 +52,5 @@ return ok } - if obj.Type() == t { - return true - } - - return false + return obj.Type() == t }
7e3d5535dde7ce18b28d3ee1b12ded170dcac792
--- +++ @@ -9,6 +9,7 @@ type Play struct { NodeTemplate NodeTemplate + InterfaceName string OperationName string } @@ -17,9 +18,9 @@ i := 0 index := make(map[int]Play, 0) for _, node := range s.TopologyTemplate.NodeTemplates { - for _, intf := range node.Interfaces { + for intfn, intf := range node.Interfaces { for op, _ := range intf.Operations { - index[i] = Play{node, op} + index[i] = Play{node, intfn, op} i += 1 } }
f9a8c9a68124f765dbf727e286e4ff56b9d8b5b0
--- +++ @@ -1,9 +1,15 @@ package gstrings import ( + "fmt" "github.com/wallclockbuilder/testify/assert" "testing" ) + +func ExampleSize(){ + fmt.Println(Size("hello")) + // Output: 5 +} func TestSize(t *testing.T) { assert := assert.New(t)
9262c5b32f99d677b6878984e35dbd6a5b31fbd8
--- +++ @@ -16,9 +16,10 @@ import ( "runtime" + "os" + "github.com/spf13/hugo/commands" jww "github.com/spf13/jwalterweatherman" - "os" ) func main() { @@ -28,4 +29,10 @@ if jww.LogCountForLevelsGreaterThanorEqualTo(jww.LevelError) > 0 { os.Exit(-1) } + + if commands.Hugo != nil { + if commands.Hugo.Log.LogCountForLevelsGreaterThanorEqualTo(jww.LevelError) > 0 { + os.Exit(-1) + } + } }
fe764f09ca3f776eee1f5b5dfa680502f9ae4ede
--- +++ @@ -6,6 +6,10 @@ ) func TestDefaultSessionConfig(t *testing.T) { + // Cleanup before the test + os.Unsetenv("AWS_DEFAULT_REGION") + os.Unsetenv("AWS_REGION") + cases := []struct { expected string export bool @@ -19,10 +23,10 @@ exportVal: "", }, { - expected: "ap-southeast-1", + expected: "ap-southeast-2", export: true, exportVar: "AWS_DEFAULT_REGION", - exportVal: "ap-southeast-1", + exportVal: "ap-southeast-2", }, { expected: "us-west-2",
1c03ff45cda99e5bf750797c2acbeb962b3a8e89
--- +++ @@ -10,10 +10,18 @@ "net/http" ) +// ErrNotFound gets passed to a Router's ErrorHandler if +// no route matched the request path or none of the matching routes wrote +// a response. var ErrNotFound = errors.New(http.StatusText(http.StatusNotFound)) -var StdErrorHandler = ErrorHandlerFunc(StdErrorHandlerFunc) -func StdErrorHandlerFunc(res ResponseWriter, req *Request, err error) { +// StdErrorHandler is the default ErrorHandler added to all Server instances +// created with NewServer(). +// +// All errors, except ErrNotFound, passed to it result in an internal server error (500) including +// the message in the response body. The ErrNotFound error results +// in a "not found" (404) response. +var StdErrorHandler = ErrorHandlerFunc(func(res ResponseWriter, req *Request, err error) { status := http.StatusInternalServerError if err == ErrNotFound { @@ -22,4 +30,4 @@ res.WriteHeader(status) fmt.Fprintf(res, err.Error()) -} +})
42f2186cd3ba22bec9d91fa8db313dce0fdc126a
--- +++ @@ -10,9 +10,9 @@ // CreateUser creates a new user with keycloak func CreateUser(ctx worker.Context, args ...interface{}) error { fmt.Println("Working on job", ctx.Jid()) - err := keycloak.KeycloakCreateUser(args[0]) + err := keycloak.KeycloakCreateUser(args[0].(string)) if err != nil { - return ctx.Error(500, err) + return ctx.Err() } return err }
87ce5635037d59ba58f6a66522b1c0083d06411b
--- +++ @@ -19,7 +19,7 @@ for _, tt := range testCases { actual := ToDecimal(tt.binary) if actual != tt.expected { - t.Fatalf("ToDecimal(%v): expected %d, actual %d", tt.binary, tt.expected, actual) + t.Fatalf("ToDecimal(%v): expected %v, actual %v", tt.binary, tt.expected, actual) } } }
1fb1394e83bb05775e26440ae7b5d51dc4241a32
--- +++ @@ -25,6 +25,9 @@ if err := u.Authenticate(password); err != nil { return errors.New("invalid password") } + if u.IsDisabled { + return errors.New("disabled account") + } session, _ := s.sessions.Get(r, sessionName) session.Values[sessionUserID] = u.ID session.Save(r, w)
a144fcfdb707ccb883a33a1e44473f51ca5f9843
--- +++ @@ -17,7 +17,7 @@ fmt.Println() fmt.Printf("%d|", i+1) for j := 0; j < 8; j++ { - fmt.Print(" |") + fmt.Printf("%c|", Piece(Point{i, j})) } fmt.Println(i + 1) }
9eb88c578b43a36fca89513f00e4b0cfe3fbbca7
--- +++ @@ -1,4 +1,54 @@ package main +import ( + "flag" + "fmt" + "io/ioutil" +) + +var flag_profit int + +func init() { + flag.IntVar(&flag_profit, "profit", -1, "a min amount that you want to win") +} + +func parseGames() <-chan []LottoGame { + parsedGames := make(chan []LottoGame) + + go func() { + bytes, err := ioutil.ReadFile("scratcher.txt") + if err != nil { + panic(err) + } + + games, err := ParseLotteryGames(bytes) + if err != nil { + panic(err) + } + parsedGames <- games + }() + + return parsedGames +} + func main() { + flag.Parse() + + // Async load the LottoGames from the datafile + gamesCh := parseGames() + + var profit int + if flag_profit == -1 { + // Profit parameter wasn't passed on the commandline + // TODO: Ask the user for the profit using stdin + panic("invalid profit") + } else { + profit = flag_profit + } + + games := <-gamesCh + + for _, game := range games { + fmt.Println(game.OddsOfWinning(profit)) + } }
8d436c8d2297250f8f25373156462eb633fe81f7
--- +++ @@ -3,19 +3,20 @@ package tv_test import ( + "time" + "github.com/appneta/go-traceview/v1/tv" "golang.org/x/net/context" ) -func ExampleBeginProfile(ctx context.Context) { - defer tv.BeginProfile(ctx, "example").End() - // ... do something ... +func slowFunc(ctx context.Context) { + defer tv.BeginProfile(ctx, "slowFunc").End() + // ... do something else ... + time.Sleep(1 * time.Second) } -func ExampleBeginProfile_func(ctx context.Context) { - // typically this would be used in a named function - func() { - defer tv.BeginProfile(ctx, "example_func").End() - // ... do something else ... - }() +func Example() { + ctx := tv.NewContext(context.Background(), tv.NewTrace("myLayer")) + slowFunc(ctx) + tv.EndTrace(ctx) }
69269e6470f0bf9bcd78770fea6b6c99945fd32f
--- +++ @@ -23,15 +23,27 @@ if err != nil { return "", err } + _, err = exchangeCode(number) + if err != nil { + return "", err + } return number, nil } func AreaCode(phoneNumber string) (areaCode string, e error) { areaCode = phoneNumber[0:3] if strings.HasPrefix(areaCode, "0") || strings.HasPrefix(areaCode, "1") { - return "", fmt.Errorf("area code %v can not start with 0", areaCode) + return "", fmt.Errorf("area code %v can not start with 0 or 1", areaCode) } return areaCode, nil +} + +func exchangeCode(phoneNumber string) (exchangeCode string, e error) { + exchangeCode = phoneNumber[3:6] + if strings.HasPrefix(exchangeCode, "0") || strings.HasPrefix(exchangeCode, "1") { + return "", fmt.Errorf("exchange code %v can not start with 0 or 1", exchangeCode) + } + return exchangeCode, nil } func Format(phoneNumber string) (string, error) {
b99f21ab009fcc03f072921a11daf77e38a20be8
--- +++ @@ -1,6 +1,21 @@ -package main +package dbr import ( "fmt" - "dbr" ) + +type EventReceiver interface { + Event(eventName string) + EventKv(eventName string, kvs map[string]string) +} + +type TimingReceiver interface { + Timing(eventName string, nanoseconds int64) + TimingKv(eventName string, nanoseconds int64, kvs map[string]string) +} + +func DoSomething(s EventReceiver) { + fmt.Println("Doing it.", s) + + s.Event("sup") +}
5e53e3dd7de0df7b2426d14aff333f0d940e1694
--- +++ @@ -2,7 +2,6 @@ import ( "net" - "runtime" "sync/atomic" ) @@ -36,7 +35,6 @@ return } logger.Debugf("copied %d bytes from %s to %s", n, r.RemoteAddr(), w.RemoteAddr()) - runtime.Gosched() } }
ee8f3f8991405d6fda391e883d4df5340cfb264a
--- +++ @@ -6,11 +6,10 @@ Value float64 } -// MakePair evaluates the input function f at the input x and returns -// the associated (element, mass) pair. -func MakePair(f func(interface{}) float64, x interface{}) *Pair { +// NewPair creates a *Pair from the input interface and value. +func NewPair(elem interface{}, val float64) *Pair { return &Pair{ - Element: x, - Value: f(x), + Element: elem, + Value: val, } }
93c5d4600dbb6f41a739a30004876cd70b19b2a5
--- +++ @@ -7,13 +7,10 @@ "github.com/lohmander/webapi" ) -func handler(rw http.ResponseWriter, req *http.Request) { - fmt.Fprintf(rw, "Hello there") -} - func main() { api := webapi.NewAPI() api.Apply(Logger) + api.Add(`/subscriptions$`, &Subscription{}) api.Add(`/subscriptions/(?P<id>\d+)$`, &Subscription{}, Teapot) @@ -24,7 +21,7 @@ func Logger(handler webapi.Handler) webapi.Handler { return func(r *webapi.Request) (int, webapi.Response) { code, data := handler(r) - fmt.Printf("%d %s %s", code, r.Method, r.URL.Path) + fmt.Println(code, r.Method, r.URL.Path) return code, data } }
0a45903563082932864f1e746a17a8e3f9a19a89
--- +++ @@ -8,7 +8,7 @@ // Setuid sets the uid of the calling thread to the specified uid. func Setuid(uid int) (err error) { - _, _, e1 := syscall.RawSyscall(syscall.SYS_SETUID, uintptr(uid), 0, 0) + _, _, e1 := syscall.RawSyscall(syscall.SYS_SETUID32, uintptr(uid), 0, 0) if e1 != 0 { err = e1 }
351e79a723d28b1ea9dc04e2813bd2be4f5b339e
--- +++ @@ -1 +1,35 @@ package goat + +import ( + "bytes" + "net/http/httptest" + "testing" +) + +func TestWriteError(t *testing.T) { + // In + code := 500 + err := "foo" + + // Expected + json := `{ + "error": "` + err + `" +} +` + buf := bytes.NewBufferString(json) + + w := httptest.NewRecorder() + WriteError(w, code, err) + + // Test code + if w.Code != code { + t.Errorf("WriteError should set Code to %i, but did set it to %i", code, w.Code) + } + + // Test body + if w.Body == nil { + t.Errorf("WriteError should set Body to %s, but didn't", json) + } else if bytes.Equal(w.Body.Bytes(), buf.Bytes()) { + t.Errorf("WriteError should set Body to %v, but did set it to %v", buf, w.Body) + } +}
c8a502f5c1a9fae75095b776e04265bf8cc470a7
--- +++ @@ -10,7 +10,6 @@ // CreatePipe() // DeletePipeline() // DownloadCLI() - // GetConfig() // HijackContainer() // ListContainer() // ListJobInputs() @@ -21,6 +20,7 @@ Build(buildID string) (atc.Build, error) Job(pipelineName, jobName string) (atc.Job, error) JobBuild(pipelineName, jobName, buildName string) (atc.Build, error) + PipelineConfig(pipelineName string) (atc.Config, error) } type AtcHandler struct {
ab99ac551bd95e1c2c611e6af1f8a4d625497c42
--- +++ @@ -1,4 +1,8 @@ package main + +import ( + "errors" +) var CmdCurrent = &Cmd{ Name: "current", @@ -9,6 +13,11 @@ } func currentCommandFn(env Env, args []string) (err error) { + if len(args) < 2 { + err = errors.New("Missing PATH argument") + return + } + path := args[1] watches := NewFileTimes() watchString, ok := env[DIRENV_WATCHES]
aee2ec6a8097021180c3904c3201946294afe55c
--- +++ @@ -8,7 +8,7 @@ // FindCompilerLanuncher probes compiler launcher if exists. // Currently only probes SN-DBS launcher. func FindCompilerLauncher() string { - dir, ok := os.LookupEnv("SCE_SDK_ROOT") + dir, ok := os.LookupEnv("SCE_ROOT_DIR") if ok { lancherPath := filepath.Join(dir, "Common", "SN-DBS", "bin", "dbsbuild.exe") if _, err := os.Stat(lancherPath); err == nil {
9682b7065c48648a63ec1822d376f8482a38671c
--- +++ @@ -5,20 +5,20 @@ func TestDependencies(t *testing.T) { container := &Container{Run: RunParameters{RawLink: []string{"a:b", "b:d"}}} if deps := container.Dependencies(); deps[0] != "a" || deps[1] != "b" { - t.Errorf("Dependencies should have been a and b") + t.Error("Dependencies should have been a and b") } container = &Container{Run: RunParameters{RawLink: []string{}}} if deps := container.Dependencies(); len(deps) != 0 { - t.Errorf("Dependencies should have been empty") + t.Error("Dependencies should have been empty") } } func TestIsTargeted(t *testing.T) { container := &Container{RawName: "a"} if container.IsTargeted([]string{"b"}) { - t.Errorf("Container name was a, got targeted with b") + t.Error("Container name was a, got targeted with b") } if !container.IsTargeted([]string{"x", "a"}) { - t.Errorf("Container name was a, should have been targeted with a") + t.Error("Container name was a, should have been targeted with a") } }
f740ab9b8c6801e16ec3f290a62a09df51045c8f
--- +++ @@ -14,12 +14,13 @@ if pump.Error() == nil { return } + pump.SetError(nil) log.Printf("waking pump") const ( // Older pumps should have RF enabled to increase the // frequency with which they listen for wakeups. - numWakeups = 75 - xmitDelay = 35 * time.Millisecond + numWakeups = 100 + xmitDelay = 10 * time.Millisecond ) packet := commandPacket(Wakeup, nil) for i := 0; i < numWakeups; i++ {
5ae158f91cef7c6e8889f0a9697ba5b18a858cd3
--- +++ @@ -6,10 +6,11 @@ // Client is the aptomictl config representation type Client struct { - Debug bool `validate:"-"` - API API `validate:"required"` - Auth Auth `validate:"required"` - HTTP HTTP `validate:"required"` + Debug bool `validate:"-"` + Output string `validate:"required"` + API API `validate:"required"` + Auth Auth `validate:"required"` + HTTP HTTP `validate:"required"` } // HTTP is the config for low level HTTP client
0e759c1e5ea129437368e00c70562ab3e9e3bc02
--- +++ @@ -4,7 +4,7 @@ "testing" ) -func TestUncomment(t *testing.T) { +func TestTrimComment(t *testing.T) { tests := []struct { name string input string @@ -25,7 +25,7 @@ `{"url": "http://example.com"} `}, } for _, test := range tests { - actual, err := Uncomment(test.input) + actual, err := TrimComment(test.input) if err != nil { t.Fatal(err) }
ad50209dd215f6324ec49fc22036af57d8f1e15b
--- +++ @@ -1,9 +1,9 @@ package tools import ( + "fmt" "log" "strings" - "fmt" ) // UploadFile used to upload file by S3 pre-signed URL
a2b8d636f3207a7d27b2f9512c5185d269936e2d
--- +++ @@ -6,7 +6,7 @@ func TestLex(t *testing.T) { l := newLexer() - res, errs := l.Lex("a **= (7 ** (3 + 4 - 2)) << 1.23 % 0.3") + res, errs := l.Lex("some_var123 **= (7 ** (3 + 4 - 2)) << 1.23 % 0.3") expected := []tokenType{ IDENT, POW_EQ, LPAREN, INT, POW, LPAREN, INT, ADD, INT, SUB, INT, RPAREN, RPAREN, LSH, FLOAT, REM, FLOAT, EOL,
52268cfeb67eb48c79d77a539e8dc790d1a6a9bb
--- +++ @@ -11,7 +11,7 @@ ) // The main version number that is being run at the moment. -const Version = "0.12.0" +var Version = "0.12.0" // A pre-release marker for the version. If this is "" (empty string) // then it means that it is a final release. Otherwise, this is a pre-release @@ -21,7 +21,11 @@ // SemVer is an instance of version.Version. This has the secondary // benefit of verifying during tests and init time that our version is a // proper semantic version, which should always be the case. -var SemVer = version.Must(version.NewVersion(Version)) +var SemVer *version.Version + +func init() { + SemVer = version.Must(version.NewVersion(Version)) +} // Header is the header name used to send the current terraform version // in http requests.
00e788ad4469dbc25f09d8a5ac63295dd4bdde83
--- +++ @@ -11,7 +11,13 @@ // } func (e APIError) Error() string { - return fmt.Sprintf("sentry: %v", e) + if len(e) == 1 { + if detail, ok := e["detail"].(string); ok { + return fmt.Sprintf("sentry: %s", detail) + } + } + + return fmt.Sprintf("sentry: %v", map[string]interface{}(e)) } // Empty returns true if empty.
412dcc0e30ce3e137a67f445a9095ecd4bf1c190
--- +++ @@ -6,6 +6,10 @@ "syscall" "unsafe" ) + +// #include <sys/ioctl.h> +// enum { _GO_TIOCGWINSZ = TIOCGWINSZ }; +import "C" type winsize struct { ws_row, ws_col uint16 @@ -17,7 +21,7 @@ syscall.Syscall(syscall.SYS_IOCTL, uintptr(0), - uintptr(0x5413), + uintptr(C._GO_TIOCGWINSZ), uintptr(unsafe.Pointer(&ws))) return int(ws.ws_col)
824911e61202060dfa41f012546faf0601776c4c
--- +++ @@ -5,4 +5,7 @@ import () -type Account struct{} +type Account struct { + Key string + Token string +}
a0542b662899c105853eaebeef9a751ceb7af00f
--- +++ @@ -36,4 +36,10 @@ if len(actual) != len(expect) { t.Fatalf("%v does not much to expected: %v", len(actual), len(expect)) } + + for i := range expect { + if expect[i] != actual[i] { + t.Fatalf("%v does not much to expected: %v", actual, expect) + } + } }
021903d1ff70343a09e5cc8669c46a91187a68b7
--- +++ @@ -20,6 +20,10 @@ // Debug logging debug bool + + // version flags + version bool + buildVersion string ) func init() { @@ -27,6 +31,7 @@ flag.StringVar(&defaultConfig, "config", "", "default config file") flag.StringVar(&stateConfig, "state", "", "updated config which reflects the internal state") flag.BoolVar(&debug, "debug", false, "verbose logging") + flag.BoolVar(&version, "v", false, "display version") flag.Parse() } @@ -36,6 +41,11 @@ log.DefaultLogger.Level = log.DEBUG } + if version { + println(buildVersion) + return + } + loadConfig() startHTTPServer() }
e02909f004d1d83127a43dad74a5217f2445fafd
--- +++ @@ -2,6 +2,7 @@ import ( "os" + "os/exec" "path" "path/filepath" ) @@ -25,7 +26,7 @@ if err := os.MkdirAll(f.pathByParams(), 0755); err != nil { return err } - return os.Rename(from, filepath.Join(f.pathByParams(), path.Base(from))) + return exec.Command("mv", from, filepath.Join(f.pathByParams(), path.Base(from))).Run() } func (f fileStorage) pathByParams() string {
b43683f05ba1453e302ffed77c04ed124bf330d4
--- +++ @@ -1,10 +1,55 @@ package dice -import "testing" +import ( + "github.com/stretchr/testify/assert" + "testing" +) -func TestRollable(t *testing.T) { - var attackDie AttackDie - var defenseDie DefenseDie - attackDie.Roll() - defenseDie.Roll() +func TestRollable_AttackDie(t *testing.T) { + assert := assert.New(t) + + var attackDie AttackDie + var blanks, focuses, hits, crits int + attackDie.Roll() + + for i := 0; i < 1000; i++ { + switch attackDie.Result() { + case BLANK: + blanks++ + case FOCUS: + focuses++ + case HIT: + hits++ + case CRIT: + crits++ + } + } + + assert.InEpsilon(int(1000*2.0/8), blanks, 50) + assert.InEpsilon(int(1000*2.0/8), focuses, 50) + assert.InEpsilon(int(1000*3.0/8), hits, 50) + assert.InEpsilon(int(1000*1.0/8), crits, 50) } + +func TestRollable_DefenseDie(t *testing.T) { + assert := assert.New(t) + + var defenseDie DefenseDie + var blanks, focuses, evades int + defenseDie.Roll() + + for i := 0; i < 1000; i++ { + switch defenseDie.Result() { + case BLANK: + blanks++ + case FOCUS: + focuses++ + case EVADE: + evades++ + } + } + + assert.InEpsilon(int(1000*3.0/8), blanks, 50) + assert.InEpsilon(int(1000*2.0/8), focuses, 50) + assert.InEpsilon(int(1000*3.0/8), evades, 50) +}
9e5c624a5635e3b60623bbf033ebe13de6dc5733
--- +++ @@ -3,6 +3,7 @@ import ( "fmt" "http" + "mahonia.googlecode.com/hg" ) // support for running "redwood -test http://example.com" @@ -27,4 +28,39 @@ fmt.Println(s) } } + + fmt.Println() + fmt.Println("Downloading content...") + res, err := http.Get(u) + if err != nil { + fmt.Println(err) + return + } + + defer res.Body.Close() + wr := newWordReader(res.Body, mahonia.NewDecoder("UTF-8")) + ps := newPhraseScanner() + ps.scanByte(' ') + buf := make([]byte, 4096) + for { + n, err := wr.Read(buf) + if err != nil { + break + } + for i := 0; i < n; i++ { + ps.scanByte(buf[i]) + } + } + ps.scanByte(' ') + + fmt.Println() + + if len(ps.tally) == 0 { + fmt.Println("No content phrases match.") + } else { + fmt.Println("The following content phrases match:") + for rule, count := range ps.tally { + fmt.Println(rule, count) + } + } }
9fdf576f310d92d9465e8681ecec628628feb3ce
--- +++ @@ -14,11 +14,9 @@ return []byte{}, err } - data, err := ioutil.ReadAll(resp.Body) + data, _ := ioutil.ReadAll(resp.Body) defer resp.Body.Close() - if err != nil { - return []byte{}, err - } + return data, nil }
376283d9b93d7e99a61a630c42b8feb9e60bb459
--- +++ @@ -24,7 +24,8 @@ resp.Write(part) } - w.WriteHeader(http.StatusOK) + multipartWriter.Close() + w.Header().Set("Content-Type", mime.FormatMediaType("multipart/mixed", map[string]string{"boundary": multipartWriter.Boundary()})) w.WriteHeader(http.StatusOK) buf.WriteTo(w)
b02341bcf440acf5f1a8c89e14de035e8da65946
--- +++ @@ -1,13 +1,26 @@ package main import ( - "github.com/buchgr/bazelremote/cache" + "flag" + "strconv" + + "github.com/buchgr/bazel-remote/cache" ) -// TODO: Add command line flags +func main() { + port := flag.Int("port", 8080, "The port the HTTP server listens on") + dir := flag.String("dir", "", + "Directory path where to store the cache contents") + maxSize := flag.Int64("max_size", -1, + "The maximum size of the remote cache in bytes") + flag.Parse() -func main() { + if *maxSize <= 0 { + flag.Usage() + return + } + e := cache.NewEnsureSpacer(0.8, 0.5) - h := cache.NewHTTPCache(":8080", "/Users/buchgr/cache", 10*1024*1024, e) + h := cache.NewHTTPCache(":"+strconv.Itoa(*port), *dir, *maxSize, e) h.Serve() }