_id stringlengths 40 40 | text stringlengths 81 2.19k | title stringclasses 1
value |
|---|---|---|
f9f47a8418140a0477c82c4ea9ffb0366b6815a6 | ---
+++
@@ -25,7 +25,7 @@
}
func (p rProjects) HasDirectory(projectID, dirID string) bool {
- rql := model.ProjectDirs.T().GetAllByIndex("directory_id", dirID)
+ rql := model.ProjectDirs.T().GetAllByIndex("datadir_id", dirID)
var proj2dir []schema.Project2DataDir
if err := model.ProjectDirs.Qs(p.session).Rows(rql, &proj2dir); err != nil {
return false | |
ea03b4335528cf741b29df1403680f11e56722b1 | ---
+++
@@ -16,7 +16,7 @@
cmd := exec.Command("git", "checkout", args[0])
var out bytes.Buffer
- cmd.Stdout = &out
+ cmd.Stderr = &out
err := cmd.Run()
if err != nil {
fmt.Fprintf(os.Stderr, err.Error()) | |
e2e1ab814c27496d1847ab8c0dad3a06f149ffbc | ---
+++
@@ -15,7 +15,7 @@
if err != nil {
t.Fatal(err)
}
- defer r.Stop()
+ defer r.Stop() // Make sure recorder is stopped once done with it
// Create an HTTP client and inject our transport
client := &http.Client{ | |
189a27608be511bc0680e4a055e8379b52934461 | ---
+++
@@ -16,7 +16,7 @@
} else {
runner.Stdout = os.Stdout
runner.Stderr = os.Stderr
- runner.Start()
+ runner.Wait()
}
return string(output[:]) | |
e5bc99a99d55d43985c9d51e114bae665b176de7 | ---
+++
@@ -1,12 +1,62 @@
+// Package types provides types for the custom JSON configuration and the
+// custom JSON read, watch and book JSON file.
package types
-//type Config map[string][]map[string]string
+import (
+ "os"
+ "fmt"
+ "encoding/json"
+)
+
+// A single record of the configuration file.
type ConfigRecord map[string]string
+
+// A whole configuration file.
type Config map[string]ConfigRecord
+// A single base record of the read, watch or book JSON file.
type BaseRecord struct {
Title string
Link string
}
+// A whole read, watch or book JSON file.
type RecordList []BaseRecord
+
+// Read opens and read a given JSON file into the RecordList.
+// It returns nil on success and the error on failure (propagates the error).
+func (list *RecordList) Read(file string) error {
+ // open JSON file
+ readFile, err := os.Open(file)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Error while opening %s\n", file)
+ return err
+ }
+
+ // decode JSON file
+ jsonParser := json.NewDecoder(readFile)
+ if err = jsonParser.Decode(&list); err != nil {
+ fmt.Fprintf(os.Stderr, "Error while parsing %s\n", file)
+ readFile.Close()
+ return err
+ }
+
+ readFile.Close()
+ return nil
+}
+
+// Write opens and writes the RecordList to a given JSON file.
+// It returns nil on success and the error on failure (propagates the error).
+func (list *RecordList) Write(file string) error {
+ // write back to JSON file
+ readFile, err := os.Create(file)
+ jsonWriter := json.NewEncoder(readFile)
+ if err = jsonWriter.Encode(&list); err != nil {
+ fmt.Fprintf(os.Stderr, "Error while writing back %s\n", file)
+ readFile.Close()
+ return err
+ }
+
+ readFile.Close()
+ return nil
+} | |
97070aceb9df2dfc4a987290d1d9340df3fe31bf | ---
+++
@@ -1,9 +1,14 @@
package turnservicecli
+
+import (
+ "time"
+)
// CredentialsResponse defines a REST response containing TURN data.
type CredentialsResponse struct {
Success bool `json:"success"`
Nonce string `json:"nonce"`
+ Expires *time.Time `json:"expires,omitempty"`
Turn *CredentialsData `json:"turn"`
Session string `json:"session,omitempty"`
} | |
ffa15356101da9e453bd5bbe85421684648841a2 | ---
+++
@@ -8,7 +8,7 @@
)
func parsePrivateKey(data []byte) (*rsa.PrivateKey, error) {
- pemData, err := pemParse(data, "PRIVATE KEY")
+ pemData, err := pemParse(data, "RSA PRIVATE KEY")
if err != nil {
return nil, err
} | |
faaef83954e9564a9ec054c464a59e041c8c2b3d | ---
+++
@@ -17,10 +17,11 @@
i++
out += fmt.Sprint(i)
})
- time.Sleep(interval * 8)
+ // wait little more because of concurrency
+ time.Sleep(interval * 9)
stopChan <- struct{}{}
- if expected != out {
- t.Fatalf("Expected %v, found %v", expected, out)
+ if !strings.HasPrefix(out, expected) {
+ t.Fatalf("Expected to have prefix %v, found %v", expected, out)
}
out = ""
i = 0 | |
efa3f7929d27a919286246551cb146506e734d13 | ---
+++
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-// +build plan9
+// +build plan9 windows
package rand
| |
33f9460667d9fde7c765459e4d003f0326793bc3 | ---
+++
@@ -3,21 +3,18 @@
import (
"fmt"
"os"
-
- "github.com/Symantec/Dominator/lib/srpc"
)
func showImageSubcommand(args []string) {
- imageSClient, _ := getClients()
- if err := showImage(imageSClient, args[0]); err != nil {
+ if err := showImage(args[0]); err != nil {
fmt.Fprintf(os.Stderr, "Error showing image\t%s\n", err)
os.Exit(1)
}
os.Exit(0)
}
-func showImage(client *srpc.Client, image string) error {
- fs, err := getFsOfImage(client, image)
+func showImage(image string) error {
+ fs, err := getTypedImage(image)
if err != nil {
return err
} | |
ca4cbeca56eeff402465984327e61c0d1fd9a723 | ---
+++
@@ -6,9 +6,18 @@
"time"
)
-var LedgerRecordSelect sq.SelectBuilder = sq.
- Select("hl.*").
- From("history_ledgers hl")
+var LedgerRecordSelect sq.SelectBuilder = sq.Select(
+ "hl.id",
+ "hl.sequence",
+ "hl.importer_version",
+ "hl.ledger_hash",
+ "hl.previous_ledger_hash",
+ "hl.transaction_count",
+ "hl.operation_count",
+ "hl.closed_at",
+ "hl.created_at",
+ "hl.updated_at",
+).From("history_ledgers hl")
type LedgerRecord struct {
HistoryRecord | |
b5b9899f87181ceca7d7b3cb6663c33bc22ed8b6 | ---
+++
@@ -7,6 +7,7 @@
"os/signal"
"sync"
"syscall"
+ "time"
)
var listenerChan = make(chan net.Listener)
@@ -35,6 +36,11 @@
if *pidfile != "" {
os.Remove(*pidfile)
}
+ go func() {
+ // Stop after 24 hours even if the connections aren't closed.
+ time.Sleep(24 * time.Hour)
+ os.Exit(0)
+ }()
activeConnections.Wait()
os.Exit(0)
} | |
e3b45696e080e7f51f1fcf0e0881200e83a256fd | ---
+++
@@ -28,4 +28,8 @@
if err == nil {
dbsettings.Password = string(sqlInfoContents)
}
+ secretKey, err := ioutil.ReadFile("../secretkey")
+ if err == nil {
+ SecretKey = secretKey
+ }
} | |
4a0da1a38f4a6e698de2e443003cc04da69839c6 | ---
+++
@@ -20,5 +20,8 @@
// Button sends the button-press to the pump.
func (pump *Pump) Button(b PumpButton) {
+ n := pump.Retries()
+ defer pump.SetRetries(n)
+ pump.SetRetries(1)
pump.Execute(button, byte(b))
} | |
904296f68512d2055ae9fe79d2c1f2cddec645b7 | ---
+++
@@ -6,18 +6,25 @@
links []*node
}
-func newNode() *node {
- return &node{links: make([]*node, 0)}
+func newNode(val rune, isEnd bool) *node {
+ return &node{
+ val: val,
+ end: isEnd,
+ links: make([]*node, 0),
+ }
}
func (n *node) add(rs []rune) {
cur := n
- for _, v := range rs {
+ for k, v := range rs {
+ isEnd := k == len(rs)-1
+
link := cur.linkByVal(v)
if link == nil {
- link = newNode()
+ link = newNode(v, isEnd)
cur.links = append(cur.links, link)
}
+
cur = link
}
} | |
38c5b09efa1a2d74b62c921b545601f1d5009496 | ---
+++
@@ -1,6 +1,7 @@
package passhash
import (
+ "context"
"testing"
)
@@ -8,6 +9,14 @@
store := DummyCredentialStore{}
credential := &Credential{}
if err := store.Store(credential); err != nil {
+ t.Error("Got error storing credential.", err)
+ }
+}
+
+func TestDummyCredentialStoreStoreContext(t *testing.T) {
+ store := DummyCredentialStore{}
+ credential := &Credential{}
+ if err := store.StoreContext(context.Background(), credential); err != nil {
t.Error("Got error storing credential.", err)
}
}
@@ -23,3 +32,15 @@
t.Error("DummyCredentialStore provided credential.", credential)
}
}
+
+func TestDummyCredentialStoreLoadContext(t *testing.T) {
+ store := DummyCredentialStore{}
+ userID := UserID(0)
+ credential, err := store.LoadContext(context.Background(), userID)
+ if err == nil {
+ t.Error("Got error loading credential.", err)
+ }
+ if credential != nil {
+ t.Error("DummyCredentialStore provided credential.", credential)
+ }
+} | |
097bd9f0b1cd3cae779ed277efce5911359cc49a | ---
+++
@@ -50,3 +50,18 @@
return c
}
+
+// List type represents a slice of strings
+type List []string
+
+// Contains returns a boolean indicating whether the list
+// contains the given string.
+func (l List) Contains(x string) bool {
+ for _, v := range l {
+ if v == x {
+ return true
+ }
+ }
+
+ return false
+} | |
a2f3c88e6c93db375f881d18bbc8ae45e1c36883 | ---
+++
@@ -30,20 +30,17 @@
}
func Decoding(s string) string {
- runes := []rune(s)
-
var out string
cnt := 0
- for i := 0; i < len(runes); i++ {
- if unicode.IsDigit(runes[i]) {
- cnt = cnt*10 + int(runes[i]-'0')
+ for _, r := range s {
+ if unicode.IsDigit(r) {
+ cnt = cnt*10 + int(r-'0')
} else {
- out += strings.Repeat(string(runes[i]), cnt)
+ out += strings.Repeat(string(r), cnt)
cnt = 0
}
-
}
return out | |
e3803f94b09f41e361bb67ad12d9b68d9806385a | ---
+++
@@ -11,7 +11,7 @@
func getNodeRoles(commaSepRoles string) ([]string, error) {
roles := strings.Split(commaSepRoles, ",")
for _, r := range roles {
- if r != "etcd" && r != "master" && r != "worker" && r != "ingress" {
+ if r != "etcd" && r != "master" && r != "worker" && r != "ingress" && r != "storage" {
return nil, fmt.Errorf("%s is not a valid node role", r)
}
} | |
67719d691d596688fc606d189469ecece5e5e690 | ---
+++
@@ -15,6 +15,11 @@
appName := c.MustGet(api.AppName).(string)
routePath := path.Clean(c.MustGet(api.Path).(string))
+ if _, err := s.Datastore.GetRoute(ctx, appName, routePath); err != nil {
+ handleErrorResponse(c, err)
+ return
+ }
+
if err := s.Datastore.RemoveRoute(ctx, appName, routePath); err != nil {
handleErrorResponse(c, err)
return | |
80b71c1d4e233f7ea3055399f63169f447038ebf | ---
+++
@@ -43,7 +43,7 @@
}
if u != uuid {
- t.Errorf("%s != %s after Unmarshal and Marshal")
+ t.Errorf("%s != %s after Unmarshal and Marshal", u, uuid)
}
}
| |
670a45ef99fbbd3e56453892460cdef4f2df5880 | ---
+++
@@ -1,20 +1,12 @@
package main
import (
- "fmt"
"os"
"github.com/bradleyfalzon/revgrep"
)
func main() {
- fmt.Println("Starting...")
-
// Get lines changes
revgrep.Changes(nil, os.Stdin, os.Stderr)
-
- // Open stdin and scan
-
- // Check if line was affected
-
} | |
e4ff0b87427e768173ebd06f1647e8b96293d60d | ---
+++
@@ -6,7 +6,6 @@
)
type ExponentialBackoff struct {
- RandomizationFactor float64
Retries int
MaxRetries int
Delay time.Duration
@@ -15,7 +14,6 @@
func Exponential() *ExponentialBackoff {
return &ExponentialBackoff{
- RandomizationFactor: 0.5,
Retries: 0,
MaxRetries: 5,
Delay: time.Duration(0), | |
31527148797c6ba4910c8a9117172adac6d7581a | ---
+++
@@ -1,6 +1,9 @@
package kitsu
-import "testing"
+import (
+ "net/url"
+ "testing"
+)
func TestNewClient(t *testing.T) {
c := NewClient(nil)
@@ -10,23 +13,26 @@
}
}
-func TestNewRequest(t *testing.T) {
+func TestClient_NewRequest(t *testing.T) {
c := NewClient(nil)
inURL, outURL := "/foo", defaultBaseURL+"foo"
req, _ := c.NewRequest("GET", inURL, nil)
- // Test that the base URL is added to the endpoint.
+ // Test that the client's base URL is added to the endpoint.
if got, want := req.URL.String(), outURL; got != want {
t.Errorf("NewRequest(%q) URL is %q, want %q", inURL, got, want)
}
}
-func TestClient_NewRequest_badEndpoint(t *testing.T) {
+func TestClient_NewRequest_badURL(t *testing.T) {
c := NewClient(nil)
- inURL := "%foo"
+ inURL := ":"
_, err := c.NewRequest("GET", inURL, nil)
if err == nil {
t.Errorf("NewRequest(%q) should return parse err", inURL)
}
+ if err, ok := err.(*url.Error); !ok || err.Op != "parse" {
+ t.Errorf("Expected URL parse error, got %+v", err)
+ }
} | |
41c77d92452c138c4aec8fe3190431aa6b525659 | ---
+++
@@ -13,6 +13,9 @@
if files, err := ioutil.ReadDir(a_path); err == nil {
for _, file := range files {
if file.IsDir() {
+ a_fileMsgs <- FileMsg{a_path, file.Name(), CREATED}
+ a_events <- Event{DEBUG, fmt.Sprintf("Found dir %s",
+ path.Join(a_path, file.Name())), nil}
ScanDir(path.Join(a_path, file.Name()), a_fileMsgs, a_events)
} else {
a_fileMsgs <- FileMsg{a_path, file.Name(), CREATED} | |
4912d9036a1b970b5bc6ceb0298e4b7307004b27 | ---
+++
@@ -5,9 +5,11 @@
"bytes"
"strings"
"testing"
+
+ "github.com/stretchr/testify/assert"
)
-func TestHandleServerError(t *testing.T) {
+func TestServerError(t *testing.T) {
errorMessage := "test fake"
response := bytes.NewReader([]byte("SERVER_ERROR " + errorMessage))
request := bytes.NewBuffer([]byte{})
@@ -24,3 +26,33 @@
t.Fatalf("set(foo): Error = %v, want ServerError: test fake", err)
}
+
+func TestClientError(t *testing.T) {
+ errorMessage := "test fake"
+ response := bytes.NewReader([]byte("CLIENT_ERROR " + errorMessage))
+ request := bytes.NewBuffer([]byte{})
+
+ serverReadWriter := bufio.NewReadWriter(bufio.NewReader(response), bufio.NewWriter(request))
+
+ c := &Client{rw: serverReadWriter}
+
+ err := c.Set("foo", []byte("bar"))
+ e, ok := err.(ClientError)
+ if ok && strings.Contains(e.Error(), "client error: "+errorMessage) {
+ return
+ }
+
+ t.Fatalf("set(foo): Error = %v, want ClientError: test fake", err)
+}
+
+func TestReplyError(t *testing.T) {
+ response := bytes.NewReader([]byte("ERROR"))
+ request := bytes.NewBuffer([]byte{})
+
+ serverReadWriter := bufio.NewReadWriter(bufio.NewReader(response), bufio.NewWriter(request))
+
+ c := &Client{rw: serverReadWriter}
+
+ err := c.Set("foo", []byte("bar"))
+ assert.Equal(t, err, ErrReplyError)
+} | |
db1755682e45ea70489a382139721b19c25f6274 | ---
+++
@@ -10,9 +10,10 @@
return Resource{
AwsType: "AWS::EC2::InternetGateway",
- // Name
+ // Name -- not sure about this. Docs say Name, but my testing we can Ref
+ // this into an InternetGatewayId property successfully.
ReturnValue: Schema{
- Type: ValueString,
+ Type: InternetGatewayID,
},
Properties: Properties{ | |
3d24c0529c8fdb5abebaade72859f7dc0e903262 | ---
+++
@@ -31,7 +31,7 @@
break
}
switch string(buf[:3]) {
- case "inf":
+ case "nfo":
conn.Write([]byte(INFO))
case "frm":
for completed := 0; completed < TotalVoxels * 3; {
@@ -47,8 +47,6 @@
}
case "swp":
SwapDisplayBuffer()
- default:
- conn.Write([]byte("err\n"))
}
}
} | |
1bc31ba8bdc52281d7945a34f579ec7fd53640f5 | ---
+++
@@ -8,7 +8,7 @@
func BenchmarkNormal(b *testing.B) {
for i := 0; i < b.N; i++ {
- command := "hjkl"
+ command := strings.Repeat("hjkl", 100)
ed := normal{
streamSet: streamSet{in: NewReaderContext(context.TODO(), strings.NewReader(command))},
editor: newEditor(), | |
346a898ba89a7450ef30c08910db8756111a9fcc | ---
+++
@@ -6,7 +6,7 @@
// VersionMajor is for an API incompatible changes
VersionMajor = 0
// VersionMinor is for functionality in a backwards-compatible manner
- VersionMinor = 2
+ VersionMinor = 2
// VersionPatch is for backwards-compatible bug fixes
VersionPatch = 0
) | |
3b690f5544505c0d20caa85be5fc1247b3561650 | ---
+++
@@ -1,9 +1,10 @@
package config
import (
+ "reflect"
+ "testing"
+
"github.com/lifesum/configsum/pkg/errors"
-
- "testing"
)
func TestLocationInvalidLocale(t *testing.T) {
@@ -32,4 +33,15 @@
if err != nil {
t.Fatal(err)
}
+
+ have := u
+ want := userInfo{
+ Age: 27,
+ Registered: "2017-12-04T23:11:38Z",
+ Subscription: 2,
+ }
+
+ if !reflect.DeepEqual(have, want) {
+ t.Errorf("have %v, want %v", have, want)
+ }
} | |
1b80d9bec952c3231479cc7ff3fc80a3ea30addb | ---
+++
@@ -21,8 +21,3 @@
fmt.Print("Puddle> ")
}
}
-
-// RunCLI Prints to CLI
-func PrintCLI(text string) {
- fmt.Print("Puddle> ")
-} | |
184afbb9d4f2505218f5094575a5d40a706857d2 | ---
+++
@@ -51,7 +51,7 @@
}
func doAll(c *cli.Context) {
- hn := make(chan []string)
+ hn := make(chan loader.ResultData)
go loader.GetHNFeed(hn)
phres := <- hn
fmt.Printf("%s",phres) | |
6940bd44abef845b0af9b8c9916799cf3d8450d0 | ---
+++
@@ -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. | |
08d8c25446fcd2d3f1098519200921aa7a2db042 | ---
+++
@@ -13,6 +13,7 @@
Type string
Extended map[string]string
Description string
+ Value string
}
func Read(reader io.Reader) ([]*Message, error) {
@@ -22,7 +23,7 @@
}
messages := []*Message{}
- for key := range data {
+ for key, value := range data {
if key[0] == '@' {
continue
}
@@ -43,6 +44,7 @@
Type: vv["type"].(string),
Description: vv["description"].(string),
Extended: extended,
+ Value: value,
})
}
| |
57a0d8eaffc364164a7dd1392ddf82055aa10125 | ---
+++
@@ -1,7 +1,6 @@
package main
import (
- "errors"
"reflect"
"testing"
)
@@ -20,12 +19,12 @@
{
desc: "unknown provider",
name: "not-supported",
- err: errors.New("unknown provider"),
+ err: ErrUnknownProvider,
},
{
desc: "empty provider",
name: "",
- err: errors.New("unknown provider"),
+ err: ErrUnknownProvider,
},
}
| |
641a383de83ab026f6c14a51bb1185fbbe32e661 | ---
+++
@@ -14,9 +14,9 @@
Track: "ruby",
Slug: "bob",
Files: map[string]string{
- "bob_test.rb": "Tests text",
- "README.md": "Readme text",
- "/path/to/file.rb": "File text",
+ "bob_test.rb": "Tests text",
+ "README.md": "Readme text",
+ "path/to/file.rb": "File text",
},
}
| |
3314043096c6a1d72f4484e8a98e6d0f039b3562 | ---
+++
@@ -2,26 +2,11 @@
import (
"encoding/json"
- "log"
"net/http"
- "time"
"github.com/go-martini/martini"
+ "github.com/supu-io/messages"
)
-
-// CreateIssueType ...
-type CreateIssueType struct {
- Title string `json:"title"`
- Body string `json:"body"`
- Org string `json:"owner"`
- Repo string `json:"repo"`
-}
-
-// CreateIssueMsg ...
-type CreateIssueMsg struct {
- Issue CreateIssueType `json:"issue"`
- *Config `json:"config"`
-}
// CreateAttr json to create an issue
type CreateAttr struct {
@@ -31,39 +16,25 @@
Repo string `json:"repo"`
}
-func (i *CreateIssueMsg) toJSON() []byte {
- json, err := json.Marshal(i)
- if err != nil {
- log.Println(err)
- }
- return json
-
-}
-
// CreateIssue is the POST /issue/:issue and updates an Issue status
func CreateIssue(r *http.Request, params martini.Params) string {
var t CreateAttr
-
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&t)
+
if err != nil {
- return "{\"error\":\"" + err.Error() + "\"}"
+ return GenerateErrorMessage(err)
}
- msg := CreateIssueMsg{
- Issue: CreateIssueType{
+ msg := messages.CreateIssue{
+ Issue: &messages.Issue{
Title: t.Title,
Body: t.Body,
Repo: t.Repo,
Org: t.Org,
},
- Config: getConfig(),
+ Config: config(),
}
- issue, err := nc.Request("issues.create", msg.toJSON(), 10000*time.Millisecond)
- if err != nil {
- return "{\"error\":\"" + err.Error() + "\"}"
- }
-
- return string(issue.Data)
+ return Request("issues.create", msg)
} | |
0431f75e27d08749ab94e7487201d36491ae7aff | ---
+++
@@ -2,6 +2,7 @@
import (
"flag"
+ "fmt"
"log"
"net/http"
"strconv"
@@ -16,8 +17,9 @@
func main() {
flag.Parse()
+ url := fmt.Sprintf("http://localhost:%d/v1/mainnet/", *port)
+ log.Printf("RTWire service running at %s.", url)
+
addr := ":" + strconv.Itoa(*port)
-
- log.Printf("Mock RTWire service running on port %d.", *port)
log.Fatal(http.ListenAndServe(addr, service.New()))
} | |
82ead6bcf1ec5b072370f4ebf2d586a5ec511908 | ---
+++
@@ -16,7 +16,11 @@
"://tracker.istole.it:80",
"://tracker.ccc.de:80",
"://bt2.careland.com.cn:6969",
- "://announce.torrentsmd.com:8080"}
+ "://announce.torrentsmd.com:8080",
+ "://open.demonii.com:1337",
+ "://tracker.btcake.com",
+ "://tracker.prq.to",
+ "://bt.rghost.net"}
var numGood int
for _, t := range trackers { | |
7a6716f4ed3bb908d58443e7d9c5b24c648a5ab4 | ---
+++
@@ -10,12 +10,19 @@
"os/exec"
)
-func RunOrDie(arg0 string, args ...string) {
+// Run runs a command with stdin, stdout and stderr.
+func Run(arg0 string, args ...string) error {
cmd := exec.Command(arg0, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
- if err := cmd.Run(); err != nil {
+ return cmd.Run()
+}
+
+// RunOrDie runs a commands with stdin, stdout and stderr. If there is a an
+// error, it is fatally logged.
+func RunOrDie(arg0 string, args ...string) {
+ if err := Run(arg0, args...); err != nil {
log.Fatal(err)
}
} | |
635dfa6a30f9227809296d528839dbca10a36b19 | ---
+++
@@ -2,7 +2,6 @@
import (
"fmt"
- "log"
"os"
"os/exec"
"path/filepath"
@@ -18,16 +17,17 @@
func main() {
checkDir, err := os.Getwd()
if err != nil {
- log.Fatal(err)
+ fmt.Println("Error getting working directory:", err)
+ os.Exit(1)
}
for {
- //fmt.Println("Checking:", checkDir)
if existsAtPath(checkDir) {
- //fmt.Println("FOUND IT in", checkDir)
os.Exit(runAt(checkDir))
+ } else if checkDir == "/" {
+ fmt.Println("Unable to find", FILE)
+ os.Exit(1)
} else {
newdir := filepath.Dir(checkDir)
- //fmt.Println("Moving to:", newdir)
checkDir = newdir
}
}
@@ -40,7 +40,7 @@
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
- fmt.Printf("exit with errr %v\n", err)
+ fmt.Println(PROG, "exited with error", err)
return 1
} else {
return 0
@@ -52,6 +52,5 @@
if _, err := os.Stat(path); os.IsNotExist(err) {
return false
}
- //fmt.Println("found:", path)
return true
} | |
181822dd2b2187367f11cbcaf16c261fc16f4849 | ---
+++
@@ -13,8 +13,8 @@
func init() {
// HACK: This code registers routes at root on default mux... That's not very nice.
- http.Handle("/table-of-contents.js", httputil.FileHandler{gopherjs_http.Package("github.com/shurcooL/frontend/table-of-contents")})
- http.Handle("/table-of-contents.css", httputil.FileHandler{vfsutil.File(filepath.Join(importPathToDir("github.com/shurcooL/frontend/table-of-contents"), "style.css"))})
+ http.Handle("/table-of-contents.js", httputil.FileHandler{File: gopherjs_http.Package("github.com/shurcooL/frontend/table-of-contents")})
+ http.Handle("/table-of-contents.css", httputil.FileHandler{File: vfsutil.File(filepath.Join(importPathToDir("github.com/shurcooL/frontend/table-of-contents"), "style.css"))})
}
func importPathToDir(importPath string) string { | |
fbb0d707577616c12a770c5b82d84b401832e500 | ---
+++
@@ -15,14 +15,14 @@
}
}
-func max(a, b uint32) uint32 {
+func max(a, b int) int {
if a < b {
return b
}
return a
}
-func min(a, b uint32) uint32 {
+func min(a, b int) int {
if a < b {
return a
} | |
44c830670f242705d17b89225669c2d1fe45c700 | ---
+++
@@ -11,9 +11,17 @@
cmd := exec.Command(command[0], command[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
- err := cmd.Run()
+ err := cmd.Start()
if err != nil {
- fmt.Fprintf(os.Stderr, "pew: %v\n", err)
- os.Exit(1)
+ exit(err)
+ }
+ err = cmd.Wait()
+ if err != nil {
+ exit(err)
}
}
+
+func exit(err error) {
+ fmt.Fprintf(os.Stderr, "pew: %v\n", err)
+ os.Exit(1)
+} | |
caa2d9b5bad5ccf4e3706d2f688d0d1139c4725f | ---
+++
@@ -1,7 +1,9 @@
package main
import (
+ "bufio"
"os"
+ "strings"
)
func getBenchmarkInput(filename string) (output []BenchmarkInput, err error) {
@@ -12,18 +14,25 @@
}
}()
- _ = readRawData(filename)
-
- return output, err
-}
-
-func readRawData(filename string) (output []string) {
-
fd, err := os.Open(filename)
if err != nil {
panic(err)
}
defer fd.Close()
- return output
+ for scanner := bufio.NewScanner(fd); scanner.Scan(); {
+ text := scanner.Text()
+
+ comment := strings.Index(text, "#")
+ if comment != -1 {
+ text = text[:comment]
+ }
+
+ text = strings.TrimSpace(text)
+ if text == "" {
+ continue
+ }
+ }
+
+ return output, err
} | |
6ac2d50e63133d140728b2778dacae8fccc89778 | ---
+++
@@ -7,16 +7,20 @@
"github.com/emicklei/go-restful"
)
+// databaseSessionFilter is a filter than creates new database sessions. It takes a
+// function that creates new instances of the session.
type databaseSessionFilter struct {
session func() (*r.Session, error)
}
-func (f *databaseSessionFilter) Filter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
+// Filter will create a new database session and place it in the session request attribute. When control
+// returns to the filter it will close the session.
+func (f *databaseSessionFilter) Filter(request *restful.Request, response *restful.Response, chain *restful.FilterChain) {
if session, err := f.session(); err != nil {
- resp.WriteErrorString(http.StatusInternalServerError, "Unable to connect to database")
+ response.WriteErrorString(http.StatusInternalServerError, "Unable to connect to database")
} else {
- req.SetAttribute("session", session)
- chain.ProcessFilter(req, resp)
+ request.SetAttribute("session", session)
+ chain.ProcessFilter(request, response)
session.Close()
}
} | |
29f4679907773c1119629d89f08d91f4ad0a004b | ---
+++
@@ -35,7 +35,7 @@
func newTimer(timeout duration) (t *timer) {
t = &timer{
- C: make(chan struct{}),
+ C: make(chan struct{}, 1),
}
if timeout >= 0 {
@@ -54,10 +54,7 @@
timer.id = js.Global.Call("setTimeout", func() {
timer.id = nil
-
- go func() {
- timer.C <- struct{}{}
- }()
+ timer.C <- struct{}{}
}, timeout)
}
| |
b13028a3f6da77d1e8325ab8719e9d3a703a5a03 | ---
+++
@@ -28,11 +28,11 @@
}
func (s *SpyReport) IsValid() bool {
- return s.ValidUntil > time.Now().UnixNano()/1e6
+ return s.ValidUntil > time.Now().Unix()
}
func CreateSpyReport(target *Planet, mission *Mission) *SpyReport {
- now := time.Now().UnixNano() / 1e6
+ now := time.Now().Unix()
report := &SpyReport{
Player: mission.Player,
Name: target.Name,
@@ -40,7 +40,7 @@
Position: target.Position,
ShipCount: target.ShipCount,
CreatedAt: now,
- ValidUntil: now + SPY_REPORT_VALIDITY*1000,
+ ValidUntil: now + SPY_REPORT_VALIDITY,
}
Save(report)
return report | |
a2c051de357cbc7890c931051877d753aecc055a | ---
+++
@@ -11,8 +11,8 @@
var providerConfig config.Provider
switch c.Command.Name {
case "AWS":
- validateArgs(c, 2)
- providerConfig = config.Provider{"AWS_ACCESS_KEY_ID": c.Args()[0], "AWS_SECRET_ACCESS_KEY": c.Args()[1]}
+ validateArgs(c, 3)
+ providerConfig = config.Provider{"bucket": c.Args()[0], "AWS_ACCESS_KEY_ID": c.Args()[1], "AWS_SECRET_ACCESS_KEY": c.Args()[2]}
case "encryption":
validateArgs(c, 1)
providerConfig = config.Provider{"pass": c.Args()[0]} | |
91fb95b9683221d032051bf4d0f79eb422bb232d | ---
+++
@@ -1,10 +1,21 @@
package routes
import (
+ "log"
+
"github.com/DVI-GI-2017/Jira__backend/handlers"
)
func InitRouter(r *router) {
- r.Post("/signup", handlers.RegisterUser)
- r.Post("/signin", handlers.Login)
+ const signup = "/signup"
+ err := r.Post(signup, handlers.RegisterUser)
+ if err != nil {
+ log.Panicf("can not init route '%s': %v", signup, err)
+ }
+
+ const signin = "/signin"
+ err = r.Post(signin, handlers.Login)
+ if err != nil {
+ log.Panicf("can not init route '%s': %v", signin, err)
+ }
} | |
f68cf915047c362711b71917751d1d6fb8598138 | ---
+++
@@ -9,7 +9,7 @@
"github.com/gliderlabs/logspout/router"
)
-const NumMessages = 250000
+const NumMessages = 1000000
func TestCloudWatchAdapter(t *testing.T) {
if testing.Short() { | |
2c47d6ab1b9edc503d7a4513c8e7671b897a7505 | ---
+++
@@ -1,9 +1,12 @@
package main
import (
+ "bufio"
"fmt"
"os"
+ "strings"
+ "github.com/howeyc/gopass"
"gopkg.in/ini.v1"
)
@@ -24,14 +27,31 @@
checkError(err)
}
+ reader := bufio.NewReader(os.Stdin)
+
if val, ok := os.LookupEnv("ADFS_USER"); ok {
adfsConfig.Username = val
+ } else if adfsConfig.Username == "" {
+ fmt.Printf("Username: ")
+ user, err := reader.ReadString('\n')
+ checkError(err)
+ adfsConfig.Username = strings.Trim(user, "\n")
}
if val, ok := os.LookupEnv("ADFS_PASS"); ok {
adfsConfig.Password = val
+ } else if adfsConfig.Password == "" {
+ fmt.Printf("Password: ")
+ pass, err := gopass.GetPasswd()
+ checkError(err)
+ adfsConfig.Password = string(pass[:])
}
if val, ok := os.LookupEnv("ADFS_HOST"); ok {
adfsConfig.Hostname = val
+ } else if adfsConfig.Hostname == "" {
+ fmt.Printf("Hostname: ")
+ host, err := reader.ReadString('\n')
+ checkError(err)
+ adfsConfig.Hostname = strings.Trim(host, "\n")
}
return adfsConfig | |
2d2ec43ef2e47a2645b15c99a72758d5ebe6721b | ---
+++
@@ -5,6 +5,7 @@
package main
import (
+ "fmt"
"strings"
"testing"
)
@@ -41,3 +42,12 @@
substTestCase(t, &v, "Mirror, Mirror on the Wall")
}
+
+func TestExpandPathnameTemplate(t *testing.T) {
+ fmt.Println(expandPathnameTemplate("{nil}{dir}/{name}.{ext}",
+ map[string]interface{}{
+ "nil": []string{},
+ "dir": []string{"red", "blue", "yellow", "green"},
+ "name": []string{"foo", "bar"},
+ "ext": []string{"js", "go", "rs"}}))
+} | |
0482410d9d3e8b3c113872d5f97f1d79921d84d9 | ---
+++
@@ -2,7 +2,7 @@
// Agents lists agents and their status.
func Agents(client Client, actionID string) ([]Response, error) {
- return requestList(client, "Agents", actionID, "AgentsEntry", "AgentsComplete")
+ return requestList(client, "Agents", actionID, "Agents", "AgentsComplete")
}
// AgentLogoff sets an agent as no longer logged in. | |
a7da9bcf5a3479d959364cd8b79f3e93c1673080 | ---
+++
@@ -14,7 +14,7 @@
}
func NewSession(id string, provider Provider) *Session {
- v := make(map[string]interface{}, 0)
+ v := make(map[string]interface{})
return &Session{
id: id,
Last: time.Now(), | |
3425ae831dd809140f6094813bba8ebce0c962b1 | ---
+++
@@ -3,6 +3,8 @@
import (
".."
"../queuedir"
+ "os"
+ "path/filepath"
"strings"
)
@@ -12,11 +14,14 @@
func (c *QueuesCommand) Run() {
err := gitmedia.WalkQueues(func(name string, queue *queuedir.Queue) error {
+ wd, _ := os.Getwd()
gitmedia.Print(name)
return queue.Walk(func(id string, body []byte) error {
parts := strings.Split(string(body), ":")
if len(parts) == 2 {
- gitmedia.Print(" " + parts[1])
+ absPath := filepath.Join(gitmedia.LocalWorkingDir, parts[1])
+ relPath, _ := filepath.Rel(wd, absPath)
+ gitmedia.Print(" " + relPath)
} else {
gitmedia.Print(" " + parts[0])
} | |
4cd80fc744507cc9c2eba328da5777e6f184447f | ---
+++
@@ -8,7 +8,7 @@
Pattern string `json:"pattern"`
Broker string `json:"broker"`
From string `json:"from" db:"fromName"`
- IsActive bool `json:"is_active"`
+ IsActive bool `json:"is_active" db:"isActive"`
broker Broker
regex *regexp.Regexp
} | |
c6f6094b3e7dfc3f4c72fcf264377f23305b2a1a | ---
+++
@@ -2,7 +2,7 @@
import (
"flag"
- // "fmt"
+ "fmt"
"io/ioutil"
"log"
"runtime"
@@ -10,13 +10,20 @@
func main() {
runtime.GOMAXPROCS(2)
+
+ // Flag initialization
+ var printAST, printInst bool
+ flag.BoolVar(&printAST, "ast", false, "Print abstract syntax tree structure")
+ flag.BoolVar(&printInst, "bytecode", false, "Print comprehensive bytecode instructions")
+
flag.Parse()
if flag.NArg() != 1 {
flag.Usage()
log.Fatalf("FILE: the .rb file to execute")
}
- file := flag.Arg(0)
+
+ file := flag.Args()[0]
buffer, err := ioutil.ReadFile(file)
if err != nil {
@@ -31,18 +38,28 @@
p.Execute()
- // Traverse(rootAST)
+ if printAST {
+ Traverse(rootAST)
+ }
vm := initVM()
vm.compile(rootAST)
- vm.executeBytecode()
- // fmt.Println("")
- // fmt.Println(len(vm.instList))
- // for _, v := range vm.instList {
- // fmt.Println(v)
- // fmt.Print("\t")
- // fmt.Println(v.obj)
- // }
+ if printInst {
+ printInstructions(vm.instList, true)
+ }
+
+ vm.executeBytecode(nil)
}
+
+func printInstructions(inst []Instruction, blocks bool) {
+ for _, v := range inst {
+ fmt.Println(v)
+ fmt.Print("\t")
+ fmt.Println(v.obj)
+ if v.inst_type == BC_PUTOBJ && v.obj.(*RObject).name == "RBlock" {
+ printInstructions(v.obj.(*RObject).methods["def"].def, blocks)
+ }
+ }
+} | |
58ff12f3f8fedb1227f38e0c21557ef2fb1fc7a4 | ---
+++
@@ -1,6 +1,7 @@
package logging
import (
+ stackdriver "github.com/TV4/logrus-stackdriver-formatter"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
@@ -11,6 +12,8 @@
// - include source file and line number for every event (false [default], true)
func ConfigureLogging(cfg *viper.Viper) {
switch cfg.GetString("logging.format") {
+ case "stackdriver":
+ logrus.SetFormatter(stackdriver.NewFormatter())
case "json":
logrus.SetFormatter(&logrus.JSONFormatter{})
case "text": | |
2e943e24b794d899aae3397a6a8a34ea2ee4271d | ---
+++
@@ -12,7 +12,7 @@
file, err := ioutil.ReadFile("../input.txt")
if err != nil {
fmt.Println(err)
- return
+ os.Exit(1)
}
content := string(file) | |
55960d6e0bda20d4452a1b73c48d542f84661e2f | ---
+++
@@ -1,7 +1,11 @@
package client
import (
+ "bytes"
+ "fmt"
+ "io/ioutil"
"net/http"
+ "strings"
"testing"
"golang.org/x/net/context"
@@ -16,3 +20,31 @@
t.Fatalf("expected a Server Error, got %v", err)
}
}
+
+func TestContainerExport(t *testing.T) {
+ expectedURL := "/containers/container_id/export"
+ client := &Client{
+ transport: newMockClient(nil, func(r *http.Request) (*http.Response, error) {
+ if !strings.HasPrefix(r.URL.Path, expectedURL) {
+ return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, r.URL)
+ }
+
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Body: ioutil.NopCloser(bytes.NewReader([]byte("response"))),
+ }, nil
+ }),
+ }
+ body, err := client.ContainerExport(context.Background(), "container_id")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer body.Close()
+ content, err := ioutil.ReadAll(body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(content) != "response" {
+ t.Fatalf("expected response to contain 'response', got %s", string(content))
+ }
+} | |
2129e4d7cbd99ad640258ac1809f9dc6ea7adf40 | ---
+++
@@ -2,6 +2,8 @@
import (
"errors"
+
+ "github.com/mdlayher/wavepipe/data"
)
var (
@@ -21,6 +23,9 @@
// for a transcoder
type Transcoder interface {
Codec() string
+ FFmpeg() *FFmpeg
+ MIMEType() string
+ SetSong(*data.Song)
Quality() string
}
| |
400764703c931ba79573d1e50b8c0ca5718a782b | ---
+++
@@ -36,9 +36,9 @@
context.SetCurrentUser(req, user)
chain.next()
+ } else {
+ redirectToLogin(res, req)
}
-
- redirectToLogin(res, req)
}
func redirectToLogin(res http.ResponseWriter, req *http.Request) { | |
297531c672687973facd15b3d0b8a6c839fef6ef | ---
+++
@@ -2,8 +2,8 @@
import (
"bytes"
+ "crypto/rand"
"math"
- "math/rand"
"testing"
)
@@ -20,8 +20,7 @@
_, err := rand.Read(samples)
if err != nil {
- //according to go docs, this should never ever happen
- t.Fatal("RNG Error!")
+ t.Fatal("RNG Error: ", err)
}
//make a copy, for payloader input | |
33beb7569c13d185e9603d56b2f3268ff591d0c1 | ---
+++
@@ -1 +1,49 @@
package creational
+
+import "sync"
+
+// PoolObject represents the object to be stored in the Pool.
+type PoolObject struct {
+}
+
+// Pool represents the pool of objects to use.
+type Pool struct {
+ *sync.Mutex
+ inuse []*PoolObject
+ available []*PoolObject
+}
+
+// NewPool creates a new pool.
+func NewPool() *Pool {
+ return &Pool{}
+}
+
+// Acquire acquires a new PoolObject to use from the pool.
+// Here acquire creates a new instance of a PoolObject if none available.
+func (p *Pool) Acquire() *PoolObject {
+ p.Lock()
+ var object *PoolObject = nil
+ if len(p.available) != 0 {
+ object = p.available[0]
+ p.available = append(p.available[:0], p.available[1:]...)
+ p.inuse = append(p.inuse, object)
+ } else {
+ object := &PoolObject{}
+ p.inuse = append(p.inuse, object)
+ }
+ p.Unlock()
+ return object
+}
+
+// Release releases a PoolObject back to the Pool.
+func (p *Pool) Release(object *PoolObject) {
+ p.Lock()
+ p.available = append(p.available, object)
+ for i, v := range p.inuse {
+ if v == object {
+ p.inuse = append(p.inuse[:i], p.inuse[i+1:]...)
+ break
+ }
+ }
+ p.Unlock()
+} | |
692ad988d2c678785832561ea999fa22486baba1 | ---
+++
@@ -1,8 +1,4 @@
package channels
-
-import (
- "log"
-)
type FanState struct {
Speed *float64 `json:"speed,omitempty"` // the speed of the fan as a percentage of maximum
@@ -30,6 +26,6 @@
}
func (c *FanStatChannel) SendState(fanState *FanState) error {
- log.Printf("SendState: %+v\n, %p", fanState, c.SendEvent)
+ //log.Printf("SendState: %+v\n, %p", fanState, c.SendEvent)
return c.SendEvent("state", fanState)
} | |
a558b299a1b3a9ffdbc8d9d5160ef23963a843b7 | ---
+++
@@ -10,9 +10,17 @@
t.Error("validateConfig should return an error when the modulepath hasn't been set")
}
- subject := New()
- subject.Config["modulepath"] = "stub modulepath"
- if subject.validateConfig() != nil {
- t.Error("validateConfig should return nil when the modulepath has been set")
+ subject1 := New()
+ subject1.Config["modulepath"] = "stub modulepath"
+ subject1.Config["fileurl"] = "stub fileurl"
+ if subject1.validateConfig() != nil {
+ t.Error("validateConfig should return nil when the modulepath and fileurl have been set")
}
+
+ subject2 := New()
+ subject2.Config["modulepath"] = "stub modulepath"
+ if subject2.validateConfig().Error() != "Fileurl must be set before starting the API server" {
+ t.Error("validateConfig should return an error when the fileurl hasn't been set")
+ }
+
} | |
c31fc60b8c177aacf91ae0b197ebe7484fbc6d90 | ---
+++
@@ -25,3 +25,8 @@
s := NewTopSampler(pid)
s.Probe(pid)
}
+
+func TestProbeNotExistingDoesNotPanic(t *testing.T) {
+ s := NewTopSampler(99999999999999999)
+ s.Probe(99999999999999999)
+} | |
0c1ba6f232dc2a250f68368035b5c529c8b38774 | ---
+++
@@ -4,14 +4,34 @@
"image/color"
"engo.io/ecs"
+ "engo.io/engo"
"engo.io/engo/common"
)
+
+const buttonOpenMenu = "OpenMenu"
type game struct{}
func (g *game) Type() string { return sceneGame }
func (g *game) Preload() {}
-func (g *game) Setup(*ecs.World) {
+func (g *game) Setup(world *ecs.World) {
+
+ engo.Input.RegisterButton(buttonOpenMenu, engo.Escape)
common.SetBackground(color.White)
+ world.AddSystem(&common.RenderSystem{})
+ world.AddSystem(&inputSystem{})
}
+
+type inputSystem struct{}
+
+// Update is ran every frame, with `dt` being the time
+// in seconds since the last frame
+func (is *inputSystem) Update(float32) {
+ if engo.Input.Button(buttonOpenMenu).JustPressed() {
+ engo.SetSceneByName(sceneMainMenu, true)
+ }
+}
+
+// Remove is called whenever an Entity is removed from the World, in order to remove it from this sytem as well
+func (is *inputSystem) Remove(ecs.BasicEntity) {} | |
1ae31463f5f9a24311b8a65057ffc3461abdf1bd | ---
+++
@@ -15,6 +15,8 @@
"quota-name-goes-here",
"-m", "512M",
), 5.0).Should(Exit(0))
+
+ Eventually(Cf("quota", "quota-name-goes-here"), 5.0).Should(Say("512M"))
quotaOutput := Cf("quotas")
Eventually(quotaOutput, 5).Should(Say("quota-name-goes-here")) | |
98858f51dad950dddaa665096d4952b01c89528e | ---
+++
@@ -3,6 +3,7 @@
import (
"flag"
"log"
+ "runtime"
"github.com/fimad/ggircd/irc"
)
@@ -11,6 +12,8 @@
"Path to a file containing the irc daemon's configuration.")
func main() {
+ runtime.GOMAXPROCS(runtime.NumCPU())
+
flag.Parse()
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
| |
6de3139072bc6c74cfe672d33d30b0778670eace | ---
+++
@@ -8,14 +8,14 @@
// NetworkLoadBalancerAction represents a lifecycle event action for network load balancers.
type NetworkLoadBalancerAction string
-// All supported lifecycle events for network forwards.
+// All supported lifecycle events for network load balancers.
const (
- NetworkLoadBalancerCreated = NetworkForwardAction(api.EventLifecycleNetworkLoadBalancerCreated)
- NetworkLoadBalancerDeleted = NetworkForwardAction(api.EventLifecycleNetworkLoadBalancerDeleted)
- NetworkLoadBalancerUpdated = NetworkForwardAction(api.EventLifecycleNetworkLoadBalancerUpdated)
+ NetworkLoadBalancerCreated = NetworkLoadBalancerAction(api.EventLifecycleNetworkLoadBalancerCreated)
+ NetworkLoadBalancerDeleted = NetworkLoadBalancerAction(api.EventLifecycleNetworkLoadBalancerDeleted)
+ NetworkLoadBalancerUpdated = NetworkLoadBalancerAction(api.EventLifecycleNetworkLoadBalancerUpdated)
)
-// Event creates the lifecycle event for an action on a network forward.
+// Event creates the lifecycle event for an action on a network load balancer.
func (a NetworkLoadBalancerAction) Event(n network, listenAddress string, requestor *api.EventLifecycleRequestor, ctx map[string]any) api.EventLifecycle {
u := api.NewURL().Path(version.APIVersion, "networks", n.Name(), "load-balancers", listenAddress).Project(n.Project())
return api.EventLifecycle{ | |
13fd5f07a36d333d0626764ac27f2cca3bd1cc5f | ---
+++
@@ -16,7 +16,7 @@
}
app := cli.NewApp()
- app.Name = "machine"
+ app.Name = os.Args[0]
app.Commands = Commands
app.CommandNotFound = cmdNotFound
app.Usage = "Create and manage machines running Docker." | |
f5babce21c18273d9c71a4d3b2f19d63e61005f1 | ---
+++
@@ -30,7 +30,7 @@
Description: "Status",
Options: []string{"Active", "Inactive"},
},
- Required: constraints.Always,
+ Default: "Active",
},
"UserName": Schema{ | |
b65ac55033c46ddbd453560e388ea3a9747b85c6 | ---
+++
@@ -17,9 +17,10 @@
import (
"fmt"
- "semver"
"gnd.la/template/assets"
+
+ "github.com/rainycape/semver"
)
const ( | |
38d98b5520be54d8af491557271c460cc22553c2 | ---
+++
@@ -21,6 +21,16 @@
log.Fatalf("lookup failure on %s:0:%s: %s", "zfs", "arcstats", err)
}
log.Debugf("Collected: %v", ks)
+ n, err := ks.GetNamed("hits")
+ if err != nil {
+ log.Fatalf("getting '%s' from %s: %s", "hits", ks, err)
+ }
+ log.Debugf("Hits: %v", n)
+ n, err = ks.GetNamed("misses")
+ if err != nil {
+ log.Fatalf("getting '%s' from %s: %s", "misses", ks, err)
+ }
+ log.Debugf("Misses: %v", n)
time.Sleep(10 * time.Second)
}
} | |
c78acaddfc9bb52d20a38dcddc961ea3d95a6e3f | ---
+++
@@ -29,7 +29,13 @@
os.Exit(0)
}
- cmd := exec.Command(bin, "-l"+lexer, "-f"+format, "-O encoding="+enc)
+ // Guess the lexer based on content if a specific one is not provided
+ lexerArg := "-g"
+ if lexer != "" {
+ lexerArg = "-l" + lexer
+ }
+
+ cmd := exec.Command(bin, lexerArg, "-f"+format, "-O encoding="+enc)
cmd.Stdin = strings.NewReader(code)
var out bytes.Buffer | |
026348035cb2a9cc885794f759f962d828c79c0b | ---
+++
@@ -3,6 +3,8 @@
import (
"io/ioutil"
"testing"
+
+ "github.com/vbauerster/mpb/decor"
)
func BenchmarkIncrSingleBar(b *testing.B) {
@@ -20,3 +22,11 @@
bar.Increment()
}
}
+
+func BenchmarkIncrSingleBarWithNameDecorator(b *testing.B) {
+ p := New(WithOutput(ioutil.Discard))
+ bar := p.AddBar(int64(b.N), PrependDecorators(decor.Name("test")))
+ for i := 0; i < b.N; i++ {
+ bar.Increment()
+ }
+} | |
8a55ab207daeb27609a2f4de402fdfde787d87e1 | ---
+++
@@ -9,9 +9,11 @@
// Store endpoints first since they are the most active
//e.GET("/api/store/", storeGetView)
//e.POST("/api/store/", storePostView)
- g = g.Group("/store")
- g.GET("/", storeGetView)
- g.POST("/", storePostView)
+
+ // TODO Can not register same handler for two different routes
+ //g = g.Group("/store")
+ //g.GET("/", storeGetView)
+ //g.POST("/", storePostView)
// :project_id is [\w_-]+
g = g.Group("/:project_id/store")
g.GET("/", storeGetView) | |
f756a0b3116e3d0be27ca61fb8960bfa4647360f | ---
+++
@@ -10,6 +10,9 @@
)
func isatty(w io.Writer) bool {
+ if os.Getenv("GONDOLA_FORCE_TTY") != "" {
+ return true
+ }
if ioctlReadTermios != 0 {
if f, ok := w.(*os.File); ok {
var termios syscall.Termios | |
e557bbc61fca084ebbb4d948000e2394047244b8 | ---
+++
@@ -2,8 +2,21 @@
import (
"fmt"
+ "github.com/jessevdk/go-flags"
+ "os"
)
func main() {
- fmt.Println("Hello, world!")
+ var opts struct {
+ Name string `short:"n" long:"name" description:"Name to greet" default:"world"`
+ }
+
+ parser := flags.NewParser(&opts, flags.Default)
+ parser.Usage = "[options]"
+ if _, err := parser.Parse(); err != nil {
+ fmt.Fprintln(os.Stderr, "Error parsing command line")
+ os.Exit(1)
+ }
+
+ fmt.Printf("Hello, %s!\n", opts.Name)
} | |
39a071aa01998a4efc4a36b8737909fef3f2d968 | ---
+++
@@ -33,16 +33,20 @@
if *event.Type == "PullRequestEvent" {
prEvent := github.PullRequestEvent{}
+
err = json.Unmarshal(event.GetRawPayload(), &prEvent)
if err != nil {
panic(err)
}
- fmt.Printf("%s\n", *prEvent.PullRequest.URL)
+ prAction := prEvent.GetAction()
- if *prEvent.Action == "opened" {
- MirrorPR(&prEvent) //TODO: Check if we already have an open PR for this and add a comment saying upstream reopened it
- } else if *prEvent.Action == "closed" {
+ fmt.Printf("%s\n", prEvent.PullRequest.GetURL())
+
+ if prAction == "opened" {
+ //TODO: Check if we already have an open PR for this and add a comment saying upstream reopened it and remove the upsteam closed tag
+ MirrorPR(&prEvent)
+ } else if prAction == "closed" {
//AddLabel("Upstream Closed")
}
} | |
f1e4952e73bd1951b30578baff86eed808ae478c | ---
+++
@@ -20,7 +20,7 @@
package main
-import "gitlab.gaba.co.jp/gaba-infra/go-vtm-cli/cmd"
+import "github.com/martinlindner/go-vtm-cli/cmd"
func main() {
cmd.Execute() | |
519a78936c598ccb445c7205a2889aaec7f34657 | ---
+++
@@ -15,7 +15,7 @@
message_type, err := jq.String("message_type")
if err != nil {
- log.Fatalf("Error parsing message_type", err)
+ log.Fatalf("Error parsing message_type: %v", err)
}
log.Info("Message type -> ", message_type) | |
45e069a7f553085c07c0049a9bce043577276b77 | ---
+++
@@ -23,7 +23,8 @@
runTemplateFunctionTest(t, "VarName", "one-half", "one_half")
runTemplateFunctionTest(t, "VarNameUC", "C++11", "CXX11")
- runTemplateFunctionTest(t, "VarNameUC", "cross-country", "CROSS_COUNTRY")
+ runTemplateFunctionTest(t, "VarNameUC",
+ "cross-country", "CROSS_COUNTRY")
runTemplateFunctionTest(t, "LibName", "libc++11", "libc++11")
runTemplateFunctionTest(t, "LibName", "dash-dot.", "dash-dot.") | |
5fb651ea19dce69cf0fba0cfe945cafc5cb1e76f | ---
+++
@@ -3,10 +3,10 @@
import (
"bufio"
+ "flag"
"fmt"
"os"
"time"
- "flag"
)
func readLines(c chan int) {
@@ -28,7 +28,9 @@
func main() {
var d time.Duration
+ var t bool
flag.DurationVar(&d, "i", time.Second, "Update interval")
+ flag.BoolVar(&t, "t", false, "Include timestamp")
flag.Parse()
line := 0
count := 0
@@ -40,7 +42,11 @@
select {
// print counts
case <-tick:
- fmt.Println(float64(line-count)/d.Seconds(), "/sec")
+ prnt := fmt.Sprintf("%v /sec", float64(line-count)/d.Seconds())
+ if t {
+ prnt = fmt.Sprintf("%s\t%s", prnt, time.Now().UTC().Format("Mon Jan 2 15:04:05 UTC 2006"))
+ }
+ fmt.Println(prnt)
count = line
// update counts
case line = <-c: | |
0b871e418a39c5637d235e4eb6f412aa7188bb5f | ---
+++
@@ -22,7 +22,7 @@
TRIANGLES DrawMode = gl.TRIANGLES
)
-func (d DrawMode) PrimativeCount(vertexCount int) int {
+func (d DrawMode) PrimitiveCount(vertexCount int) int {
switch d {
case POINTS:
return vertexCount | |
76a53b903b1cd44c867b5580f2a7dd34ca5f52e1 | ---
+++
@@ -14,6 +14,10 @@
h := hmac.New(sha256.New, key)
h.Write([]byte(message))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
+}
+func ComputeHmac256Html(message string, secret string) string {
+ t := ComputeHmac256(message, secret)
+ return strings.Replace(t, "/", "_", -1)
}
func Capitalize(s string) string { | |
8e8f92af1961482e5c0c2e0adb2b3f55c7274833 | ---
+++
@@ -8,8 +8,7 @@
"time"
)
-// Why 32? See https://github.com/docker/docker/pull/8035.
-const defaultTimeout = 32 * time.Second
+const defaultTimeout = 10 * time.Second
// ErrProtocolNotAvailable is returned when a given transport protocol is not provided by the operating system.
var ErrProtocolNotAvailable = errors.New("protocol not available") | |
ad053987e5f1ce62787228478dc056986fb9f248 | ---
+++
@@ -19,11 +19,13 @@
}
type HealthResponse struct {
- Initialized bool `json:"initialized"`
- Sealed bool `json:"sealed"`
- Standby bool `json:"standby"`
- ServerTimeUTC int64 `json:"server_time_utc"`
- Version string `json:"version"`
- ClusterName string `json:"cluster_name,omitempty"`
- ClusterID string `json:"cluster_id,omitempty"`
+ Initialized bool `json:"initialized"`
+ Sealed bool `json:"sealed"`
+ Standby bool `json:"standby"`
+ ReplicationPerfMode string `json:"replication_perf_mode"`
+ ReplicationDRMode string `json:"replication_dr_mode"`
+ ServerTimeUTC int64 `json:"server_time_utc"`
+ Version string `json:"version"`
+ ClusterName string `json:"cluster_name,omitempty"`
+ ClusterID string `json:"cluster_id,omitempty"`
} | |
9cdde8b89f31d4873957652273e234b3a55740db | ---
+++
@@ -2,24 +2,35 @@
// Merge Sort, O(n lg n) worst-case. Very beautiful.
func MergeSort(ns []int) []int {
+ // Base case - an empty or length 1 slice is trivially sorted.
if len(ns) < 2 {
+ // We need not allocate memory here as the at most 1 element will only be referenced
+ // once.
return ns
}
half := len(ns) / 2
+ // The wonder of merge sort - we sort each half of the slice using... merge sort :-)
+ // Where is your God now?
ns1 := MergeSort(ns[:half])
ns2 := MergeSort(ns[half:])
+ // We now have 2 separately sorted slices, merge them into one.
return Merge(ns1, ns2)
}
+// Merge, O(n), merges two sorted slices into one.
func Merge(ns1, ns2 []int) []int {
length := len(ns1) + len(ns2)
ret := make([]int, length)
i, j := 0, 0
+ // We iterate through each element of the returned slice, placing elements of each of the
+ // input slices in their appropriate places.
+ //
+ // Loop Invariant: ret[:k] consists of ns1[:i] and ns2[:j] in sorted order.
for k := 0; k < length; k++ {
switch {
case j >= len(ns2) || ns1[i] <= ns2[j]:
@@ -31,5 +42,8 @@
}
}
+ // When the loop is complete, i == len(ns1), j == len(ns2). Therefore our loop invariant
+ // determines that ret consists of ns1 and ns2 in sorted order, which matches the purpose
+ // of the function.
return ret
} | |
cee5deef1e50a7ee2107af17809b01598a7a5725 | ---
+++
@@ -7,6 +7,9 @@
{{ range .Services }}{{ .GetName }}:
{{ range $key, $value := .GetParameters }}{{ $key }}: {{ $value }}
{{ end }}
- {{ end }}
+ {{ end }}units:
+ {{ range .Units }}- name: {{ .GetName }}
+ command: {{ .GetCommand }}
+ {{ end }}
`
} | |
8a235f0a643c8ebe98a3a85b11aae73e8517ea07 | ---
+++
@@ -2,4 +2,8 @@
package etc
+// for default icon
//go:generate cmd /c go run mkversioninfo.go version.txt version.txt < versioninfo.json > v.json && go run github.com/josephspurrier/goversioninfo/cmd/goversioninfo -icon=nyagos.ico -o ..\nyagos.syso v.json && del v.json
+
+// for second icon (disabled)
+////go:generate cmd /c go run mkversioninfo.go version.txt version.txt < versioninfo.json > v.json && go run github.com/josephspurrier/goversioninfo/cmd/goversioninfo -icon=nyagos32x32.ico -icon=nyagos16x16.ico -o ..\nyagos.syso v.json && del v.json | |
131b04445d5539c6ec67e611792118758aaee414 | ---
+++
@@ -43,5 +43,8 @@
r := gin.Default()
web.RegisterRoutes(r)
- r.Run() // listen and serve on 0.0.0.0:8080
+ err = r.Run() // listen and serve on 0.0.0.0:8080
+ if err != nil {
+ logging.Error("Error running web service", err)
+ }
} | |
a4a50f8a69a72689b1700e4a1f9031e8ed9dab3d | ---
+++
@@ -23,11 +23,10 @@
}
for name, ok := range testCases {
- testName := fmt.Sprintf("%s is %s", name, acceptability(ok))
- t.Run(testName, func(t *testing.T) {
+ t.Run(name, func(t *testing.T) {
acceptable, err := track.AcceptFilename(name)
assert.NoError(t, err, name)
- assert.Equal(t, ok, acceptable, testName)
+ assert.Equal(t, ok, acceptable, fmt.Sprintf("%s is %s", name, acceptability(ok)))
})
}
} | |
17187685fba4907d90cd545015cff21b8483732a | ---
+++
@@ -1 +1,13 @@
package lexer
+
+type Lexer struct {
+ input string
+ position int // current position in input (points to current char)
+ readPosition int // current reading position in input (after current char)
+ ch byte // current char being looked at
+}
+
+func New(input string) *Lexer {
+ l := &Lexer{ input: input }
+ return l
+} | |
457c1eda5f6025f80e8dda547ade623e11be30b3 | ---
+++
@@ -8,11 +8,13 @@
src string
dst string
}{
+ //Full URI
{
"https://github.com/sunaku/vim-unbundle",
"https://github.com/sunaku/vim-unbundle",
},
+ //Short GitHub URI
{
"Shougo/neobundle.vim",
"https://github.com/Shougo/neobundle.vim", | |
dc23141dcf5bba4fab44b1f3748d3437d4bd4ece | ---
+++
@@ -12,7 +12,11 @@
)
// EnvFullName returns a string based on the provided environment
-// that is suitable for identifying the env on a provider.
+// that is suitable for identifying the env on a provider. The resuling
+// string clearly associates the value with juju, whereas the
+// environment's UUID alone isn't very distinctive for humans. This
+// benefits users by helping them quickly identify in their hosting
+// management tools which instances are juju related.
func EnvFullName(env environs.Environ) string {
envUUID, _ := env.Config().UUID() // Env should have validated this.
return fmt.Sprintf("juju-%s", envUUID)
@@ -20,7 +24,8 @@
// MachineFullName returns a string based on the provided environment
// and machine ID that is suitable for identifying instances on a
-// provider.
+// provider. See EnvFullName for an explanation on how this function
+// helps juju users.
func MachineFullName(env environs.Environ, machineId string) string {
envstr := EnvFullName(env)
machineTag := names.NewMachineTag(machineId) | |
ed3efb14fd5eee4a768419ae847ba39dbe6fac79 | ---
+++
@@ -15,10 +15,10 @@
func initLogger(slog bool) {
if slog {
- l, err := syslog.NewLogger(syslog.LOG_INFO, 0)
+ lw, err := syslog.New(syslog.LOG_INFO, "cbfs")
if err != nil {
corelog.Fatalf("Can't initialize logger: %v", err)
}
- log = l
+ log = corelog.New(lw, "", 0)
}
} |
Subsets and Splits
Match Query to Corpus Titles
Matches queries with corpus entries based on their row numbers, providing a simple pairing of text data without revealing deeper insights or patterns.