repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1 value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
etcd-io/gofail | code/binding.go | Write | func (b *Binding) Write(dst io.Writer) error {
hdr := "// GENERATED BY GOFAIL. DO NOT EDIT.\n\n" +
"package " + b.pkg +
"\n\nimport \"github.com/etcd-io/gofail/runtime\"\n\n"
if _, err := fmt.Fprint(dst, hdr); err != nil {
return err
}
for _, fp := range b.fps {
_, err := fmt.Fprintf(
dst,
"var %s *runtime.Failpoint = runtime.NewFailpoint(%q, %q)\n",
fp.Runtime(),
b.fppath,
fp.Name())
if err != nil {
return err
}
}
return nil
} | go | func (b *Binding) Write(dst io.Writer) error {
hdr := "// GENERATED BY GOFAIL. DO NOT EDIT.\n\n" +
"package " + b.pkg +
"\n\nimport \"github.com/etcd-io/gofail/runtime\"\n\n"
if _, err := fmt.Fprint(dst, hdr); err != nil {
return err
}
for _, fp := range b.fps {
_, err := fmt.Fprintf(
dst,
"var %s *runtime.Failpoint = runtime.NewFailpoint(%q, %q)\n",
fp.Runtime(),
b.fppath,
fp.Name())
if err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"b",
"*",
"Binding",
")",
"Write",
"(",
"dst",
"io",
".",
"Writer",
")",
"error",
"{",
"hdr",
":=",
"\"",
"\\n",
"\\n",
"\"",
"+",
"\"",
"\"",
"+",
"b",
".",
"pkg",
"+",
"\"",
"\\n",
"\\n",
"\\\"",
"\\\"",
"\\n",
"\\n",
"\"",
"\n",
"if",
"_",
",",
"err",
":=",
"fmt",
".",
"Fprint",
"(",
"dst",
",",
"hdr",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"fp",
":=",
"range",
"b",
".",
"fps",
"{",
"_",
",",
"err",
":=",
"fmt",
".",
"Fprintf",
"(",
"dst",
",",
"\"",
"\\n",
"\"",
",",
"fp",
".",
"Runtime",
"(",
")",
",",
"b",
".",
"fppath",
",",
"fp",
".",
"Name",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Write writes the fp.generated.go file for a package. | [
"Write",
"writes",
"the",
"fp",
".",
"generated",
".",
"go",
"file",
"for",
"a",
"package",
"."
] | 51ce9a71510a58bad5ae66ddd278ef28762a1550 | https://github.com/etcd-io/gofail/blob/51ce9a71510a58bad5ae66ddd278ef28762a1550/code/binding.go#L33-L52 | train |
rjeczalik/notify | watcher_fen.go | Init | func (f *fen) Init() (err error) {
f.p, err = f.cf.portCreate()
return
} | go | func (f *fen) Init() (err error) {
f.p, err = f.cf.portCreate()
return
} | [
"func",
"(",
"f",
"*",
"fen",
")",
"Init",
"(",
")",
"(",
"err",
"error",
")",
"{",
"f",
".",
"p",
",",
"err",
"=",
"f",
".",
"cf",
".",
"portCreate",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // init initializes FEN. | [
"init",
"initializes",
"FEN",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fen.go#L87-L90 | train |
rjeczalik/notify | watchpoint.go | Add | func (wp watchpoint) Add(c chan<- EventInfo, e Event) (diff eventDiff) {
wp[c] |= e
diff[0] = wp[nil]
diff[1] = diff[0] | e
wp[nil] = diff[1] &^ omit
// Strip diff from internal events.
diff[0] &^= internal
diff[1] &^= internal
if diff[0] == diff[1] {
return none
}
return
} | go | func (wp watchpoint) Add(c chan<- EventInfo, e Event) (diff eventDiff) {
wp[c] |= e
diff[0] = wp[nil]
diff[1] = diff[0] | e
wp[nil] = diff[1] &^ omit
// Strip diff from internal events.
diff[0] &^= internal
diff[1] &^= internal
if diff[0] == diff[1] {
return none
}
return
} | [
"func",
"(",
"wp",
"watchpoint",
")",
"Add",
"(",
"c",
"chan",
"<-",
"EventInfo",
",",
"e",
"Event",
")",
"(",
"diff",
"eventDiff",
")",
"{",
"wp",
"[",
"c",
"]",
"|=",
"e",
"\n",
"diff",
"[",
"0",
"]",
"=",
"wp",
"[",
"nil",
"]",
"\n",
"diff",
"[",
"1",
"]",
"=",
"diff",
"[",
"0",
"]",
"|",
"e",
"\n",
"wp",
"[",
"nil",
"]",
"=",
"diff",
"[",
"1",
"]",
"&^",
"omit",
"\n",
"// Strip diff from internal events.",
"diff",
"[",
"0",
"]",
"&^=",
"internal",
"\n",
"diff",
"[",
"1",
"]",
"&^=",
"internal",
"\n",
"if",
"diff",
"[",
"0",
"]",
"==",
"diff",
"[",
"1",
"]",
"{",
"return",
"none",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Add assumes neither c nor e are nil or zero values. | [
"Add",
"assumes",
"neither",
"c",
"nor",
"e",
"are",
"nil",
"or",
"zero",
"values",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watchpoint.go#L44-L56 | train |
rjeczalik/notify | watcher_readdcw.go | readDirChanges | func (g *grip) readDirChanges() error {
handle := syscall.Handle(atomic.LoadUintptr((*uintptr)(&g.handle)))
if handle == syscall.InvalidHandle {
return nil // Handle was closed.
}
return syscall.ReadDirectoryChanges(
handle,
&g.buffer[0],
uint32(unsafe.Sizeof(g.buffer)),
g.recursive,
encode(g.filter),
nil,
(*syscall.Overlapped)(unsafe.Pointer(g.ovlapped)),
0,
)
} | go | func (g *grip) readDirChanges() error {
handle := syscall.Handle(atomic.LoadUintptr((*uintptr)(&g.handle)))
if handle == syscall.InvalidHandle {
return nil // Handle was closed.
}
return syscall.ReadDirectoryChanges(
handle,
&g.buffer[0],
uint32(unsafe.Sizeof(g.buffer)),
g.recursive,
encode(g.filter),
nil,
(*syscall.Overlapped)(unsafe.Pointer(g.ovlapped)),
0,
)
} | [
"func",
"(",
"g",
"*",
"grip",
")",
"readDirChanges",
"(",
")",
"error",
"{",
"handle",
":=",
"syscall",
".",
"Handle",
"(",
"atomic",
".",
"LoadUintptr",
"(",
"(",
"*",
"uintptr",
")",
"(",
"&",
"g",
".",
"handle",
")",
")",
")",
"\n",
"if",
"handle",
"==",
"syscall",
".",
"InvalidHandle",
"{",
"return",
"nil",
"// Handle was closed.",
"\n",
"}",
"\n\n",
"return",
"syscall",
".",
"ReadDirectoryChanges",
"(",
"handle",
",",
"&",
"g",
".",
"buffer",
"[",
"0",
"]",
",",
"uint32",
"(",
"unsafe",
".",
"Sizeof",
"(",
"g",
".",
"buffer",
")",
")",
",",
"g",
".",
"recursive",
",",
"encode",
"(",
"g",
".",
"filter",
")",
",",
"nil",
",",
"(",
"*",
"syscall",
".",
"Overlapped",
")",
"(",
"unsafe",
".",
"Pointer",
"(",
"g",
".",
"ovlapped",
")",
")",
",",
"0",
",",
")",
"\n",
"}"
] | // readDirChanges tells the system to store file change information in grip's
// buffer. Directory changes that occur between calls to this function are added
// to the buffer and then, returned with the next call. | [
"readDirChanges",
"tells",
"the",
"system",
"to",
"store",
"file",
"change",
"information",
"in",
"grip",
"s",
"buffer",
".",
"Directory",
"changes",
"that",
"occur",
"between",
"calls",
"to",
"this",
"function",
"are",
"added",
"to",
"the",
"buffer",
"and",
"then",
"returned",
"with",
"the",
"next",
"call",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_readdcw.go#L111-L127 | train |
rjeczalik/notify | watcher_readdcw.go | encode | func encode(filter uint32) uint32 {
e := Event(filter & (onlyNGlobalEvents | onlyNotifyChanges))
if e&dirmarker != 0 {
return uint32(FileNotifyChangeDirName)
}
if e&Create != 0 {
e = (e ^ Create) | FileNotifyChangeFileName
}
if e&Remove != 0 {
e = (e ^ Remove) | FileNotifyChangeFileName
}
if e&Write != 0 {
e = (e ^ Write) | FileNotifyChangeAttributes | FileNotifyChangeSize |
FileNotifyChangeCreation | FileNotifyChangeSecurity
}
if e&Rename != 0 {
e = (e ^ Rename) | FileNotifyChangeFileName
}
return uint32(e)
} | go | func encode(filter uint32) uint32 {
e := Event(filter & (onlyNGlobalEvents | onlyNotifyChanges))
if e&dirmarker != 0 {
return uint32(FileNotifyChangeDirName)
}
if e&Create != 0 {
e = (e ^ Create) | FileNotifyChangeFileName
}
if e&Remove != 0 {
e = (e ^ Remove) | FileNotifyChangeFileName
}
if e&Write != 0 {
e = (e ^ Write) | FileNotifyChangeAttributes | FileNotifyChangeSize |
FileNotifyChangeCreation | FileNotifyChangeSecurity
}
if e&Rename != 0 {
e = (e ^ Rename) | FileNotifyChangeFileName
}
return uint32(e)
} | [
"func",
"encode",
"(",
"filter",
"uint32",
")",
"uint32",
"{",
"e",
":=",
"Event",
"(",
"filter",
"&",
"(",
"onlyNGlobalEvents",
"|",
"onlyNotifyChanges",
")",
")",
"\n",
"if",
"e",
"&",
"dirmarker",
"!=",
"0",
"{",
"return",
"uint32",
"(",
"FileNotifyChangeDirName",
")",
"\n",
"}",
"\n",
"if",
"e",
"&",
"Create",
"!=",
"0",
"{",
"e",
"=",
"(",
"e",
"^",
"Create",
")",
"|",
"FileNotifyChangeFileName",
"\n",
"}",
"\n",
"if",
"e",
"&",
"Remove",
"!=",
"0",
"{",
"e",
"=",
"(",
"e",
"^",
"Remove",
")",
"|",
"FileNotifyChangeFileName",
"\n",
"}",
"\n",
"if",
"e",
"&",
"Write",
"!=",
"0",
"{",
"e",
"=",
"(",
"e",
"^",
"Write",
")",
"|",
"FileNotifyChangeAttributes",
"|",
"FileNotifyChangeSize",
"|",
"FileNotifyChangeCreation",
"|",
"FileNotifyChangeSecurity",
"\n",
"}",
"\n",
"if",
"e",
"&",
"Rename",
"!=",
"0",
"{",
"e",
"=",
"(",
"e",
"^",
"Rename",
")",
"|",
"FileNotifyChangeFileName",
"\n",
"}",
"\n",
"return",
"uint32",
"(",
"e",
")",
"\n",
"}"
] | // encode transforms a generic filter, which contains platform independent and
// implementation specific bit fields, to value that can be used as NotifyFilter
// parameter in ReadDirectoryChangesW function. | [
"encode",
"transforms",
"a",
"generic",
"filter",
"which",
"contains",
"platform",
"independent",
"and",
"implementation",
"specific",
"bit",
"fields",
"to",
"value",
"that",
"can",
"be",
"used",
"as",
"NotifyFilter",
"parameter",
"in",
"ReadDirectoryChangesW",
"function",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_readdcw.go#L132-L151 | train |
rjeczalik/notify | watcher_readdcw.go | closeHandle | func (wd *watched) closeHandle() (err error) {
for _, g := range wd.digrip {
if g == nil {
continue
}
for {
handle := syscall.Handle(atomic.LoadUintptr((*uintptr)(&g.handle)))
if handle == syscall.InvalidHandle {
break // Already closed.
}
e := syscall.CloseHandle(handle)
if e != nil && err == nil {
err = e
}
// Set invalid handle even when CloseHandle fails. This will leak
// the handle but, since we can't close it anyway, there won't be
// any difference.
if atomic.CompareAndSwapUintptr((*uintptr)(&g.handle),
(uintptr)(handle), (uintptr)(syscall.InvalidHandle)) {
break
}
}
}
return
} | go | func (wd *watched) closeHandle() (err error) {
for _, g := range wd.digrip {
if g == nil {
continue
}
for {
handle := syscall.Handle(atomic.LoadUintptr((*uintptr)(&g.handle)))
if handle == syscall.InvalidHandle {
break // Already closed.
}
e := syscall.CloseHandle(handle)
if e != nil && err == nil {
err = e
}
// Set invalid handle even when CloseHandle fails. This will leak
// the handle but, since we can't close it anyway, there won't be
// any difference.
if atomic.CompareAndSwapUintptr((*uintptr)(&g.handle),
(uintptr)(handle), (uintptr)(syscall.InvalidHandle)) {
break
}
}
}
return
} | [
"func",
"(",
"wd",
"*",
"watched",
")",
"closeHandle",
"(",
")",
"(",
"err",
"error",
")",
"{",
"for",
"_",
",",
"g",
":=",
"range",
"wd",
".",
"digrip",
"{",
"if",
"g",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n\n",
"for",
"{",
"handle",
":=",
"syscall",
".",
"Handle",
"(",
"atomic",
".",
"LoadUintptr",
"(",
"(",
"*",
"uintptr",
")",
"(",
"&",
"g",
".",
"handle",
")",
")",
")",
"\n",
"if",
"handle",
"==",
"syscall",
".",
"InvalidHandle",
"{",
"break",
"// Already closed.",
"\n",
"}",
"\n\n",
"e",
":=",
"syscall",
".",
"CloseHandle",
"(",
"handle",
")",
"\n",
"if",
"e",
"!=",
"nil",
"&&",
"err",
"==",
"nil",
"{",
"err",
"=",
"e",
"\n",
"}",
"\n\n",
"// Set invalid handle even when CloseHandle fails. This will leak",
"// the handle but, since we can't close it anyway, there won't be",
"// any difference.",
"if",
"atomic",
".",
"CompareAndSwapUintptr",
"(",
"(",
"*",
"uintptr",
")",
"(",
"&",
"g",
".",
"handle",
")",
",",
"(",
"uintptr",
")",
"(",
"handle",
")",
",",
"(",
"uintptr",
")",
"(",
"syscall",
".",
"InvalidHandle",
")",
")",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // closeHandle closes handles that are stored in digrip array. Function always
// tries to close all of the handlers before it exits, even when there are errors
// returned from the operating system kernel. | [
"closeHandle",
"closes",
"handles",
"that",
"are",
"stored",
"in",
"digrip",
"array",
".",
"Function",
"always",
"tries",
"to",
"close",
"all",
"of",
"the",
"handlers",
"before",
"it",
"exits",
"even",
"when",
"there",
"are",
"errors",
"returned",
"from",
"the",
"operating",
"system",
"kernel",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_readdcw.go#L226-L253 | train |
rjeczalik/notify | watcher_readdcw.go | newWatcher | func newWatcher(c chan<- EventInfo) watcher {
r := &readdcw{
m: make(map[string]*watched),
cph: syscall.InvalidHandle,
c: c,
}
runtime.SetFinalizer(r, func(r *readdcw) {
if r.cph != syscall.InvalidHandle {
syscall.CloseHandle(r.cph)
}
})
return r
} | go | func newWatcher(c chan<- EventInfo) watcher {
r := &readdcw{
m: make(map[string]*watched),
cph: syscall.InvalidHandle,
c: c,
}
runtime.SetFinalizer(r, func(r *readdcw) {
if r.cph != syscall.InvalidHandle {
syscall.CloseHandle(r.cph)
}
})
return r
} | [
"func",
"newWatcher",
"(",
"c",
"chan",
"<-",
"EventInfo",
")",
"watcher",
"{",
"r",
":=",
"&",
"readdcw",
"{",
"m",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"watched",
")",
",",
"cph",
":",
"syscall",
".",
"InvalidHandle",
",",
"c",
":",
"c",
",",
"}",
"\n",
"runtime",
".",
"SetFinalizer",
"(",
"r",
",",
"func",
"(",
"r",
"*",
"readdcw",
")",
"{",
"if",
"r",
".",
"cph",
"!=",
"syscall",
".",
"InvalidHandle",
"{",
"syscall",
".",
"CloseHandle",
"(",
"r",
".",
"cph",
")",
"\n",
"}",
"\n",
"}",
")",
"\n",
"return",
"r",
"\n",
"}"
] | // NewWatcher creates new non-recursive watcher backed by ReadDirectoryChangesW. | [
"NewWatcher",
"creates",
"new",
"non",
"-",
"recursive",
"watcher",
"backed",
"by",
"ReadDirectoryChangesW",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_readdcw.go#L268-L280 | train |
rjeczalik/notify | watcher_readdcw.go | Watch | func (r *readdcw) Watch(path string, event Event) error {
return r.watch(path, event, false)
} | go | func (r *readdcw) Watch(path string, event Event) error {
return r.watch(path, event, false)
} | [
"func",
"(",
"r",
"*",
"readdcw",
")",
"Watch",
"(",
"path",
"string",
",",
"event",
"Event",
")",
"error",
"{",
"return",
"r",
".",
"watch",
"(",
"path",
",",
"event",
",",
"false",
")",
"\n",
"}"
] | // Watch implements notify.Watcher interface. | [
"Watch",
"implements",
"notify",
".",
"Watcher",
"interface",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_readdcw.go#L283-L285 | train |
rjeczalik/notify | watcher_readdcw.go | RecursiveWatch | func (r *readdcw) RecursiveWatch(path string, event Event) error {
return r.watch(path, event, true)
} | go | func (r *readdcw) RecursiveWatch(path string, event Event) error {
return r.watch(path, event, true)
} | [
"func",
"(",
"r",
"*",
"readdcw",
")",
"RecursiveWatch",
"(",
"path",
"string",
",",
"event",
"Event",
")",
"error",
"{",
"return",
"r",
".",
"watch",
"(",
"path",
",",
"event",
",",
"true",
")",
"\n",
"}"
] | // RecursiveWatch implements notify.RecursiveWatcher interface. | [
"RecursiveWatch",
"implements",
"notify",
".",
"RecursiveWatcher",
"interface",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_readdcw.go#L288-L290 | train |
rjeczalik/notify | watcher_readdcw.go | Rewatch | func (r *readdcw) Rewatch(path string, oldevent, newevent Event) error {
return r.rewatch(path, uint32(oldevent), uint32(newevent), false)
} | go | func (r *readdcw) Rewatch(path string, oldevent, newevent Event) error {
return r.rewatch(path, uint32(oldevent), uint32(newevent), false)
} | [
"func",
"(",
"r",
"*",
"readdcw",
")",
"Rewatch",
"(",
"path",
"string",
",",
"oldevent",
",",
"newevent",
"Event",
")",
"error",
"{",
"return",
"r",
".",
"rewatch",
"(",
"path",
",",
"uint32",
"(",
"oldevent",
")",
",",
"uint32",
"(",
"newevent",
")",
",",
"false",
")",
"\n",
"}"
] | // Rewatch implements notify.Rewatcher interface. | [
"Rewatch",
"implements",
"notify",
".",
"Rewatcher",
"interface",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_readdcw.go#L451-L453 | train |
rjeczalik/notify | watcher_readdcw.go | RecursiveRewatch | func (r *readdcw) RecursiveRewatch(oldpath, newpath string, oldevent,
newevent Event) error {
if oldpath != newpath {
if err := r.unwatch(oldpath); err != nil {
return err
}
return r.watch(newpath, newevent, true)
}
return r.rewatch(newpath, uint32(oldevent), uint32(newevent), true)
} | go | func (r *readdcw) RecursiveRewatch(oldpath, newpath string, oldevent,
newevent Event) error {
if oldpath != newpath {
if err := r.unwatch(oldpath); err != nil {
return err
}
return r.watch(newpath, newevent, true)
}
return r.rewatch(newpath, uint32(oldevent), uint32(newevent), true)
} | [
"func",
"(",
"r",
"*",
"readdcw",
")",
"RecursiveRewatch",
"(",
"oldpath",
",",
"newpath",
"string",
",",
"oldevent",
",",
"newevent",
"Event",
")",
"error",
"{",
"if",
"oldpath",
"!=",
"newpath",
"{",
"if",
"err",
":=",
"r",
".",
"unwatch",
"(",
"oldpath",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"r",
".",
"watch",
"(",
"newpath",
",",
"newevent",
",",
"true",
")",
"\n",
"}",
"\n",
"return",
"r",
".",
"rewatch",
"(",
"newpath",
",",
"uint32",
"(",
"oldevent",
")",
",",
"uint32",
"(",
"newevent",
")",
",",
"true",
")",
"\n",
"}"
] | // RecursiveRewatch implements notify.RecursiveRewatcher interface. | [
"RecursiveRewatch",
"implements",
"notify",
".",
"RecursiveRewatcher",
"interface",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_readdcw.go#L456-L465 | train |
rjeczalik/notify | watcher_readdcw.go | Close | func (r *readdcw) Close() (err error) {
r.Lock()
if !r.start {
r.Unlock()
return nil
}
for _, wd := range r.m {
wd.filter &^= onlyMachineStates
wd.filter |= stateCPClose
if e := wd.closeHandle(); e != nil && err == nil {
err = e
}
}
r.start = false
r.Unlock()
r.wg.Add(1)
if e := syscall.PostQueuedCompletionStatus(r.cph, 0, stateCPClose, nil); e != nil && err == nil {
return e
}
r.wg.Wait()
return
} | go | func (r *readdcw) Close() (err error) {
r.Lock()
if !r.start {
r.Unlock()
return nil
}
for _, wd := range r.m {
wd.filter &^= onlyMachineStates
wd.filter |= stateCPClose
if e := wd.closeHandle(); e != nil && err == nil {
err = e
}
}
r.start = false
r.Unlock()
r.wg.Add(1)
if e := syscall.PostQueuedCompletionStatus(r.cph, 0, stateCPClose, nil); e != nil && err == nil {
return e
}
r.wg.Wait()
return
} | [
"func",
"(",
"r",
"*",
"readdcw",
")",
"Close",
"(",
")",
"(",
"err",
"error",
")",
"{",
"r",
".",
"Lock",
"(",
")",
"\n",
"if",
"!",
"r",
".",
"start",
"{",
"r",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"for",
"_",
",",
"wd",
":=",
"range",
"r",
".",
"m",
"{",
"wd",
".",
"filter",
"&^=",
"onlyMachineStates",
"\n",
"wd",
".",
"filter",
"|=",
"stateCPClose",
"\n",
"if",
"e",
":=",
"wd",
".",
"closeHandle",
"(",
")",
";",
"e",
"!=",
"nil",
"&&",
"err",
"==",
"nil",
"{",
"err",
"=",
"e",
"\n",
"}",
"\n",
"}",
"\n",
"r",
".",
"start",
"=",
"false",
"\n",
"r",
".",
"Unlock",
"(",
")",
"\n",
"r",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"if",
"e",
":=",
"syscall",
".",
"PostQueuedCompletionStatus",
"(",
"r",
".",
"cph",
",",
"0",
",",
"stateCPClose",
",",
"nil",
")",
";",
"e",
"!=",
"nil",
"&&",
"err",
"==",
"nil",
"{",
"return",
"e",
"\n",
"}",
"\n",
"r",
".",
"wg",
".",
"Wait",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Close resets the whole watcher object, closes all existing file descriptors,
// and sends stateCPClose state as completion key to the main watcher's loop. | [
"Close",
"resets",
"the",
"whole",
"watcher",
"object",
"closes",
"all",
"existing",
"file",
"descriptors",
"and",
"sends",
"stateCPClose",
"state",
"as",
"completion",
"key",
"to",
"the",
"main",
"watcher",
"s",
"loop",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_readdcw.go#L547-L568 | train |
rjeczalik/notify | watcher_readdcw.go | gensys | func gensys(filter uint32, ge, se Event) (gene, syse Event) {
isdir := filter&uint32(dirmarker) != 0
if isdir && filter&uint32(FileNotifyChangeDirName) != 0 ||
!isdir && filter&uint32(FileNotifyChangeFileName) != 0 ||
filter&uint32(fileNotifyChangeModified) != 0 {
syse = se
}
if filter&uint32(ge) != 0 {
gene = ge
}
return
} | go | func gensys(filter uint32, ge, se Event) (gene, syse Event) {
isdir := filter&uint32(dirmarker) != 0
if isdir && filter&uint32(FileNotifyChangeDirName) != 0 ||
!isdir && filter&uint32(FileNotifyChangeFileName) != 0 ||
filter&uint32(fileNotifyChangeModified) != 0 {
syse = se
}
if filter&uint32(ge) != 0 {
gene = ge
}
return
} | [
"func",
"gensys",
"(",
"filter",
"uint32",
",",
"ge",
",",
"se",
"Event",
")",
"(",
"gene",
",",
"syse",
"Event",
")",
"{",
"isdir",
":=",
"filter",
"&",
"uint32",
"(",
"dirmarker",
")",
"!=",
"0",
"\n",
"if",
"isdir",
"&&",
"filter",
"&",
"uint32",
"(",
"FileNotifyChangeDirName",
")",
"!=",
"0",
"||",
"!",
"isdir",
"&&",
"filter",
"&",
"uint32",
"(",
"FileNotifyChangeFileName",
")",
"!=",
"0",
"||",
"filter",
"&",
"uint32",
"(",
"fileNotifyChangeModified",
")",
"!=",
"0",
"{",
"syse",
"=",
"se",
"\n",
"}",
"\n",
"if",
"filter",
"&",
"uint32",
"(",
"ge",
")",
"!=",
"0",
"{",
"gene",
"=",
"ge",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // gensys decides whether the Windows action, system-independent event or both
// of them should be returned. Since the grip's filter may be atomically changed
// during watcher lifetime, it is possible that neither Windows nor notify masks
// are watched by the user when this function is called. | [
"gensys",
"decides",
"whether",
"the",
"Windows",
"action",
"system",
"-",
"independent",
"event",
"or",
"both",
"of",
"them",
"should",
"be",
"returned",
".",
"Since",
"the",
"grip",
"s",
"filter",
"may",
"be",
"atomically",
"changed",
"during",
"watcher",
"lifetime",
"it",
"is",
"possible",
"that",
"neither",
"Windows",
"nor",
"notify",
"masks",
"are",
"watched",
"by",
"the",
"user",
"when",
"this",
"function",
"is",
"called",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_readdcw.go#L594-L605 | train |
rjeczalik/notify | watcher_fsevents.go | splitflags | func splitflags(set uint32) (e []uint32) {
for i := uint32(1); set != 0; i, set = i<<1, set>>1 {
if (set & 1) != 0 {
e = append(e, i)
}
}
return
} | go | func splitflags(set uint32) (e []uint32) {
for i := uint32(1); set != 0; i, set = i<<1, set>>1 {
if (set & 1) != 0 {
e = append(e, i)
}
}
return
} | [
"func",
"splitflags",
"(",
"set",
"uint32",
")",
"(",
"e",
"[",
"]",
"uint32",
")",
"{",
"for",
"i",
":=",
"uint32",
"(",
"1",
")",
";",
"set",
"!=",
"0",
";",
"i",
",",
"set",
"=",
"i",
"<<",
"1",
",",
"set",
">>",
"1",
"{",
"if",
"(",
"set",
"&",
"1",
")",
"!=",
"0",
"{",
"e",
"=",
"append",
"(",
"e",
",",
"i",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // splitflags separates event flags from single set into slice of flags. | [
"splitflags",
"separates",
"event",
"flags",
"from",
"single",
"set",
"into",
"slice",
"of",
"flags",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fsevents.go#L30-L37 | train |
rjeczalik/notify | watcher_fsevents.go | Dispatch | func (w *watch) Dispatch(ev []FSEvent) {
events := atomic.LoadUint32(&w.events)
isrec := (atomic.LoadInt32(&w.isrec) == 1)
for i := range ev {
if ev[i].Flags&FSEventsHistoryDone != 0 {
w.flushed = true
continue
}
if !w.flushed {
continue
}
dbgprintf("%v (0x%x) (%s, i=%d, ID=%d, len=%d)\n", Event(ev[i].Flags),
ev[i].Flags, ev[i].Path, i, ev[i].ID, len(ev))
if ev[i].Flags&failure != 0 {
// TODO(rjeczalik): missing error handling
continue
}
if !strings.HasPrefix(ev[i].Path, w.path) {
continue
}
n := len(w.path)
base := ""
if len(ev[i].Path) > n {
if ev[i].Path[n] != '/' {
continue
}
base = ev[i].Path[n+1:]
if !isrec && strings.IndexByte(base, '/') != -1 {
continue
}
}
// TODO(rjeczalik): get diff only from filtered events?
e := w.strip(string(base), ev[i].Flags) & events
if e == 0 {
continue
}
for _, e := range splitflags(e) {
dbgprintf("%d: single event: %v", ev[i].ID, Event(e))
w.c <- &event{
fse: ev[i],
event: Event(e),
}
}
}
} | go | func (w *watch) Dispatch(ev []FSEvent) {
events := atomic.LoadUint32(&w.events)
isrec := (atomic.LoadInt32(&w.isrec) == 1)
for i := range ev {
if ev[i].Flags&FSEventsHistoryDone != 0 {
w.flushed = true
continue
}
if !w.flushed {
continue
}
dbgprintf("%v (0x%x) (%s, i=%d, ID=%d, len=%d)\n", Event(ev[i].Flags),
ev[i].Flags, ev[i].Path, i, ev[i].ID, len(ev))
if ev[i].Flags&failure != 0 {
// TODO(rjeczalik): missing error handling
continue
}
if !strings.HasPrefix(ev[i].Path, w.path) {
continue
}
n := len(w.path)
base := ""
if len(ev[i].Path) > n {
if ev[i].Path[n] != '/' {
continue
}
base = ev[i].Path[n+1:]
if !isrec && strings.IndexByte(base, '/') != -1 {
continue
}
}
// TODO(rjeczalik): get diff only from filtered events?
e := w.strip(string(base), ev[i].Flags) & events
if e == 0 {
continue
}
for _, e := range splitflags(e) {
dbgprintf("%d: single event: %v", ev[i].ID, Event(e))
w.c <- &event{
fse: ev[i],
event: Event(e),
}
}
}
} | [
"func",
"(",
"w",
"*",
"watch",
")",
"Dispatch",
"(",
"ev",
"[",
"]",
"FSEvent",
")",
"{",
"events",
":=",
"atomic",
".",
"LoadUint32",
"(",
"&",
"w",
".",
"events",
")",
"\n",
"isrec",
":=",
"(",
"atomic",
".",
"LoadInt32",
"(",
"&",
"w",
".",
"isrec",
")",
"==",
"1",
")",
"\n",
"for",
"i",
":=",
"range",
"ev",
"{",
"if",
"ev",
"[",
"i",
"]",
".",
"Flags",
"&",
"FSEventsHistoryDone",
"!=",
"0",
"{",
"w",
".",
"flushed",
"=",
"true",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"!",
"w",
".",
"flushed",
"{",
"continue",
"\n",
"}",
"\n",
"dbgprintf",
"(",
"\"",
"\\n",
"\"",
",",
"Event",
"(",
"ev",
"[",
"i",
"]",
".",
"Flags",
")",
",",
"ev",
"[",
"i",
"]",
".",
"Flags",
",",
"ev",
"[",
"i",
"]",
".",
"Path",
",",
"i",
",",
"ev",
"[",
"i",
"]",
".",
"ID",
",",
"len",
"(",
"ev",
")",
")",
"\n",
"if",
"ev",
"[",
"i",
"]",
".",
"Flags",
"&",
"failure",
"!=",
"0",
"{",
"// TODO(rjeczalik): missing error handling",
"continue",
"\n",
"}",
"\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"ev",
"[",
"i",
"]",
".",
"Path",
",",
"w",
".",
"path",
")",
"{",
"continue",
"\n",
"}",
"\n",
"n",
":=",
"len",
"(",
"w",
".",
"path",
")",
"\n",
"base",
":=",
"\"",
"\"",
"\n",
"if",
"len",
"(",
"ev",
"[",
"i",
"]",
".",
"Path",
")",
">",
"n",
"{",
"if",
"ev",
"[",
"i",
"]",
".",
"Path",
"[",
"n",
"]",
"!=",
"'/'",
"{",
"continue",
"\n",
"}",
"\n",
"base",
"=",
"ev",
"[",
"i",
"]",
".",
"Path",
"[",
"n",
"+",
"1",
":",
"]",
"\n",
"if",
"!",
"isrec",
"&&",
"strings",
".",
"IndexByte",
"(",
"base",
",",
"'/'",
")",
"!=",
"-",
"1",
"{",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"// TODO(rjeczalik): get diff only from filtered events?",
"e",
":=",
"w",
".",
"strip",
"(",
"string",
"(",
"base",
")",
",",
"ev",
"[",
"i",
"]",
".",
"Flags",
")",
"&",
"events",
"\n",
"if",
"e",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n",
"for",
"_",
",",
"e",
":=",
"range",
"splitflags",
"(",
"e",
")",
"{",
"dbgprintf",
"(",
"\"",
"\"",
",",
"ev",
"[",
"i",
"]",
".",
"ID",
",",
"Event",
"(",
"e",
")",
")",
"\n",
"w",
".",
"c",
"<-",
"&",
"event",
"{",
"fse",
":",
"ev",
"[",
"i",
"]",
",",
"event",
":",
"Event",
"(",
"e",
")",
",",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Dispatch is a stream function which forwards given file events for the watched
// path to underlying FileInfo channel. | [
"Dispatch",
"is",
"a",
"stream",
"function",
"which",
"forwards",
"given",
"file",
"events",
"for",
"the",
"watched",
"path",
"to",
"underlying",
"FileInfo",
"channel",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fsevents.go#L119-L163 | train |
rjeczalik/notify | watcher_fsevents.go | Stop | func (w *watch) Stop() {
w.stream.Stop()
// TODO(rjeczalik): make (*stream).Stop flush synchronously undelivered events,
// so the following hack can be removed. It should flush all the streams
// concurrently as we care not to block too much here.
atomic.StoreUint32(&w.events, 0)
atomic.StoreInt32(&w.isrec, 0)
} | go | func (w *watch) Stop() {
w.stream.Stop()
// TODO(rjeczalik): make (*stream).Stop flush synchronously undelivered events,
// so the following hack can be removed. It should flush all the streams
// concurrently as we care not to block too much here.
atomic.StoreUint32(&w.events, 0)
atomic.StoreInt32(&w.isrec, 0)
} | [
"func",
"(",
"w",
"*",
"watch",
")",
"Stop",
"(",
")",
"{",
"w",
".",
"stream",
".",
"Stop",
"(",
")",
"\n",
"// TODO(rjeczalik): make (*stream).Stop flush synchronously undelivered events,",
"// so the following hack can be removed. It should flush all the streams",
"// concurrently as we care not to block too much here.",
"atomic",
".",
"StoreUint32",
"(",
"&",
"w",
".",
"events",
",",
"0",
")",
"\n",
"atomic",
".",
"StoreInt32",
"(",
"&",
"w",
".",
"isrec",
",",
"0",
")",
"\n",
"}"
] | // Stop closes underlying FSEvents stream and stops dispatching events. | [
"Stop",
"closes",
"underlying",
"FSEvents",
"stream",
"and",
"stops",
"dispatching",
"events",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fsevents.go#L166-L173 | train |
rjeczalik/notify | watcher_fsevents.go | Watch | func (fse *fsevents) Watch(path string, event Event) error {
return fse.watch(path, event, 0)
} | go | func (fse *fsevents) Watch(path string, event Event) error {
return fse.watch(path, event, 0)
} | [
"func",
"(",
"fse",
"*",
"fsevents",
")",
"Watch",
"(",
"path",
"string",
",",
"event",
"Event",
")",
"error",
"{",
"return",
"fse",
".",
"watch",
"(",
"path",
",",
"event",
",",
"0",
")",
"\n",
"}"
] | // Watch implements Watcher interface. It fails with non-nil error when setting
// the watch-point by FSEvents fails or with errAlreadyWatched error when
// the given path is already watched. | [
"Watch",
"implements",
"Watcher",
"interface",
".",
"It",
"fails",
"with",
"non",
"-",
"nil",
"error",
"when",
"setting",
"the",
"watch",
"-",
"point",
"by",
"FSEvents",
"fails",
"or",
"with",
"errAlreadyWatched",
"error",
"when",
"the",
"given",
"path",
"is",
"already",
"watched",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fsevents.go#L221-L223 | train |
rjeczalik/notify | watcher_fsevents.go | Rewatch | func (fse *fsevents) Rewatch(path string, oldevent, newevent Event) error {
w, ok := fse.watches[path]
if !ok {
return errNotWatched
}
if !atomic.CompareAndSwapUint32(&w.events, uint32(oldevent), uint32(newevent)) {
return errInvalidEventSet
}
atomic.StoreInt32(&w.isrec, 0)
return nil
} | go | func (fse *fsevents) Rewatch(path string, oldevent, newevent Event) error {
w, ok := fse.watches[path]
if !ok {
return errNotWatched
}
if !atomic.CompareAndSwapUint32(&w.events, uint32(oldevent), uint32(newevent)) {
return errInvalidEventSet
}
atomic.StoreInt32(&w.isrec, 0)
return nil
} | [
"func",
"(",
"fse",
"*",
"fsevents",
")",
"Rewatch",
"(",
"path",
"string",
",",
"oldevent",
",",
"newevent",
"Event",
")",
"error",
"{",
"w",
",",
"ok",
":=",
"fse",
".",
"watches",
"[",
"path",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errNotWatched",
"\n",
"}",
"\n",
"if",
"!",
"atomic",
".",
"CompareAndSwapUint32",
"(",
"&",
"w",
".",
"events",
",",
"uint32",
"(",
"oldevent",
")",
",",
"uint32",
"(",
"newevent",
")",
")",
"{",
"return",
"errInvalidEventSet",
"\n",
"}",
"\n",
"atomic",
".",
"StoreInt32",
"(",
"&",
"w",
".",
"isrec",
",",
"0",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Rewatch implements Watcher interface. It fails with errNotWatched when
// the given path is not being watched or with errInvalidEventSet when oldevent
// does not match event set the watch-point currently holds. | [
"Rewatch",
"implements",
"Watcher",
"interface",
".",
"It",
"fails",
"with",
"errNotWatched",
"when",
"the",
"given",
"path",
"is",
"not",
"being",
"watched",
"or",
"with",
"errInvalidEventSet",
"when",
"oldevent",
"does",
"not",
"match",
"event",
"set",
"the",
"watch",
"-",
"point",
"currently",
"holds",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fsevents.go#L234-L244 | train |
rjeczalik/notify | watcher_fsevents.go | Close | func (fse *fsevents) Close() error {
for _, w := range fse.watches {
w.Stop()
}
fse.watches = nil
return nil
} | go | func (fse *fsevents) Close() error {
for _, w := range fse.watches {
w.Stop()
}
fse.watches = nil
return nil
} | [
"func",
"(",
"fse",
"*",
"fsevents",
")",
"Close",
"(",
")",
"error",
"{",
"for",
"_",
",",
"w",
":=",
"range",
"fse",
".",
"watches",
"{",
"w",
".",
"Stop",
"(",
")",
"\n",
"}",
"\n",
"fse",
".",
"watches",
"=",
"nil",
"\n",
"return",
"nil",
"\n",
"}"
] | // Close unwatches all watch-points. | [
"Close",
"unwatches",
"all",
"watch",
"-",
"points",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fsevents.go#L305-L311 | train |
rjeczalik/notify | watcher_fsevents_cgo.go | init | func init() {
wg.Add(1)
go func() {
// There is exactly one run loop per thread. Lock this goroutine to its
// thread to ensure that it's not rescheduled on a different thread while
// setting up the run loop.
runtime.LockOSThread()
runloop = C.CFRunLoopGetCurrent()
C.CFRunLoopAddSource(runloop, source, C.kCFRunLoopDefaultMode)
C.CFRunLoopRun()
panic("runloop has just unexpectedly stopped")
}()
C.CFRunLoopSourceSignal(source)
} | go | func init() {
wg.Add(1)
go func() {
// There is exactly one run loop per thread. Lock this goroutine to its
// thread to ensure that it's not rescheduled on a different thread while
// setting up the run loop.
runtime.LockOSThread()
runloop = C.CFRunLoopGetCurrent()
C.CFRunLoopAddSource(runloop, source, C.kCFRunLoopDefaultMode)
C.CFRunLoopRun()
panic("runloop has just unexpectedly stopped")
}()
C.CFRunLoopSourceSignal(source)
} | [
"func",
"init",
"(",
")",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"// There is exactly one run loop per thread. Lock this goroutine to its",
"// thread to ensure that it's not rescheduled on a different thread while",
"// setting up the run loop.",
"runtime",
".",
"LockOSThread",
"(",
")",
"\n",
"runloop",
"=",
"C",
".",
"CFRunLoopGetCurrent",
"(",
")",
"\n",
"C",
".",
"CFRunLoopAddSource",
"(",
"runloop",
",",
"source",
",",
"C",
".",
"kCFRunLoopDefaultMode",
")",
"\n",
"C",
".",
"CFRunLoopRun",
"(",
")",
"\n",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"(",
")",
"\n",
"C",
".",
"CFRunLoopSourceSignal",
"(",
"source",
")",
"\n",
"}"
] | // initializes the global runloop and ensures any created stream awaits its
// readiness. | [
"initializes",
"the",
"global",
"runloop",
"and",
"ensures",
"any",
"created",
"stream",
"awaits",
"its",
"readiness",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fsevents_cgo.go#L63-L76 | train |
rjeczalik/notify | watcher_fsevents_cgo.go | newStream | func newStream(path string, fn streamFunc) *stream {
return &stream{
path: path,
info: streamFuncs.add(fn),
}
} | go | func newStream(path string, fn streamFunc) *stream {
return &stream{
path: path,
info: streamFuncs.add(fn),
}
} | [
"func",
"newStream",
"(",
"path",
"string",
",",
"fn",
"streamFunc",
")",
"*",
"stream",
"{",
"return",
"&",
"stream",
"{",
"path",
":",
"path",
",",
"info",
":",
"streamFuncs",
".",
"add",
"(",
"fn",
")",
",",
"}",
"\n",
"}"
] | // NewStream creates a stream for given path, listening for file events and
// calling fn upon receiving any. | [
"NewStream",
"creates",
"a",
"stream",
"for",
"given",
"path",
"listening",
"for",
"file",
"events",
"and",
"calling",
"fn",
"upon",
"receiving",
"any",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fsevents_cgo.go#L155-L160 | train |
rjeczalik/notify | watcher_fsevents_cgo.go | Start | func (s *stream) Start() error {
if s.ref != nilstream {
return nil
}
wg.Wait()
p := C.CFStringCreateWithCStringNoCopy(C.kCFAllocatorDefault, C.CString(s.path), C.kCFStringEncodingUTF8, C.kCFAllocatorDefault)
path := C.CFArrayCreate(C.kCFAllocatorDefault, (*unsafe.Pointer)(unsafe.Pointer(&p)), 1, nil)
ctx := C.FSEventStreamContext{}
ref := C.EventStreamCreate(&ctx, C.uintptr_t(s.info), path, C.FSEventStreamEventId(atomic.LoadUint64(&since)), latency, flags)
if ref == nilstream {
return errCreate
}
C.FSEventStreamScheduleWithRunLoop(ref, runloop, C.kCFRunLoopDefaultMode)
if C.FSEventStreamStart(ref) == C.Boolean(0) {
C.FSEventStreamInvalidate(ref)
return errStart
}
C.CFRunLoopWakeUp(runloop)
s.ref = ref
return nil
} | go | func (s *stream) Start() error {
if s.ref != nilstream {
return nil
}
wg.Wait()
p := C.CFStringCreateWithCStringNoCopy(C.kCFAllocatorDefault, C.CString(s.path), C.kCFStringEncodingUTF8, C.kCFAllocatorDefault)
path := C.CFArrayCreate(C.kCFAllocatorDefault, (*unsafe.Pointer)(unsafe.Pointer(&p)), 1, nil)
ctx := C.FSEventStreamContext{}
ref := C.EventStreamCreate(&ctx, C.uintptr_t(s.info), path, C.FSEventStreamEventId(atomic.LoadUint64(&since)), latency, flags)
if ref == nilstream {
return errCreate
}
C.FSEventStreamScheduleWithRunLoop(ref, runloop, C.kCFRunLoopDefaultMode)
if C.FSEventStreamStart(ref) == C.Boolean(0) {
C.FSEventStreamInvalidate(ref)
return errStart
}
C.CFRunLoopWakeUp(runloop)
s.ref = ref
return nil
} | [
"func",
"(",
"s",
"*",
"stream",
")",
"Start",
"(",
")",
"error",
"{",
"if",
"s",
".",
"ref",
"!=",
"nilstream",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"p",
":=",
"C",
".",
"CFStringCreateWithCStringNoCopy",
"(",
"C",
".",
"kCFAllocatorDefault",
",",
"C",
".",
"CString",
"(",
"s",
".",
"path",
")",
",",
"C",
".",
"kCFStringEncodingUTF8",
",",
"C",
".",
"kCFAllocatorDefault",
")",
"\n",
"path",
":=",
"C",
".",
"CFArrayCreate",
"(",
"C",
".",
"kCFAllocatorDefault",
",",
"(",
"*",
"unsafe",
".",
"Pointer",
")",
"(",
"unsafe",
".",
"Pointer",
"(",
"&",
"p",
")",
")",
",",
"1",
",",
"nil",
")",
"\n",
"ctx",
":=",
"C",
".",
"FSEventStreamContext",
"{",
"}",
"\n",
"ref",
":=",
"C",
".",
"EventStreamCreate",
"(",
"&",
"ctx",
",",
"C",
".",
"uintptr_t",
"(",
"s",
".",
"info",
")",
",",
"path",
",",
"C",
".",
"FSEventStreamEventId",
"(",
"atomic",
".",
"LoadUint64",
"(",
"&",
"since",
")",
")",
",",
"latency",
",",
"flags",
")",
"\n",
"if",
"ref",
"==",
"nilstream",
"{",
"return",
"errCreate",
"\n",
"}",
"\n",
"C",
".",
"FSEventStreamScheduleWithRunLoop",
"(",
"ref",
",",
"runloop",
",",
"C",
".",
"kCFRunLoopDefaultMode",
")",
"\n",
"if",
"C",
".",
"FSEventStreamStart",
"(",
"ref",
")",
"==",
"C",
".",
"Boolean",
"(",
"0",
")",
"{",
"C",
".",
"FSEventStreamInvalidate",
"(",
"ref",
")",
"\n",
"return",
"errStart",
"\n",
"}",
"\n",
"C",
".",
"CFRunLoopWakeUp",
"(",
"runloop",
")",
"\n",
"s",
".",
"ref",
"=",
"ref",
"\n",
"return",
"nil",
"\n",
"}"
] | // Start creates a FSEventStream for the given path and schedules it with
// global runloop. It's a nop if the stream was already started. | [
"Start",
"creates",
"a",
"FSEventStream",
"for",
"the",
"given",
"path",
"and",
"schedules",
"it",
"with",
"global",
"runloop",
".",
"It",
"s",
"a",
"nop",
"if",
"the",
"stream",
"was",
"already",
"started",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fsevents_cgo.go#L164-L184 | train |
rjeczalik/notify | watcher_fsevents_cgo.go | Stop | func (s *stream) Stop() {
if s.ref == nilstream {
return
}
wg.Wait()
C.FSEventStreamStop(s.ref)
C.FSEventStreamInvalidate(s.ref)
C.CFRunLoopWakeUp(runloop)
s.ref = nilstream
streamFuncs.delete(s.info)
} | go | func (s *stream) Stop() {
if s.ref == nilstream {
return
}
wg.Wait()
C.FSEventStreamStop(s.ref)
C.FSEventStreamInvalidate(s.ref)
C.CFRunLoopWakeUp(runloop)
s.ref = nilstream
streamFuncs.delete(s.info)
} | [
"func",
"(",
"s",
"*",
"stream",
")",
"Stop",
"(",
")",
"{",
"if",
"s",
".",
"ref",
"==",
"nilstream",
"{",
"return",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"C",
".",
"FSEventStreamStop",
"(",
"s",
".",
"ref",
")",
"\n",
"C",
".",
"FSEventStreamInvalidate",
"(",
"s",
".",
"ref",
")",
"\n",
"C",
".",
"CFRunLoopWakeUp",
"(",
"runloop",
")",
"\n",
"s",
".",
"ref",
"=",
"nilstream",
"\n",
"streamFuncs",
".",
"delete",
"(",
"s",
".",
"info",
")",
"\n",
"}"
] | // Stop stops underlying FSEventStream and unregisters it from global runloop. | [
"Stop",
"stops",
"underlying",
"FSEventStream",
"and",
"unregisters",
"it",
"from",
"global",
"runloop",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fsevents_cgo.go#L187-L197 | train |
rjeczalik/notify | util.go | nonil | func nonil(err ...error) error {
for _, err := range err {
if err != nil {
return err
}
}
return nil
} | go | func nonil(err ...error) error {
for _, err := range err {
if err != nil {
return err
}
}
return nil
} | [
"func",
"nonil",
"(",
"err",
"...",
"error",
")",
"error",
"{",
"for",
"_",
",",
"err",
":=",
"range",
"err",
"{",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // nonil gives first non-nil error from the given arguments. | [
"nonil",
"gives",
"first",
"non",
"-",
"nil",
"error",
"from",
"the",
"given",
"arguments",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/util.go#L41-L48 | train |
rjeczalik/notify | util.go | canonical | func canonical(p string) (string, error) {
p, err := filepath.Abs(p)
if err != nil {
return "", err
}
for i, j, depth := 1, 0, 1; i < len(p); i, depth = i+1, depth+1 {
if depth > 128 {
return "", &os.PathError{Op: "canonical", Path: p, Err: errDepth}
}
if j = strings.IndexRune(p[i:], '/'); j == -1 {
j, i = i, len(p)
} else {
j, i = i, i+j
}
fi, err := os.Lstat(p[:i])
if err != nil {
return "", err
}
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
s, err := os.Readlink(p[:i])
if err != nil {
return "", err
}
if filepath.IsAbs(s) {
p = "/" + s + p[i:]
} else {
p = p[:j] + s + p[i:]
}
i = 1 // no guarantee s is canonical, start all over
}
}
return filepath.Clean(p), nil
} | go | func canonical(p string) (string, error) {
p, err := filepath.Abs(p)
if err != nil {
return "", err
}
for i, j, depth := 1, 0, 1; i < len(p); i, depth = i+1, depth+1 {
if depth > 128 {
return "", &os.PathError{Op: "canonical", Path: p, Err: errDepth}
}
if j = strings.IndexRune(p[i:], '/'); j == -1 {
j, i = i, len(p)
} else {
j, i = i, i+j
}
fi, err := os.Lstat(p[:i])
if err != nil {
return "", err
}
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
s, err := os.Readlink(p[:i])
if err != nil {
return "", err
}
if filepath.IsAbs(s) {
p = "/" + s + p[i:]
} else {
p = p[:j] + s + p[i:]
}
i = 1 // no guarantee s is canonical, start all over
}
}
return filepath.Clean(p), nil
} | [
"func",
"canonical",
"(",
"p",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"p",
",",
"err",
":=",
"filepath",
".",
"Abs",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"for",
"i",
",",
"j",
",",
"depth",
":=",
"1",
",",
"0",
",",
"1",
";",
"i",
"<",
"len",
"(",
"p",
")",
";",
"i",
",",
"depth",
"=",
"i",
"+",
"1",
",",
"depth",
"+",
"1",
"{",
"if",
"depth",
">",
"128",
"{",
"return",
"\"",
"\"",
",",
"&",
"os",
".",
"PathError",
"{",
"Op",
":",
"\"",
"\"",
",",
"Path",
":",
"p",
",",
"Err",
":",
"errDepth",
"}",
"\n",
"}",
"\n",
"if",
"j",
"=",
"strings",
".",
"IndexRune",
"(",
"p",
"[",
"i",
":",
"]",
",",
"'/'",
")",
";",
"j",
"==",
"-",
"1",
"{",
"j",
",",
"i",
"=",
"i",
",",
"len",
"(",
"p",
")",
"\n",
"}",
"else",
"{",
"j",
",",
"i",
"=",
"i",
",",
"i",
"+",
"j",
"\n",
"}",
"\n",
"fi",
",",
"err",
":=",
"os",
".",
"Lstat",
"(",
"p",
"[",
":",
"i",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"fi",
".",
"Mode",
"(",
")",
"&",
"os",
".",
"ModeSymlink",
"==",
"os",
".",
"ModeSymlink",
"{",
"s",
",",
"err",
":=",
"os",
".",
"Readlink",
"(",
"p",
"[",
":",
"i",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"filepath",
".",
"IsAbs",
"(",
"s",
")",
"{",
"p",
"=",
"\"",
"\"",
"+",
"s",
"+",
"p",
"[",
"i",
":",
"]",
"\n",
"}",
"else",
"{",
"p",
"=",
"p",
"[",
":",
"j",
"]",
"+",
"s",
"+",
"p",
"[",
"i",
":",
"]",
"\n",
"}",
"\n",
"i",
"=",
"1",
"// no guarantee s is canonical, start all over",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"filepath",
".",
"Clean",
"(",
"p",
")",
",",
"nil",
"\n",
"}"
] | // canonical resolves any symlink in the given path and returns it in a clean form.
// It expects the path to be absolute. It fails to resolve circular symlinks by
// maintaining a simple iteration limit. | [
"canonical",
"resolves",
"any",
"symlink",
"in",
"the",
"given",
"path",
"and",
"returns",
"it",
"in",
"a",
"clean",
"form",
".",
"It",
"expects",
"the",
"path",
"to",
"be",
"absolute",
".",
"It",
"fails",
"to",
"resolve",
"circular",
"symlinks",
"by",
"maintaining",
"a",
"simple",
"iteration",
"limit",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/util.go#L67-L99 | train |
rjeczalik/notify | watcher_trigger.go | newWatcher | func newWatcher(c chan<- EventInfo) watcher {
t := &trg{
s: make(chan struct{}, 1),
pthLkp: make(map[string]*watched, 0),
c: c,
}
t.t = newTrigger(t.pthLkp)
if err := t.t.Init(); err != nil {
t.Close()
return watcherStub{fmt.Errorf("failed setting up watcher: %v", err)}
}
go t.monitor()
return t
} | go | func newWatcher(c chan<- EventInfo) watcher {
t := &trg{
s: make(chan struct{}, 1),
pthLkp: make(map[string]*watched, 0),
c: c,
}
t.t = newTrigger(t.pthLkp)
if err := t.t.Init(); err != nil {
t.Close()
return watcherStub{fmt.Errorf("failed setting up watcher: %v", err)}
}
go t.monitor()
return t
} | [
"func",
"newWatcher",
"(",
"c",
"chan",
"<-",
"EventInfo",
")",
"watcher",
"{",
"t",
":=",
"&",
"trg",
"{",
"s",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
",",
"pthLkp",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"watched",
",",
"0",
")",
",",
"c",
":",
"c",
",",
"}",
"\n",
"t",
".",
"t",
"=",
"newTrigger",
"(",
"t",
".",
"pthLkp",
")",
"\n",
"if",
"err",
":=",
"t",
".",
"t",
".",
"Init",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"t",
".",
"Close",
"(",
")",
"\n",
"return",
"watcherStub",
"{",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"}",
"\n",
"}",
"\n",
"go",
"t",
".",
"monitor",
"(",
")",
"\n",
"return",
"t",
"\n",
"}"
] | // newWatcher returns new watcher's implementation. | [
"newWatcher",
"returns",
"new",
"watcher",
"s",
"implementation",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_trigger.go#L101-L114 | train |
rjeczalik/notify | watcher_trigger.go | Close | func (t *trg) Close() (err error) {
t.Lock()
if err = t.t.Stop(); err != nil {
t.Unlock()
return
}
<-t.s
var e error
for _, w := range t.pthLkp {
if e = t.unwatch(w.p, w.fi); e != nil {
dbgprintf("trg: unwatch %q failed: %q\n", w.p, e)
err = nonil(err, e)
}
}
if e = t.t.Close(); e != nil {
dbgprintf("trg: closing native watch failed: %q\n", e)
err = nonil(err, e)
}
if remaining := len(t.pthLkp); remaining != 0 {
err = nonil(err, fmt.Errorf("Not all watches were removed: len(t.pthLkp) == %v", len(t.pthLkp)))
}
t.Unlock()
return
} | go | func (t *trg) Close() (err error) {
t.Lock()
if err = t.t.Stop(); err != nil {
t.Unlock()
return
}
<-t.s
var e error
for _, w := range t.pthLkp {
if e = t.unwatch(w.p, w.fi); e != nil {
dbgprintf("trg: unwatch %q failed: %q\n", w.p, e)
err = nonil(err, e)
}
}
if e = t.t.Close(); e != nil {
dbgprintf("trg: closing native watch failed: %q\n", e)
err = nonil(err, e)
}
if remaining := len(t.pthLkp); remaining != 0 {
err = nonil(err, fmt.Errorf("Not all watches were removed: len(t.pthLkp) == %v", len(t.pthLkp)))
}
t.Unlock()
return
} | [
"func",
"(",
"t",
"*",
"trg",
")",
"Close",
"(",
")",
"(",
"err",
"error",
")",
"{",
"t",
".",
"Lock",
"(",
")",
"\n",
"if",
"err",
"=",
"t",
".",
"t",
".",
"Stop",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"t",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"<-",
"t",
".",
"s",
"\n",
"var",
"e",
"error",
"\n",
"for",
"_",
",",
"w",
":=",
"range",
"t",
".",
"pthLkp",
"{",
"if",
"e",
"=",
"t",
".",
"unwatch",
"(",
"w",
".",
"p",
",",
"w",
".",
"fi",
")",
";",
"e",
"!=",
"nil",
"{",
"dbgprintf",
"(",
"\"",
"\\n",
"\"",
",",
"w",
".",
"p",
",",
"e",
")",
"\n",
"err",
"=",
"nonil",
"(",
"err",
",",
"e",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"e",
"=",
"t",
".",
"t",
".",
"Close",
"(",
")",
";",
"e",
"!=",
"nil",
"{",
"dbgprintf",
"(",
"\"",
"\\n",
"\"",
",",
"e",
")",
"\n",
"err",
"=",
"nonil",
"(",
"err",
",",
"e",
")",
"\n",
"}",
"\n",
"if",
"remaining",
":=",
"len",
"(",
"t",
".",
"pthLkp",
")",
";",
"remaining",
"!=",
"0",
"{",
"err",
"=",
"nonil",
"(",
"err",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"t",
".",
"pthLkp",
")",
")",
")",
"\n",
"}",
"\n",
"t",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Close implements watcher. | [
"Close",
"implements",
"watcher",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_trigger.go#L117-L140 | train |
rjeczalik/notify | watcher_trigger.go | send | func (t *trg) send(evn []event) {
for i := range evn {
t.c <- &evn[i]
}
} | go | func (t *trg) send(evn []event) {
for i := range evn {
t.c <- &evn[i]
}
} | [
"func",
"(",
"t",
"*",
"trg",
")",
"send",
"(",
"evn",
"[",
"]",
"event",
")",
"{",
"for",
"i",
":=",
"range",
"evn",
"{",
"t",
".",
"c",
"<-",
"&",
"evn",
"[",
"i",
"]",
"\n",
"}",
"\n",
"}"
] | // send reported events one by one through chan. | [
"send",
"reported",
"events",
"one",
"by",
"one",
"through",
"chan",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_trigger.go#L143-L147 | train |
rjeczalik/notify | watcher_trigger.go | Watch | func (t *trg) Watch(p string, e Event) error {
fi, err := os.Stat(p)
if err != nil {
return err
}
t.Lock()
err = t.watch(p, e, fi)
t.Unlock()
return err
} | go | func (t *trg) Watch(p string, e Event) error {
fi, err := os.Stat(p)
if err != nil {
return err
}
t.Lock()
err = t.watch(p, e, fi)
t.Unlock()
return err
} | [
"func",
"(",
"t",
"*",
"trg",
")",
"Watch",
"(",
"p",
"string",
",",
"e",
"Event",
")",
"error",
"{",
"fi",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"t",
".",
"Lock",
"(",
")",
"\n",
"err",
"=",
"t",
".",
"watch",
"(",
"p",
",",
"e",
",",
"fi",
")",
"\n",
"t",
".",
"Unlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Watch implements Watcher interface. | [
"Watch",
"implements",
"Watcher",
"interface",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_trigger.go#L252-L261 | train |
rjeczalik/notify | watcher_trigger.go | Unwatch | func (t *trg) Unwatch(p string) error {
fi, err := os.Stat(p)
if err != nil {
return err
}
t.Lock()
err = t.unwatch(p, fi)
t.Unlock()
return err
} | go | func (t *trg) Unwatch(p string) error {
fi, err := os.Stat(p)
if err != nil {
return err
}
t.Lock()
err = t.unwatch(p, fi)
t.Unlock()
return err
} | [
"func",
"(",
"t",
"*",
"trg",
")",
"Unwatch",
"(",
"p",
"string",
")",
"error",
"{",
"fi",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"t",
".",
"Lock",
"(",
")",
"\n",
"err",
"=",
"t",
".",
"unwatch",
"(",
"p",
",",
"fi",
")",
"\n",
"t",
".",
"Unlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Unwatch implements Watcher interface. | [
"Unwatch",
"implements",
"Watcher",
"interface",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_trigger.go#L264-L273 | train |
rjeczalik/notify | watcher_trigger.go | process | func (t *trg) process(n interface{}) (evn []event) {
t.Lock()
w, ge, err := t.t.Watched(n)
if err != nil {
t.Unlock()
dbgprintf("trg: %v event lookup failed: %q", Event(ge), err)
return
}
e := decode(ge, w.eDir|w.eNonDir)
if ge&int64(not2nat[Remove]|not2nat[Rename]) == 0 {
switch fi, err := os.Stat(w.p); {
case err != nil:
default:
if err = t.t.Watch(fi, w, encode(w.eDir|w.eNonDir, fi.IsDir())); err != nil {
dbgprintf("trg: %q is no longer watched: %q", w.p, err)
t.t.Del(w)
}
}
}
if e == Event(0) && (!w.fi.IsDir() || (ge&int64(not2nat[Write])) == 0) {
t.Unlock()
return
}
if w.fi.IsDir() {
evn = append(evn, t.dir(w, n, e, Event(ge))...)
} else {
evn = append(evn, t.file(w, n, e)...)
}
if Event(ge)&(not2nat[Remove]|not2nat[Rename]) != 0 {
t.t.Del(w)
}
t.Unlock()
return
} | go | func (t *trg) process(n interface{}) (evn []event) {
t.Lock()
w, ge, err := t.t.Watched(n)
if err != nil {
t.Unlock()
dbgprintf("trg: %v event lookup failed: %q", Event(ge), err)
return
}
e := decode(ge, w.eDir|w.eNonDir)
if ge&int64(not2nat[Remove]|not2nat[Rename]) == 0 {
switch fi, err := os.Stat(w.p); {
case err != nil:
default:
if err = t.t.Watch(fi, w, encode(w.eDir|w.eNonDir, fi.IsDir())); err != nil {
dbgprintf("trg: %q is no longer watched: %q", w.p, err)
t.t.Del(w)
}
}
}
if e == Event(0) && (!w.fi.IsDir() || (ge&int64(not2nat[Write])) == 0) {
t.Unlock()
return
}
if w.fi.IsDir() {
evn = append(evn, t.dir(w, n, e, Event(ge))...)
} else {
evn = append(evn, t.file(w, n, e)...)
}
if Event(ge)&(not2nat[Remove]|not2nat[Rename]) != 0 {
t.t.Del(w)
}
t.Unlock()
return
} | [
"func",
"(",
"t",
"*",
"trg",
")",
"process",
"(",
"n",
"interface",
"{",
"}",
")",
"(",
"evn",
"[",
"]",
"event",
")",
"{",
"t",
".",
"Lock",
"(",
")",
"\n",
"w",
",",
"ge",
",",
"err",
":=",
"t",
".",
"t",
".",
"Watched",
"(",
"n",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"t",
".",
"Unlock",
"(",
")",
"\n",
"dbgprintf",
"(",
"\"",
"\"",
",",
"Event",
"(",
"ge",
")",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"e",
":=",
"decode",
"(",
"ge",
",",
"w",
".",
"eDir",
"|",
"w",
".",
"eNonDir",
")",
"\n",
"if",
"ge",
"&",
"int64",
"(",
"not2nat",
"[",
"Remove",
"]",
"|",
"not2nat",
"[",
"Rename",
"]",
")",
"==",
"0",
"{",
"switch",
"fi",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"w",
".",
"p",
")",
";",
"{",
"case",
"err",
"!=",
"nil",
":",
"default",
":",
"if",
"err",
"=",
"t",
".",
"t",
".",
"Watch",
"(",
"fi",
",",
"w",
",",
"encode",
"(",
"w",
".",
"eDir",
"|",
"w",
".",
"eNonDir",
",",
"fi",
".",
"IsDir",
"(",
")",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"dbgprintf",
"(",
"\"",
"\"",
",",
"w",
".",
"p",
",",
"err",
")",
"\n",
"t",
".",
"t",
".",
"Del",
"(",
"w",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"e",
"==",
"Event",
"(",
"0",
")",
"&&",
"(",
"!",
"w",
".",
"fi",
".",
"IsDir",
"(",
")",
"||",
"(",
"ge",
"&",
"int64",
"(",
"not2nat",
"[",
"Write",
"]",
")",
")",
"==",
"0",
")",
"{",
"t",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"w",
".",
"fi",
".",
"IsDir",
"(",
")",
"{",
"evn",
"=",
"append",
"(",
"evn",
",",
"t",
".",
"dir",
"(",
"w",
",",
"n",
",",
"e",
",",
"Event",
"(",
"ge",
")",
")",
"...",
")",
"\n",
"}",
"else",
"{",
"evn",
"=",
"append",
"(",
"evn",
",",
"t",
".",
"file",
"(",
"w",
",",
"n",
",",
"e",
")",
"...",
")",
"\n",
"}",
"\n",
"if",
"Event",
"(",
"ge",
")",
"&",
"(",
"not2nat",
"[",
"Remove",
"]",
"|",
"not2nat",
"[",
"Rename",
"]",
")",
"!=",
"0",
"{",
"t",
".",
"t",
".",
"Del",
"(",
"w",
")",
"\n",
"}",
"\n",
"t",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // process event returned by native call. | [
"process",
"event",
"returned",
"by",
"native",
"call",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_trigger.go#L415-L450 | train |
rjeczalik/notify | watcher_inotify.go | newWatcher | func newWatcher(c chan<- EventInfo) watcher {
i := &inotify{
m: make(map[int32]*watched),
fd: invalidDescriptor,
pipefd: []int{invalidDescriptor, invalidDescriptor},
epfd: invalidDescriptor,
epes: make([]unix.EpollEvent, 0),
c: c,
}
runtime.SetFinalizer(i, func(i *inotify) {
i.epollclose()
if i.fd != invalidDescriptor {
unix.Close(int(i.fd))
}
})
return i
} | go | func newWatcher(c chan<- EventInfo) watcher {
i := &inotify{
m: make(map[int32]*watched),
fd: invalidDescriptor,
pipefd: []int{invalidDescriptor, invalidDescriptor},
epfd: invalidDescriptor,
epes: make([]unix.EpollEvent, 0),
c: c,
}
runtime.SetFinalizer(i, func(i *inotify) {
i.epollclose()
if i.fd != invalidDescriptor {
unix.Close(int(i.fd))
}
})
return i
} | [
"func",
"newWatcher",
"(",
"c",
"chan",
"<-",
"EventInfo",
")",
"watcher",
"{",
"i",
":=",
"&",
"inotify",
"{",
"m",
":",
"make",
"(",
"map",
"[",
"int32",
"]",
"*",
"watched",
")",
",",
"fd",
":",
"invalidDescriptor",
",",
"pipefd",
":",
"[",
"]",
"int",
"{",
"invalidDescriptor",
",",
"invalidDescriptor",
"}",
",",
"epfd",
":",
"invalidDescriptor",
",",
"epes",
":",
"make",
"(",
"[",
"]",
"unix",
".",
"EpollEvent",
",",
"0",
")",
",",
"c",
":",
"c",
",",
"}",
"\n",
"runtime",
".",
"SetFinalizer",
"(",
"i",
",",
"func",
"(",
"i",
"*",
"inotify",
")",
"{",
"i",
".",
"epollclose",
"(",
")",
"\n",
"if",
"i",
".",
"fd",
"!=",
"invalidDescriptor",
"{",
"unix",
".",
"Close",
"(",
"int",
"(",
"i",
".",
"fd",
")",
")",
"\n",
"}",
"\n",
"}",
")",
"\n",
"return",
"i",
"\n",
"}"
] | // NewWatcher creates new non-recursive inotify backed by inotify. | [
"NewWatcher",
"creates",
"new",
"non",
"-",
"recursive",
"inotify",
"backed",
"by",
"inotify",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_inotify.go#L54-L70 | train |
rjeczalik/notify | watcher_inotify.go | Watch | func (i *inotify) Watch(path string, e Event) error {
return i.watch(path, e)
} | go | func (i *inotify) Watch(path string, e Event) error {
return i.watch(path, e)
} | [
"func",
"(",
"i",
"*",
"inotify",
")",
"Watch",
"(",
"path",
"string",
",",
"e",
"Event",
")",
"error",
"{",
"return",
"i",
".",
"watch",
"(",
"path",
",",
"e",
")",
"\n",
"}"
] | // Watch implements notify.watcher interface. | [
"Watch",
"implements",
"notify",
".",
"watcher",
"interface",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_inotify.go#L73-L75 | train |
rjeczalik/notify | watcher_inotify.go | Rewatch | func (i *inotify) Rewatch(path string, _, newevent Event) error {
return i.watch(path, newevent)
} | go | func (i *inotify) Rewatch(path string, _, newevent Event) error {
return i.watch(path, newevent)
} | [
"func",
"(",
"i",
"*",
"inotify",
")",
"Rewatch",
"(",
"path",
"string",
",",
"_",
",",
"newevent",
"Event",
")",
"error",
"{",
"return",
"i",
".",
"watch",
"(",
"path",
",",
"newevent",
")",
"\n",
"}"
] | // Rewatch implements notify.watcher interface. | [
"Rewatch",
"implements",
"notify",
".",
"watcher",
"interface",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_inotify.go#L78-L80 | train |
rjeczalik/notify | watcher_inotify.go | watch | func (i *inotify) watch(path string, e Event) (err error) {
if e&^(All|Event(unix.IN_ALL_EVENTS)) != 0 {
return errors.New("notify: unknown event")
}
if err = i.lazyinit(); err != nil {
return
}
iwd, err := unix.InotifyAddWatch(int(i.fd), path, encode(e))
if err != nil {
return
}
i.RLock()
wd := i.m[int32(iwd)]
i.RUnlock()
if wd == nil {
i.Lock()
if i.m[int32(iwd)] == nil {
i.m[int32(iwd)] = &watched{path: path, mask: uint32(e)}
}
i.Unlock()
} else {
i.Lock()
wd.mask = uint32(e)
i.Unlock()
}
return nil
} | go | func (i *inotify) watch(path string, e Event) (err error) {
if e&^(All|Event(unix.IN_ALL_EVENTS)) != 0 {
return errors.New("notify: unknown event")
}
if err = i.lazyinit(); err != nil {
return
}
iwd, err := unix.InotifyAddWatch(int(i.fd), path, encode(e))
if err != nil {
return
}
i.RLock()
wd := i.m[int32(iwd)]
i.RUnlock()
if wd == nil {
i.Lock()
if i.m[int32(iwd)] == nil {
i.m[int32(iwd)] = &watched{path: path, mask: uint32(e)}
}
i.Unlock()
} else {
i.Lock()
wd.mask = uint32(e)
i.Unlock()
}
return nil
} | [
"func",
"(",
"i",
"*",
"inotify",
")",
"watch",
"(",
"path",
"string",
",",
"e",
"Event",
")",
"(",
"err",
"error",
")",
"{",
"if",
"e",
"&^",
"(",
"All",
"|",
"Event",
"(",
"unix",
".",
"IN_ALL_EVENTS",
")",
")",
"!=",
"0",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"err",
"=",
"i",
".",
"lazyinit",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"iwd",
",",
"err",
":=",
"unix",
".",
"InotifyAddWatch",
"(",
"int",
"(",
"i",
".",
"fd",
")",
",",
"path",
",",
"encode",
"(",
"e",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"i",
".",
"RLock",
"(",
")",
"\n",
"wd",
":=",
"i",
".",
"m",
"[",
"int32",
"(",
"iwd",
")",
"]",
"\n",
"i",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"wd",
"==",
"nil",
"{",
"i",
".",
"Lock",
"(",
")",
"\n",
"if",
"i",
".",
"m",
"[",
"int32",
"(",
"iwd",
")",
"]",
"==",
"nil",
"{",
"i",
".",
"m",
"[",
"int32",
"(",
"iwd",
")",
"]",
"=",
"&",
"watched",
"{",
"path",
":",
"path",
",",
"mask",
":",
"uint32",
"(",
"e",
")",
"}",
"\n",
"}",
"\n",
"i",
".",
"Unlock",
"(",
")",
"\n",
"}",
"else",
"{",
"i",
".",
"Lock",
"(",
")",
"\n",
"wd",
".",
"mask",
"=",
"uint32",
"(",
"e",
")",
"\n",
"i",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // watch adds a new watcher to the set of watched objects or modifies the existing
// one. If called for the first time, this function initializes inotify filesystem
// monitor and starts producer-consumers goroutines. | [
"watch",
"adds",
"a",
"new",
"watcher",
"to",
"the",
"set",
"of",
"watched",
"objects",
"or",
"modifies",
"the",
"existing",
"one",
".",
"If",
"called",
"for",
"the",
"first",
"time",
"this",
"function",
"initializes",
"inotify",
"filesystem",
"monitor",
"and",
"starts",
"producer",
"-",
"consumers",
"goroutines",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_inotify.go#L85-L111 | train |
rjeczalik/notify | watcher_inotify.go | lazyinit | func (i *inotify) lazyinit() error {
if atomic.LoadInt32(&i.fd) == invalidDescriptor {
i.Lock()
defer i.Unlock()
if atomic.LoadInt32(&i.fd) == invalidDescriptor {
fd, err := unix.InotifyInit1(unix.IN_CLOEXEC)
if err != nil {
return err
}
i.fd = int32(fd)
if err = i.epollinit(); err != nil {
_, _ = i.epollclose(), unix.Close(int(fd)) // Ignore errors.
i.fd = invalidDescriptor
return err
}
esch := make(chan []*event)
go i.loop(esch)
i.wg.Add(consumersCount)
for n := 0; n < consumersCount; n++ {
go i.send(esch)
}
}
}
return nil
} | go | func (i *inotify) lazyinit() error {
if atomic.LoadInt32(&i.fd) == invalidDescriptor {
i.Lock()
defer i.Unlock()
if atomic.LoadInt32(&i.fd) == invalidDescriptor {
fd, err := unix.InotifyInit1(unix.IN_CLOEXEC)
if err != nil {
return err
}
i.fd = int32(fd)
if err = i.epollinit(); err != nil {
_, _ = i.epollclose(), unix.Close(int(fd)) // Ignore errors.
i.fd = invalidDescriptor
return err
}
esch := make(chan []*event)
go i.loop(esch)
i.wg.Add(consumersCount)
for n := 0; n < consumersCount; n++ {
go i.send(esch)
}
}
}
return nil
} | [
"func",
"(",
"i",
"*",
"inotify",
")",
"lazyinit",
"(",
")",
"error",
"{",
"if",
"atomic",
".",
"LoadInt32",
"(",
"&",
"i",
".",
"fd",
")",
"==",
"invalidDescriptor",
"{",
"i",
".",
"Lock",
"(",
")",
"\n",
"defer",
"i",
".",
"Unlock",
"(",
")",
"\n",
"if",
"atomic",
".",
"LoadInt32",
"(",
"&",
"i",
".",
"fd",
")",
"==",
"invalidDescriptor",
"{",
"fd",
",",
"err",
":=",
"unix",
".",
"InotifyInit1",
"(",
"unix",
".",
"IN_CLOEXEC",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"i",
".",
"fd",
"=",
"int32",
"(",
"fd",
")",
"\n",
"if",
"err",
"=",
"i",
".",
"epollinit",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"_",
",",
"_",
"=",
"i",
".",
"epollclose",
"(",
")",
",",
"unix",
".",
"Close",
"(",
"int",
"(",
"fd",
")",
")",
"// Ignore errors.",
"\n",
"i",
".",
"fd",
"=",
"invalidDescriptor",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"esch",
":=",
"make",
"(",
"chan",
"[",
"]",
"*",
"event",
")",
"\n",
"go",
"i",
".",
"loop",
"(",
"esch",
")",
"\n",
"i",
".",
"wg",
".",
"Add",
"(",
"consumersCount",
")",
"\n",
"for",
"n",
":=",
"0",
";",
"n",
"<",
"consumersCount",
";",
"n",
"++",
"{",
"go",
"i",
".",
"send",
"(",
"esch",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // lazyinit sets up all required file descriptors and starts 1+consumersCount
// goroutines. The producer goroutine blocks until file-system notifications
// occur. Then, all events are read from system buffer and sent to consumer
// goroutines which construct valid notify events. This method uses
// Double-Checked Locking optimization. | [
"lazyinit",
"sets",
"up",
"all",
"required",
"file",
"descriptors",
"and",
"starts",
"1",
"+",
"consumersCount",
"goroutines",
".",
"The",
"producer",
"goroutine",
"blocks",
"until",
"file",
"-",
"system",
"notifications",
"occur",
".",
"Then",
"all",
"events",
"are",
"read",
"from",
"system",
"buffer",
"and",
"sent",
"to",
"consumer",
"goroutines",
"which",
"construct",
"valid",
"notify",
"events",
".",
"This",
"method",
"uses",
"Double",
"-",
"Checked",
"Locking",
"optimization",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_inotify.go#L118-L142 | train |
rjeczalik/notify | watcher_inotify.go | send | func (i *inotify) send(esch <-chan []*event) {
for es := range esch {
for _, e := range i.transform(es) {
if e != nil {
i.c <- e
}
}
}
i.wg.Done()
} | go | func (i *inotify) send(esch <-chan []*event) {
for es := range esch {
for _, e := range i.transform(es) {
if e != nil {
i.c <- e
}
}
}
i.wg.Done()
} | [
"func",
"(",
"i",
"*",
"inotify",
")",
"send",
"(",
"esch",
"<-",
"chan",
"[",
"]",
"*",
"event",
")",
"{",
"for",
"es",
":=",
"range",
"esch",
"{",
"for",
"_",
",",
"e",
":=",
"range",
"i",
".",
"transform",
"(",
"es",
")",
"{",
"if",
"e",
"!=",
"nil",
"{",
"i",
".",
"c",
"<-",
"e",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"i",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"}"
] | // send is a consumer function which sends events to event dispatcher channel.
// It is run in a separate goroutine in order to not block loop method when
// possibly expensive write operations are performed on inotify map. | [
"send",
"is",
"a",
"consumer",
"function",
"which",
"sends",
"events",
"to",
"event",
"dispatcher",
"channel",
".",
"It",
"is",
"run",
"in",
"a",
"separate",
"goroutine",
"in",
"order",
"to",
"not",
"block",
"loop",
"method",
"when",
"possibly",
"expensive",
"write",
"operations",
"are",
"performed",
"on",
"inotify",
"map",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_inotify.go#L253-L262 | train |
rjeczalik/notify | watcher_inotify.go | transform | func (i *inotify) transform(es []*event) []*event {
var multi []*event
i.RLock()
for idx, e := range es {
if e.sys.Mask&(unix.IN_IGNORED|unix.IN_Q_OVERFLOW) != 0 {
es[idx] = nil
continue
}
wd, ok := i.m[e.sys.Wd]
if !ok || e.sys.Mask&encode(Event(wd.mask)) == 0 {
es[idx] = nil
continue
}
if e.path == "" {
e.path = wd.path
} else {
e.path = filepath.Join(wd.path, e.path)
}
multi = append(multi, decode(Event(wd.mask), e))
if e.event == 0 {
es[idx] = nil
}
}
i.RUnlock()
es = append(es, multi...)
return es
} | go | func (i *inotify) transform(es []*event) []*event {
var multi []*event
i.RLock()
for idx, e := range es {
if e.sys.Mask&(unix.IN_IGNORED|unix.IN_Q_OVERFLOW) != 0 {
es[idx] = nil
continue
}
wd, ok := i.m[e.sys.Wd]
if !ok || e.sys.Mask&encode(Event(wd.mask)) == 0 {
es[idx] = nil
continue
}
if e.path == "" {
e.path = wd.path
} else {
e.path = filepath.Join(wd.path, e.path)
}
multi = append(multi, decode(Event(wd.mask), e))
if e.event == 0 {
es[idx] = nil
}
}
i.RUnlock()
es = append(es, multi...)
return es
} | [
"func",
"(",
"i",
"*",
"inotify",
")",
"transform",
"(",
"es",
"[",
"]",
"*",
"event",
")",
"[",
"]",
"*",
"event",
"{",
"var",
"multi",
"[",
"]",
"*",
"event",
"\n",
"i",
".",
"RLock",
"(",
")",
"\n",
"for",
"idx",
",",
"e",
":=",
"range",
"es",
"{",
"if",
"e",
".",
"sys",
".",
"Mask",
"&",
"(",
"unix",
".",
"IN_IGNORED",
"|",
"unix",
".",
"IN_Q_OVERFLOW",
")",
"!=",
"0",
"{",
"es",
"[",
"idx",
"]",
"=",
"nil",
"\n",
"continue",
"\n",
"}",
"\n",
"wd",
",",
"ok",
":=",
"i",
".",
"m",
"[",
"e",
".",
"sys",
".",
"Wd",
"]",
"\n",
"if",
"!",
"ok",
"||",
"e",
".",
"sys",
".",
"Mask",
"&",
"encode",
"(",
"Event",
"(",
"wd",
".",
"mask",
")",
")",
"==",
"0",
"{",
"es",
"[",
"idx",
"]",
"=",
"nil",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"e",
".",
"path",
"==",
"\"",
"\"",
"{",
"e",
".",
"path",
"=",
"wd",
".",
"path",
"\n",
"}",
"else",
"{",
"e",
".",
"path",
"=",
"filepath",
".",
"Join",
"(",
"wd",
".",
"path",
",",
"e",
".",
"path",
")",
"\n",
"}",
"\n",
"multi",
"=",
"append",
"(",
"multi",
",",
"decode",
"(",
"Event",
"(",
"wd",
".",
"mask",
")",
",",
"e",
")",
")",
"\n",
"if",
"e",
".",
"event",
"==",
"0",
"{",
"es",
"[",
"idx",
"]",
"=",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"i",
".",
"RUnlock",
"(",
")",
"\n",
"es",
"=",
"append",
"(",
"es",
",",
"multi",
"...",
")",
"\n",
"return",
"es",
"\n",
"}"
] | // transform prepares events read from inotify file descriptor for sending to
// user. It removes invalid events and these which are no longer present in
// inotify map. This method may also split one raw event into two different ones
// when system-dependent result is required. | [
"transform",
"prepares",
"events",
"read",
"from",
"inotify",
"file",
"descriptor",
"for",
"sending",
"to",
"user",
".",
"It",
"removes",
"invalid",
"events",
"and",
"these",
"which",
"are",
"no",
"longer",
"present",
"in",
"inotify",
"map",
".",
"This",
"method",
"may",
"also",
"split",
"one",
"raw",
"event",
"into",
"two",
"different",
"ones",
"when",
"system",
"-",
"dependent",
"result",
"is",
"required",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_inotify.go#L268-L294 | train |
rjeczalik/notify | watcher_inotify.go | decode | func decode(mask Event, e *event) (syse *event) {
if sysmask := uint32(mask) & e.sys.Mask; sysmask != 0 {
syse = &event{sys: unix.InotifyEvent{
Wd: e.sys.Wd,
Mask: e.sys.Mask,
Cookie: e.sys.Cookie,
}, event: Event(sysmask), path: e.path}
}
imask := encode(mask)
switch {
case mask&Create != 0 && imask&uint32(InCreate|InMovedTo)&e.sys.Mask != 0:
e.event = Create
case mask&Remove != 0 && imask&uint32(InDelete|InDeleteSelf)&e.sys.Mask != 0:
e.event = Remove
case mask&Write != 0 && imask&uint32(InModify)&e.sys.Mask != 0:
e.event = Write
case mask&Rename != 0 && imask&uint32(InMovedFrom|InMoveSelf)&e.sys.Mask != 0:
e.event = Rename
default:
e.event = 0
}
return
} | go | func decode(mask Event, e *event) (syse *event) {
if sysmask := uint32(mask) & e.sys.Mask; sysmask != 0 {
syse = &event{sys: unix.InotifyEvent{
Wd: e.sys.Wd,
Mask: e.sys.Mask,
Cookie: e.sys.Cookie,
}, event: Event(sysmask), path: e.path}
}
imask := encode(mask)
switch {
case mask&Create != 0 && imask&uint32(InCreate|InMovedTo)&e.sys.Mask != 0:
e.event = Create
case mask&Remove != 0 && imask&uint32(InDelete|InDeleteSelf)&e.sys.Mask != 0:
e.event = Remove
case mask&Write != 0 && imask&uint32(InModify)&e.sys.Mask != 0:
e.event = Write
case mask&Rename != 0 && imask&uint32(InMovedFrom|InMoveSelf)&e.sys.Mask != 0:
e.event = Rename
default:
e.event = 0
}
return
} | [
"func",
"decode",
"(",
"mask",
"Event",
",",
"e",
"*",
"event",
")",
"(",
"syse",
"*",
"event",
")",
"{",
"if",
"sysmask",
":=",
"uint32",
"(",
"mask",
")",
"&",
"e",
".",
"sys",
".",
"Mask",
";",
"sysmask",
"!=",
"0",
"{",
"syse",
"=",
"&",
"event",
"{",
"sys",
":",
"unix",
".",
"InotifyEvent",
"{",
"Wd",
":",
"e",
".",
"sys",
".",
"Wd",
",",
"Mask",
":",
"e",
".",
"sys",
".",
"Mask",
",",
"Cookie",
":",
"e",
".",
"sys",
".",
"Cookie",
",",
"}",
",",
"event",
":",
"Event",
"(",
"sysmask",
")",
",",
"path",
":",
"e",
".",
"path",
"}",
"\n",
"}",
"\n",
"imask",
":=",
"encode",
"(",
"mask",
")",
"\n",
"switch",
"{",
"case",
"mask",
"&",
"Create",
"!=",
"0",
"&&",
"imask",
"&",
"uint32",
"(",
"InCreate",
"|",
"InMovedTo",
")",
"&",
"e",
".",
"sys",
".",
"Mask",
"!=",
"0",
":",
"e",
".",
"event",
"=",
"Create",
"\n",
"case",
"mask",
"&",
"Remove",
"!=",
"0",
"&&",
"imask",
"&",
"uint32",
"(",
"InDelete",
"|",
"InDeleteSelf",
")",
"&",
"e",
".",
"sys",
".",
"Mask",
"!=",
"0",
":",
"e",
".",
"event",
"=",
"Remove",
"\n",
"case",
"mask",
"&",
"Write",
"!=",
"0",
"&&",
"imask",
"&",
"uint32",
"(",
"InModify",
")",
"&",
"e",
".",
"sys",
".",
"Mask",
"!=",
"0",
":",
"e",
".",
"event",
"=",
"Write",
"\n",
"case",
"mask",
"&",
"Rename",
"!=",
"0",
"&&",
"imask",
"&",
"uint32",
"(",
"InMovedFrom",
"|",
"InMoveSelf",
")",
"&",
"e",
".",
"sys",
".",
"Mask",
"!=",
"0",
":",
"e",
".",
"event",
"=",
"Rename",
"\n",
"default",
":",
"e",
".",
"event",
"=",
"0",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // decode uses internally stored mask to distinguish whether system-independent
// or system-dependent event is requested. The first one is created by modifying
// `e` argument. decode method sets e.event value to 0 when an event should be
// skipped. System-dependent event is set as the function's return value which
// can be nil when the event should not be passed on. | [
"decode",
"uses",
"internally",
"stored",
"mask",
"to",
"distinguish",
"whether",
"system",
"-",
"independent",
"or",
"system",
"-",
"dependent",
"event",
"is",
"requested",
".",
"The",
"first",
"one",
"is",
"created",
"by",
"modifying",
"e",
"argument",
".",
"decode",
"method",
"sets",
"e",
".",
"event",
"value",
"to",
"0",
"when",
"an",
"event",
"should",
"be",
"skipped",
".",
"System",
"-",
"dependent",
"event",
"is",
"set",
"as",
"the",
"function",
"s",
"return",
"value",
"which",
"can",
"be",
"nil",
"when",
"the",
"event",
"should",
"not",
"be",
"passed",
"on",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_inotify.go#L319-L341 | train |
rjeczalik/notify | watcher_inotify.go | Close | func (i *inotify) Close() (err error) {
i.Lock()
if fd := atomic.LoadInt32(&i.fd); fd == invalidDescriptor {
i.Unlock()
return nil
}
for iwd := range i.m {
if e := removeInotifyWatch(i.fd, iwd); e != nil && err == nil {
err = e
}
delete(i.m, iwd)
}
switch _, errwrite := unix.Write(i.pipefd[1], []byte{0x00}); {
case errwrite != nil && err == nil:
err = errwrite
fallthrough
case errwrite != nil:
i.Unlock()
default:
i.Unlock()
i.wg.Wait()
}
return
} | go | func (i *inotify) Close() (err error) {
i.Lock()
if fd := atomic.LoadInt32(&i.fd); fd == invalidDescriptor {
i.Unlock()
return nil
}
for iwd := range i.m {
if e := removeInotifyWatch(i.fd, iwd); e != nil && err == nil {
err = e
}
delete(i.m, iwd)
}
switch _, errwrite := unix.Write(i.pipefd[1], []byte{0x00}); {
case errwrite != nil && err == nil:
err = errwrite
fallthrough
case errwrite != nil:
i.Unlock()
default:
i.Unlock()
i.wg.Wait()
}
return
} | [
"func",
"(",
"i",
"*",
"inotify",
")",
"Close",
"(",
")",
"(",
"err",
"error",
")",
"{",
"i",
".",
"Lock",
"(",
")",
"\n",
"if",
"fd",
":=",
"atomic",
".",
"LoadInt32",
"(",
"&",
"i",
".",
"fd",
")",
";",
"fd",
"==",
"invalidDescriptor",
"{",
"i",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"for",
"iwd",
":=",
"range",
"i",
".",
"m",
"{",
"if",
"e",
":=",
"removeInotifyWatch",
"(",
"i",
".",
"fd",
",",
"iwd",
")",
";",
"e",
"!=",
"nil",
"&&",
"err",
"==",
"nil",
"{",
"err",
"=",
"e",
"\n",
"}",
"\n",
"delete",
"(",
"i",
".",
"m",
",",
"iwd",
")",
"\n",
"}",
"\n",
"switch",
"_",
",",
"errwrite",
":=",
"unix",
".",
"Write",
"(",
"i",
".",
"pipefd",
"[",
"1",
"]",
",",
"[",
"]",
"byte",
"{",
"0x00",
"}",
")",
";",
"{",
"case",
"errwrite",
"!=",
"nil",
"&&",
"err",
"==",
"nil",
":",
"err",
"=",
"errwrite",
"\n",
"fallthrough",
"\n",
"case",
"errwrite",
"!=",
"nil",
":",
"i",
".",
"Unlock",
"(",
")",
"\n",
"default",
":",
"i",
".",
"Unlock",
"(",
")",
"\n",
"i",
".",
"wg",
".",
"Wait",
"(",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Close implements notify.watcher interface. It removes all existing watch
// descriptors and wakes up producer goroutine by sending data to the write end
// of the pipe. The function waits for a signal from producer which means that
// all operations on current monitoring instance are done. | [
"Close",
"implements",
"notify",
".",
"watcher",
"interface",
".",
"It",
"removes",
"all",
"existing",
"watch",
"descriptors",
"and",
"wakes",
"up",
"producer",
"goroutine",
"by",
"sending",
"data",
"to",
"the",
"write",
"end",
"of",
"the",
"pipe",
".",
"The",
"function",
"waits",
"for",
"a",
"signal",
"from",
"producer",
"which",
"means",
"that",
"all",
"operations",
"on",
"current",
"monitoring",
"instance",
"are",
"done",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_inotify.go#L374-L397 | train |
rjeczalik/notify | watcher_inotify.go | removeInotifyWatch | func removeInotifyWatch(fd int32, iwd int32) (err error) {
if _, err = unix.InotifyRmWatch(int(fd), uint32(iwd)); err != nil && err != unix.EINVAL {
return
}
return nil
} | go | func removeInotifyWatch(fd int32, iwd int32) (err error) {
if _, err = unix.InotifyRmWatch(int(fd), uint32(iwd)); err != nil && err != unix.EINVAL {
return
}
return nil
} | [
"func",
"removeInotifyWatch",
"(",
"fd",
"int32",
",",
"iwd",
"int32",
")",
"(",
"err",
"error",
")",
"{",
"if",
"_",
",",
"err",
"=",
"unix",
".",
"InotifyRmWatch",
"(",
"int",
"(",
"fd",
")",
",",
"uint32",
"(",
"iwd",
")",
")",
";",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"unix",
".",
"EINVAL",
"{",
"return",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // if path was removed, notify already removed the watch and returns EINVAL error | [
"if",
"path",
"was",
"removed",
"notify",
"already",
"removed",
"the",
"watch",
"and",
"returns",
"EINVAL",
"error"
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_inotify.go#L400-L405 | train |
rjeczalik/notify | watcher_kqueue.go | Stop | func (k *kq) Stop() (err error) {
// trigger event used to interrupt Kevent call.
_, err = syscall.Write(k.pipefds[1], []byte{0x00})
return
} | go | func (k *kq) Stop() (err error) {
// trigger event used to interrupt Kevent call.
_, err = syscall.Write(k.pipefds[1], []byte{0x00})
return
} | [
"func",
"(",
"k",
"*",
"kq",
")",
"Stop",
"(",
")",
"(",
"err",
"error",
")",
"{",
"// trigger event used to interrupt Kevent call.",
"_",
",",
"err",
"=",
"syscall",
".",
"Write",
"(",
"k",
".",
"pipefds",
"[",
"1",
"]",
",",
"[",
"]",
"byte",
"{",
"0x00",
"}",
")",
"\n",
"return",
"\n",
"}"
] | // Stop implements trigger. | [
"Stop",
"implements",
"trigger",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_kqueue.go#L45-L49 | train |
rjeczalik/notify | watcher_kqueue.go | Init | func (k *kq) Init() (err error) {
if k.fd, err = syscall.Kqueue(); err != nil {
return
}
// Creates pipe used to stop `Kevent` call by registering it,
// watching read end and writing to other end of it.
if err = syscall.Pipe(k.pipefds[:]); err != nil {
return nonil(err, k.Close())
}
var kevn [1]syscall.Kevent_t
syscall.SetKevent(&kevn[0], k.pipefds[0], syscall.EVFILT_READ, syscall.EV_ADD)
if _, err = syscall.Kevent(k.fd, kevn[:], nil, nil); err != nil {
return nonil(err, k.Close())
}
return
} | go | func (k *kq) Init() (err error) {
if k.fd, err = syscall.Kqueue(); err != nil {
return
}
// Creates pipe used to stop `Kevent` call by registering it,
// watching read end and writing to other end of it.
if err = syscall.Pipe(k.pipefds[:]); err != nil {
return nonil(err, k.Close())
}
var kevn [1]syscall.Kevent_t
syscall.SetKevent(&kevn[0], k.pipefds[0], syscall.EVFILT_READ, syscall.EV_ADD)
if _, err = syscall.Kevent(k.fd, kevn[:], nil, nil); err != nil {
return nonil(err, k.Close())
}
return
} | [
"func",
"(",
"k",
"*",
"kq",
")",
"Init",
"(",
")",
"(",
"err",
"error",
")",
"{",
"if",
"k",
".",
"fd",
",",
"err",
"=",
"syscall",
".",
"Kqueue",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"// Creates pipe used to stop `Kevent` call by registering it,",
"// watching read end and writing to other end of it.",
"if",
"err",
"=",
"syscall",
".",
"Pipe",
"(",
"k",
".",
"pipefds",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nonil",
"(",
"err",
",",
"k",
".",
"Close",
"(",
")",
")",
"\n",
"}",
"\n",
"var",
"kevn",
"[",
"1",
"]",
"syscall",
".",
"Kevent_t",
"\n",
"syscall",
".",
"SetKevent",
"(",
"&",
"kevn",
"[",
"0",
"]",
",",
"k",
".",
"pipefds",
"[",
"0",
"]",
",",
"syscall",
".",
"EVFILT_READ",
",",
"syscall",
".",
"EV_ADD",
")",
"\n",
"if",
"_",
",",
"err",
"=",
"syscall",
".",
"Kevent",
"(",
"k",
".",
"fd",
",",
"kevn",
"[",
":",
"]",
",",
"nil",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nonil",
"(",
"err",
",",
"k",
".",
"Close",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Init implements trigger. | [
"Init",
"implements",
"trigger",
"."
] | 629144ba06a1c6af28c1e42c228e3d42594ce081 | https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_kqueue.go#L89-L104 | train |
adjust/rmq | redis_wrapper.go | checkErr | func checkErr(err error) (ok bool) {
switch err {
case nil:
return true
case redis.Nil:
return false
default:
log.Panicf("rmq redis error is not nil %s", err)
return false
}
} | go | func checkErr(err error) (ok bool) {
switch err {
case nil:
return true
case redis.Nil:
return false
default:
log.Panicf("rmq redis error is not nil %s", err)
return false
}
} | [
"func",
"checkErr",
"(",
"err",
"error",
")",
"(",
"ok",
"bool",
")",
"{",
"switch",
"err",
"{",
"case",
"nil",
":",
"return",
"true",
"\n",
"case",
"redis",
".",
"Nil",
":",
"return",
"false",
"\n",
"default",
":",
"log",
".",
"Panicf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"}"
] | // checkErr returns true if there is no error, false if the result error is nil and panics if there's another error | [
"checkErr",
"returns",
"true",
"if",
"there",
"is",
"no",
"error",
"false",
"if",
"the",
"result",
"error",
"is",
"nil",
"and",
"panics",
"if",
"there",
"s",
"another",
"error"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/redis_wrapper.go#L89-L99 | train |
adjust/rmq | queue.go | Publish | func (queue *redisQueue) Publish(payload string) bool {
// debug(fmt.Sprintf("publish %s %s", payload, queue)) // COMMENTOUT
return queue.redisClient.LPush(queue.readyKey, payload)
} | go | func (queue *redisQueue) Publish(payload string) bool {
// debug(fmt.Sprintf("publish %s %s", payload, queue)) // COMMENTOUT
return queue.redisClient.LPush(queue.readyKey, payload)
} | [
"func",
"(",
"queue",
"*",
"redisQueue",
")",
"Publish",
"(",
"payload",
"string",
")",
"bool",
"{",
"// debug(fmt.Sprintf(\"publish %s %s\", payload, queue)) // COMMENTOUT",
"return",
"queue",
".",
"redisClient",
".",
"LPush",
"(",
"queue",
".",
"readyKey",
",",
"payload",
")",
"\n",
"}"
] | // Publish adds a delivery with the given payload to the queue | [
"Publish",
"adds",
"a",
"delivery",
"with",
"the",
"given",
"payload",
"to",
"the",
"queue"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L96-L99 | train |
adjust/rmq | queue.go | PublishBytes | func (queue *redisQueue) PublishBytes(payload []byte) bool {
return queue.Publish(string(payload))
} | go | func (queue *redisQueue) PublishBytes(payload []byte) bool {
return queue.Publish(string(payload))
} | [
"func",
"(",
"queue",
"*",
"redisQueue",
")",
"PublishBytes",
"(",
"payload",
"[",
"]",
"byte",
")",
"bool",
"{",
"return",
"queue",
".",
"Publish",
"(",
"string",
"(",
"payload",
")",
")",
"\n",
"}"
] | // PublishBytes just casts the bytes and calls Publish | [
"PublishBytes",
"just",
"casts",
"the",
"bytes",
"and",
"calls",
"Publish"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L102-L104 | train |
adjust/rmq | queue.go | Close | func (queue *redisQueue) Close() bool {
queue.PurgeRejected()
queue.PurgeReady()
count, _ := queue.redisClient.SRem(queuesKey, queue.name)
return count > 0
} | go | func (queue *redisQueue) Close() bool {
queue.PurgeRejected()
queue.PurgeReady()
count, _ := queue.redisClient.SRem(queuesKey, queue.name)
return count > 0
} | [
"func",
"(",
"queue",
"*",
"redisQueue",
")",
"Close",
"(",
")",
"bool",
"{",
"queue",
".",
"PurgeRejected",
"(",
")",
"\n",
"queue",
".",
"PurgeReady",
"(",
")",
"\n",
"count",
",",
"_",
":=",
"queue",
".",
"redisClient",
".",
"SRem",
"(",
"queuesKey",
",",
"queue",
".",
"name",
")",
"\n",
"return",
"count",
">",
"0",
"\n",
"}"
] | // Close purges and removes the queue from the list of queues | [
"Close",
"purges",
"and",
"removes",
"the",
"queue",
"from",
"the",
"list",
"of",
"queues"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L117-L122 | train |
adjust/rmq | queue.go | ReturnAllUnacked | func (queue *redisQueue) ReturnAllUnacked() int {
count, ok := queue.redisClient.LLen(queue.unackedKey)
if !ok {
return 0
}
unackedCount := count
for i := 0; i < unackedCount; i++ {
if _, ok := queue.redisClient.RPopLPush(queue.unackedKey, queue.readyKey); !ok {
return i
}
// debug(fmt.Sprintf("rmq queue returned unacked delivery %s %s", count, queue.readyKey)) // COMMENTOUT
}
return unackedCount
} | go | func (queue *redisQueue) ReturnAllUnacked() int {
count, ok := queue.redisClient.LLen(queue.unackedKey)
if !ok {
return 0
}
unackedCount := count
for i := 0; i < unackedCount; i++ {
if _, ok := queue.redisClient.RPopLPush(queue.unackedKey, queue.readyKey); !ok {
return i
}
// debug(fmt.Sprintf("rmq queue returned unacked delivery %s %s", count, queue.readyKey)) // COMMENTOUT
}
return unackedCount
} | [
"func",
"(",
"queue",
"*",
"redisQueue",
")",
"ReturnAllUnacked",
"(",
")",
"int",
"{",
"count",
",",
"ok",
":=",
"queue",
".",
"redisClient",
".",
"LLen",
"(",
"queue",
".",
"unackedKey",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"0",
"\n",
"}",
"\n\n",
"unackedCount",
":=",
"count",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"unackedCount",
";",
"i",
"++",
"{",
"if",
"_",
",",
"ok",
":=",
"queue",
".",
"redisClient",
".",
"RPopLPush",
"(",
"queue",
".",
"unackedKey",
",",
"queue",
".",
"readyKey",
")",
";",
"!",
"ok",
"{",
"return",
"i",
"\n",
"}",
"\n",
"// debug(fmt.Sprintf(\"rmq queue returned unacked delivery %s %s\", count, queue.readyKey)) // COMMENTOUT",
"}",
"\n\n",
"return",
"unackedCount",
"\n",
"}"
] | // ReturnAllUnacked moves all unacked deliveries back to the ready
// queue and deletes the unacked key afterwards, returns number of returned
// deliveries | [
"ReturnAllUnacked",
"moves",
"all",
"unacked",
"deliveries",
"back",
"to",
"the",
"ready",
"queue",
"and",
"deletes",
"the",
"unacked",
"key",
"afterwards",
"returns",
"number",
"of",
"returned",
"deliveries"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L142-L157 | train |
adjust/rmq | queue.go | ReturnAllRejected | func (queue *redisQueue) ReturnAllRejected() int {
rejectedCount, _ := queue.redisClient.LLen(queue.rejectedKey)
return queue.ReturnRejected(rejectedCount)
} | go | func (queue *redisQueue) ReturnAllRejected() int {
rejectedCount, _ := queue.redisClient.LLen(queue.rejectedKey)
return queue.ReturnRejected(rejectedCount)
} | [
"func",
"(",
"queue",
"*",
"redisQueue",
")",
"ReturnAllRejected",
"(",
")",
"int",
"{",
"rejectedCount",
",",
"_",
":=",
"queue",
".",
"redisClient",
".",
"LLen",
"(",
"queue",
".",
"rejectedKey",
")",
"\n",
"return",
"queue",
".",
"ReturnRejected",
"(",
"rejectedCount",
")",
"\n",
"}"
] | // ReturnAllRejected moves all rejected deliveries back to the ready
// list and returns the number of returned deliveries | [
"ReturnAllRejected",
"moves",
"all",
"rejected",
"deliveries",
"back",
"to",
"the",
"ready",
"list",
"and",
"returns",
"the",
"number",
"of",
"returned",
"deliveries"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L161-L164 | train |
adjust/rmq | queue.go | ReturnRejected | func (queue *redisQueue) ReturnRejected(count int) int {
if count == 0 {
return 0
}
for i := 0; i < count; i++ {
_, ok := queue.redisClient.RPopLPush(queue.rejectedKey, queue.readyKey)
if !ok {
return i
}
// debug(fmt.Sprintf("rmq queue returned rejected delivery %s %s", value, queue.readyKey)) // COMMENTOUT
}
return count
} | go | func (queue *redisQueue) ReturnRejected(count int) int {
if count == 0 {
return 0
}
for i := 0; i < count; i++ {
_, ok := queue.redisClient.RPopLPush(queue.rejectedKey, queue.readyKey)
if !ok {
return i
}
// debug(fmt.Sprintf("rmq queue returned rejected delivery %s %s", value, queue.readyKey)) // COMMENTOUT
}
return count
} | [
"func",
"(",
"queue",
"*",
"redisQueue",
")",
"ReturnRejected",
"(",
"count",
"int",
")",
"int",
"{",
"if",
"count",
"==",
"0",
"{",
"return",
"0",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"count",
";",
"i",
"++",
"{",
"_",
",",
"ok",
":=",
"queue",
".",
"redisClient",
".",
"RPopLPush",
"(",
"queue",
".",
"rejectedKey",
",",
"queue",
".",
"readyKey",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"i",
"\n",
"}",
"\n",
"// debug(fmt.Sprintf(\"rmq queue returned rejected delivery %s %s\", value, queue.readyKey)) // COMMENTOUT",
"}",
"\n\n",
"return",
"count",
"\n",
"}"
] | // ReturnRejected tries to return count rejected deliveries back to
// the ready list and returns the number of returned deliveries | [
"ReturnRejected",
"tries",
"to",
"return",
"count",
"rejected",
"deliveries",
"back",
"to",
"the",
"ready",
"list",
"and",
"returns",
"the",
"number",
"of",
"returned",
"deliveries"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L168-L182 | train |
adjust/rmq | queue.go | CloseInConnection | func (queue *redisQueue) CloseInConnection() {
queue.redisClient.Del(queue.unackedKey)
queue.redisClient.Del(queue.consumersKey)
queue.redisClient.SRem(queue.queuesKey, queue.name)
} | go | func (queue *redisQueue) CloseInConnection() {
queue.redisClient.Del(queue.unackedKey)
queue.redisClient.Del(queue.consumersKey)
queue.redisClient.SRem(queue.queuesKey, queue.name)
} | [
"func",
"(",
"queue",
"*",
"redisQueue",
")",
"CloseInConnection",
"(",
")",
"{",
"queue",
".",
"redisClient",
".",
"Del",
"(",
"queue",
".",
"unackedKey",
")",
"\n",
"queue",
".",
"redisClient",
".",
"Del",
"(",
"queue",
".",
"consumersKey",
")",
"\n",
"queue",
".",
"redisClient",
".",
"SRem",
"(",
"queue",
".",
"queuesKey",
",",
"queue",
".",
"name",
")",
"\n",
"}"
] | // CloseInConnection closes the queue in the associated connection by removing all related keys | [
"CloseInConnection",
"closes",
"the",
"queue",
"in",
"the",
"associated",
"connection",
"by",
"removing",
"all",
"related",
"keys"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L185-L189 | train |
adjust/rmq | queue.go | StartConsuming | func (queue *redisQueue) StartConsuming(prefetchLimit int, pollDuration time.Duration) bool {
if queue.deliveryChan != nil {
return false // already consuming
}
// add queue to list of queues consumed on this connection
if ok := queue.redisClient.SAdd(queue.queuesKey, queue.name); !ok {
log.Panicf("rmq queue failed to start consuming %s", queue)
}
queue.prefetchLimit = prefetchLimit
queue.pollDuration = pollDuration
queue.deliveryChan = make(chan Delivery, prefetchLimit)
atomic.StoreInt32(&queue.consumingStopped, 0)
// log.Printf("rmq queue started consuming %s %d %s", queue, prefetchLimit, pollDuration)
go queue.consume()
return true
} | go | func (queue *redisQueue) StartConsuming(prefetchLimit int, pollDuration time.Duration) bool {
if queue.deliveryChan != nil {
return false // already consuming
}
// add queue to list of queues consumed on this connection
if ok := queue.redisClient.SAdd(queue.queuesKey, queue.name); !ok {
log.Panicf("rmq queue failed to start consuming %s", queue)
}
queue.prefetchLimit = prefetchLimit
queue.pollDuration = pollDuration
queue.deliveryChan = make(chan Delivery, prefetchLimit)
atomic.StoreInt32(&queue.consumingStopped, 0)
// log.Printf("rmq queue started consuming %s %d %s", queue, prefetchLimit, pollDuration)
go queue.consume()
return true
} | [
"func",
"(",
"queue",
"*",
"redisQueue",
")",
"StartConsuming",
"(",
"prefetchLimit",
"int",
",",
"pollDuration",
"time",
".",
"Duration",
")",
"bool",
"{",
"if",
"queue",
".",
"deliveryChan",
"!=",
"nil",
"{",
"return",
"false",
"// already consuming",
"\n",
"}",
"\n\n",
"// add queue to list of queues consumed on this connection",
"if",
"ok",
":=",
"queue",
".",
"redisClient",
".",
"SAdd",
"(",
"queue",
".",
"queuesKey",
",",
"queue",
".",
"name",
")",
";",
"!",
"ok",
"{",
"log",
".",
"Panicf",
"(",
"\"",
"\"",
",",
"queue",
")",
"\n",
"}",
"\n\n",
"queue",
".",
"prefetchLimit",
"=",
"prefetchLimit",
"\n",
"queue",
".",
"pollDuration",
"=",
"pollDuration",
"\n",
"queue",
".",
"deliveryChan",
"=",
"make",
"(",
"chan",
"Delivery",
",",
"prefetchLimit",
")",
"\n",
"atomic",
".",
"StoreInt32",
"(",
"&",
"queue",
".",
"consumingStopped",
",",
"0",
")",
"\n",
"// log.Printf(\"rmq queue started consuming %s %d %s\", queue, prefetchLimit, pollDuration)",
"go",
"queue",
".",
"consume",
"(",
")",
"\n",
"return",
"true",
"\n",
"}"
] | // StartConsuming starts consuming into a channel of size prefetchLimit
// must be called before consumers can be added!
// pollDuration is the duration the queue sleeps before checking for new deliveries | [
"StartConsuming",
"starts",
"consuming",
"into",
"a",
"channel",
"of",
"size",
"prefetchLimit",
"must",
"be",
"called",
"before",
"consumers",
"can",
"be",
"added!",
"pollDuration",
"is",
"the",
"duration",
"the",
"queue",
"sleeps",
"before",
"checking",
"for",
"new",
"deliveries"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L203-L220 | train |
adjust/rmq | queue.go | AddConsumer | func (queue *redisQueue) AddConsumer(tag string, consumer Consumer) string {
queue.stopWg.Add(1)
name := queue.addConsumer(tag)
go queue.consumerConsume(consumer)
return name
} | go | func (queue *redisQueue) AddConsumer(tag string, consumer Consumer) string {
queue.stopWg.Add(1)
name := queue.addConsumer(tag)
go queue.consumerConsume(consumer)
return name
} | [
"func",
"(",
"queue",
"*",
"redisQueue",
")",
"AddConsumer",
"(",
"tag",
"string",
",",
"consumer",
"Consumer",
")",
"string",
"{",
"queue",
".",
"stopWg",
".",
"Add",
"(",
"1",
")",
"\n",
"name",
":=",
"queue",
".",
"addConsumer",
"(",
"tag",
")",
"\n",
"go",
"queue",
".",
"consumerConsume",
"(",
"consumer",
")",
"\n",
"return",
"name",
"\n",
"}"
] | // AddConsumer adds a consumer to the queue and returns its internal name
// panics if StartConsuming wasn't called before! | [
"AddConsumer",
"adds",
"a",
"consumer",
"to",
"the",
"queue",
"and",
"returns",
"its",
"internal",
"name",
"panics",
"if",
"StartConsuming",
"wasn",
"t",
"called",
"before!"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L242-L247 | train |
adjust/rmq | queue.go | AddBatchConsumer | func (queue *redisQueue) AddBatchConsumer(tag string, batchSize int, consumer BatchConsumer) string {
return queue.AddBatchConsumerWithTimeout(tag, batchSize, defaultBatchTimeout, consumer)
} | go | func (queue *redisQueue) AddBatchConsumer(tag string, batchSize int, consumer BatchConsumer) string {
return queue.AddBatchConsumerWithTimeout(tag, batchSize, defaultBatchTimeout, consumer)
} | [
"func",
"(",
"queue",
"*",
"redisQueue",
")",
"AddBatchConsumer",
"(",
"tag",
"string",
",",
"batchSize",
"int",
",",
"consumer",
"BatchConsumer",
")",
"string",
"{",
"return",
"queue",
".",
"AddBatchConsumerWithTimeout",
"(",
"tag",
",",
"batchSize",
",",
"defaultBatchTimeout",
",",
"consumer",
")",
"\n",
"}"
] | // AddBatchConsumer is similar to AddConsumer, but for batches of deliveries | [
"AddBatchConsumer",
"is",
"similar",
"to",
"AddConsumer",
"but",
"for",
"batches",
"of",
"deliveries"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L254-L256 | train |
adjust/rmq | queue.go | AddBatchConsumerWithTimeout | func (queue *redisQueue) AddBatchConsumerWithTimeout(tag string, batchSize int, timeout time.Duration, consumer BatchConsumer) string {
queue.stopWg.Add(1)
name := queue.addConsumer(tag)
go queue.consumerBatchConsume(batchSize, timeout, consumer)
return name
} | go | func (queue *redisQueue) AddBatchConsumerWithTimeout(tag string, batchSize int, timeout time.Duration, consumer BatchConsumer) string {
queue.stopWg.Add(1)
name := queue.addConsumer(tag)
go queue.consumerBatchConsume(batchSize, timeout, consumer)
return name
} | [
"func",
"(",
"queue",
"*",
"redisQueue",
")",
"AddBatchConsumerWithTimeout",
"(",
"tag",
"string",
",",
"batchSize",
"int",
",",
"timeout",
"time",
".",
"Duration",
",",
"consumer",
"BatchConsumer",
")",
"string",
"{",
"queue",
".",
"stopWg",
".",
"Add",
"(",
"1",
")",
"\n",
"name",
":=",
"queue",
".",
"addConsumer",
"(",
"tag",
")",
"\n",
"go",
"queue",
".",
"consumerBatchConsume",
"(",
"batchSize",
",",
"timeout",
",",
"consumer",
")",
"\n",
"return",
"name",
"\n",
"}"
] | // Timeout limits the amount of time waiting to fill an entire batch
// The timer is only started when the first message in a batch is received | [
"Timeout",
"limits",
"the",
"amount",
"of",
"time",
"waiting",
"to",
"fill",
"an",
"entire",
"batch",
"The",
"timer",
"is",
"only",
"started",
"when",
"the",
"first",
"message",
"in",
"a",
"batch",
"is",
"received"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L260-L265 | train |
adjust/rmq | queue.go | consumeBatch | func (queue *redisQueue) consumeBatch(batchSize int) bool {
if batchSize == 0 {
return false
}
for i := 0; i < batchSize; i++ {
value, ok := queue.redisClient.RPopLPush(queue.readyKey, queue.unackedKey)
if !ok {
// debug(fmt.Sprintf("rmq queue consumed last batch %s %d", queue, i)) // COMMENTOUT
return false
}
// debug(fmt.Sprintf("consume %d/%d %s %s", i, batchSize, value, queue)) // COMMENTOUT
queue.deliveryChan <- newDelivery(value, queue.unackedKey, queue.rejectedKey, queue.pushKey, queue.redisClient)
}
// debug(fmt.Sprintf("rmq queue consumed batch %s %d", queue, batchSize)) // COMMENTOUT
return true
} | go | func (queue *redisQueue) consumeBatch(batchSize int) bool {
if batchSize == 0 {
return false
}
for i := 0; i < batchSize; i++ {
value, ok := queue.redisClient.RPopLPush(queue.readyKey, queue.unackedKey)
if !ok {
// debug(fmt.Sprintf("rmq queue consumed last batch %s %d", queue, i)) // COMMENTOUT
return false
}
// debug(fmt.Sprintf("consume %d/%d %s %s", i, batchSize, value, queue)) // COMMENTOUT
queue.deliveryChan <- newDelivery(value, queue.unackedKey, queue.rejectedKey, queue.pushKey, queue.redisClient)
}
// debug(fmt.Sprintf("rmq queue consumed batch %s %d", queue, batchSize)) // COMMENTOUT
return true
} | [
"func",
"(",
"queue",
"*",
"redisQueue",
")",
"consumeBatch",
"(",
"batchSize",
"int",
")",
"bool",
"{",
"if",
"batchSize",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"batchSize",
";",
"i",
"++",
"{",
"value",
",",
"ok",
":=",
"queue",
".",
"redisClient",
".",
"RPopLPush",
"(",
"queue",
".",
"readyKey",
",",
"queue",
".",
"unackedKey",
")",
"\n",
"if",
"!",
"ok",
"{",
"// debug(fmt.Sprintf(\"rmq queue consumed last batch %s %d\", queue, i)) // COMMENTOUT",
"return",
"false",
"\n",
"}",
"\n\n",
"// debug(fmt.Sprintf(\"consume %d/%d %s %s\", i, batchSize, value, queue)) // COMMENTOUT",
"queue",
".",
"deliveryChan",
"<-",
"newDelivery",
"(",
"value",
",",
"queue",
".",
"unackedKey",
",",
"queue",
".",
"rejectedKey",
",",
"queue",
".",
"pushKey",
",",
"queue",
".",
"redisClient",
")",
"\n",
"}",
"\n\n",
"// debug(fmt.Sprintf(\"rmq queue consumed batch %s %d\", queue, batchSize)) // COMMENTOUT",
"return",
"true",
"\n",
"}"
] | // consumeBatch tries to read batchSize deliveries, returns true if any and all were consumed | [
"consumeBatch",
"tries",
"to",
"read",
"batchSize",
"deliveries",
"returns",
"true",
"if",
"any",
"and",
"all",
"were",
"consumed"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L326-L344 | train |
adjust/rmq | connection.go | OpenConnectionWithRedisClient | func OpenConnectionWithRedisClient(tag string, redisClient *redis.Client) *redisConnection {
return openConnectionWithRedisClient(tag, RedisWrapper{redisClient})
} | go | func OpenConnectionWithRedisClient(tag string, redisClient *redis.Client) *redisConnection {
return openConnectionWithRedisClient(tag, RedisWrapper{redisClient})
} | [
"func",
"OpenConnectionWithRedisClient",
"(",
"tag",
"string",
",",
"redisClient",
"*",
"redis",
".",
"Client",
")",
"*",
"redisConnection",
"{",
"return",
"openConnectionWithRedisClient",
"(",
"tag",
",",
"RedisWrapper",
"{",
"redisClient",
"}",
")",
"\n",
"}"
] | // OpenConnectionWithRedisClient opens and returns a new connection | [
"OpenConnectionWithRedisClient",
"opens",
"and",
"returns",
"a",
"new",
"connection"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/connection.go#L33-L35 | train |
adjust/rmq | connection.go | OpenConnection | func OpenConnection(tag, network, address string, db int) *redisConnection {
redisClient := redis.NewClient(&redis.Options{
Network: network,
Addr: address,
DB: db,
})
return OpenConnectionWithRedisClient(tag, redisClient)
} | go | func OpenConnection(tag, network, address string, db int) *redisConnection {
redisClient := redis.NewClient(&redis.Options{
Network: network,
Addr: address,
DB: db,
})
return OpenConnectionWithRedisClient(tag, redisClient)
} | [
"func",
"OpenConnection",
"(",
"tag",
",",
"network",
",",
"address",
"string",
",",
"db",
"int",
")",
"*",
"redisConnection",
"{",
"redisClient",
":=",
"redis",
".",
"NewClient",
"(",
"&",
"redis",
".",
"Options",
"{",
"Network",
":",
"network",
",",
"Addr",
":",
"address",
",",
"DB",
":",
"db",
",",
"}",
")",
"\n",
"return",
"OpenConnectionWithRedisClient",
"(",
"tag",
",",
"redisClient",
")",
"\n",
"}"
] | // OpenConnection opens and returns a new connection | [
"OpenConnection",
"opens",
"and",
"returns",
"a",
"new",
"connection"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/connection.go#L66-L73 | train |
adjust/rmq | connection.go | OpenQueue | func (connection *redisConnection) OpenQueue(name string) Queue {
connection.redisClient.SAdd(queuesKey, name)
queue := newQueue(name, connection.Name, connection.queuesKey, connection.redisClient)
return queue
} | go | func (connection *redisConnection) OpenQueue(name string) Queue {
connection.redisClient.SAdd(queuesKey, name)
queue := newQueue(name, connection.Name, connection.queuesKey, connection.redisClient)
return queue
} | [
"func",
"(",
"connection",
"*",
"redisConnection",
")",
"OpenQueue",
"(",
"name",
"string",
")",
"Queue",
"{",
"connection",
".",
"redisClient",
".",
"SAdd",
"(",
"queuesKey",
",",
"name",
")",
"\n",
"queue",
":=",
"newQueue",
"(",
"name",
",",
"connection",
".",
"Name",
",",
"connection",
".",
"queuesKey",
",",
"connection",
".",
"redisClient",
")",
"\n",
"return",
"queue",
"\n",
"}"
] | // OpenQueue opens and returns the queue with a given name | [
"OpenQueue",
"opens",
"and",
"returns",
"the",
"queue",
"with",
"a",
"given",
"name"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/connection.go#L76-L80 | train |
adjust/rmq | connection.go | Check | func (connection *redisConnection) Check() bool {
heartbeatKey := strings.Replace(connectionHeartbeatTemplate, phConnection, connection.Name, 1)
ttl, _ := connection.redisClient.TTL(heartbeatKey)
return ttl > 0
} | go | func (connection *redisConnection) Check() bool {
heartbeatKey := strings.Replace(connectionHeartbeatTemplate, phConnection, connection.Name, 1)
ttl, _ := connection.redisClient.TTL(heartbeatKey)
return ttl > 0
} | [
"func",
"(",
"connection",
"*",
"redisConnection",
")",
"Check",
"(",
")",
"bool",
"{",
"heartbeatKey",
":=",
"strings",
".",
"Replace",
"(",
"connectionHeartbeatTemplate",
",",
"phConnection",
",",
"connection",
".",
"Name",
",",
"1",
")",
"\n",
"ttl",
",",
"_",
":=",
"connection",
".",
"redisClient",
".",
"TTL",
"(",
"heartbeatKey",
")",
"\n",
"return",
"ttl",
">",
"0",
"\n",
"}"
] | // Check retuns true if the connection is currently active in terms of heartbeat | [
"Check",
"retuns",
"true",
"if",
"the",
"connection",
"is",
"currently",
"active",
"in",
"terms",
"of",
"heartbeat"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/connection.go#L96-L100 | train |
adjust/rmq | connection.go | StopHeartbeat | func (connection *redisConnection) StopHeartbeat() bool {
connection.heartbeatStopped = true
_, ok := connection.redisClient.Del(connection.heartbeatKey)
return ok
} | go | func (connection *redisConnection) StopHeartbeat() bool {
connection.heartbeatStopped = true
_, ok := connection.redisClient.Del(connection.heartbeatKey)
return ok
} | [
"func",
"(",
"connection",
"*",
"redisConnection",
")",
"StopHeartbeat",
"(",
")",
"bool",
"{",
"connection",
".",
"heartbeatStopped",
"=",
"true",
"\n",
"_",
",",
"ok",
":=",
"connection",
".",
"redisClient",
".",
"Del",
"(",
"connection",
".",
"heartbeatKey",
")",
"\n",
"return",
"ok",
"\n",
"}"
] | // StopHeartbeat stops the heartbeat of the connection
// it does not remove it from the list of connections so it can later be found by the cleaner | [
"StopHeartbeat",
"stops",
"the",
"heartbeat",
"of",
"the",
"connection",
"it",
"does",
"not",
"remove",
"it",
"from",
"the",
"list",
"of",
"connections",
"so",
"it",
"can",
"later",
"be",
"found",
"by",
"the",
"cleaner"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/connection.go#L104-L108 | train |
adjust/rmq | connection.go | CloseAllQueues | func (connection *redisConnection) CloseAllQueues() int {
count, _ := connection.redisClient.Del(queuesKey)
return count
} | go | func (connection *redisConnection) CloseAllQueues() int {
count, _ := connection.redisClient.Del(queuesKey)
return count
} | [
"func",
"(",
"connection",
"*",
"redisConnection",
")",
"CloseAllQueues",
"(",
")",
"int",
"{",
"count",
",",
"_",
":=",
"connection",
".",
"redisClient",
".",
"Del",
"(",
"queuesKey",
")",
"\n",
"return",
"count",
"\n",
"}"
] | // CloseAllQueues closes all queues by removing them from the global list | [
"CloseAllQueues",
"closes",
"all",
"queues",
"by",
"removing",
"them",
"from",
"the",
"global",
"list"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/connection.go#L121-L124 | train |
adjust/rmq | connection.go | CloseAllQueuesInConnection | func (connection *redisConnection) CloseAllQueuesInConnection() error {
connection.redisClient.Del(connection.queuesKey)
// debug(fmt.Sprintf("connection closed all queues %s %d", connection, connection.queuesKey)) // COMMENTOUT
return nil
} | go | func (connection *redisConnection) CloseAllQueuesInConnection() error {
connection.redisClient.Del(connection.queuesKey)
// debug(fmt.Sprintf("connection closed all queues %s %d", connection, connection.queuesKey)) // COMMENTOUT
return nil
} | [
"func",
"(",
"connection",
"*",
"redisConnection",
")",
"CloseAllQueuesInConnection",
"(",
")",
"error",
"{",
"connection",
".",
"redisClient",
".",
"Del",
"(",
"connection",
".",
"queuesKey",
")",
"\n",
"// debug(fmt.Sprintf(\"connection closed all queues %s %d\", connection, connection.queuesKey)) // COMMENTOUT",
"return",
"nil",
"\n",
"}"
] | // CloseAllQueuesInConnection closes all queues in the associated connection by removing all related keys | [
"CloseAllQueuesInConnection",
"closes",
"all",
"queues",
"in",
"the",
"associated",
"connection",
"by",
"removing",
"all",
"related",
"keys"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/connection.go#L127-L131 | train |
adjust/rmq | connection.go | heartbeat | func (connection *redisConnection) heartbeat() {
for {
if !connection.updateHeartbeat() {
// log.Printf("rmq connection failed to update heartbeat %s", connection)
}
time.Sleep(time.Second)
if connection.heartbeatStopped {
// log.Printf("rmq connection stopped heartbeat %s", connection)
return
}
}
} | go | func (connection *redisConnection) heartbeat() {
for {
if !connection.updateHeartbeat() {
// log.Printf("rmq connection failed to update heartbeat %s", connection)
}
time.Sleep(time.Second)
if connection.heartbeatStopped {
// log.Printf("rmq connection stopped heartbeat %s", connection)
return
}
}
} | [
"func",
"(",
"connection",
"*",
"redisConnection",
")",
"heartbeat",
"(",
")",
"{",
"for",
"{",
"if",
"!",
"connection",
".",
"updateHeartbeat",
"(",
")",
"{",
"// log.Printf(\"rmq connection failed to update heartbeat %s\", connection)",
"}",
"\n\n",
"time",
".",
"Sleep",
"(",
"time",
".",
"Second",
")",
"\n\n",
"if",
"connection",
".",
"heartbeatStopped",
"{",
"// log.Printf(\"rmq connection stopped heartbeat %s\", connection)",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // heartbeat keeps the heartbeat key alive | [
"heartbeat",
"keeps",
"the",
"heartbeat",
"key",
"alive"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/connection.go#L139-L152 | train |
adjust/rmq | connection.go | hijackConnection | func (connection *redisConnection) hijackConnection(name string) *redisConnection {
return &redisConnection{
Name: name,
heartbeatKey: strings.Replace(connectionHeartbeatTemplate, phConnection, name, 1),
queuesKey: strings.Replace(connectionQueuesTemplate, phConnection, name, 1),
redisClient: connection.redisClient,
}
} | go | func (connection *redisConnection) hijackConnection(name string) *redisConnection {
return &redisConnection{
Name: name,
heartbeatKey: strings.Replace(connectionHeartbeatTemplate, phConnection, name, 1),
queuesKey: strings.Replace(connectionQueuesTemplate, phConnection, name, 1),
redisClient: connection.redisClient,
}
} | [
"func",
"(",
"connection",
"*",
"redisConnection",
")",
"hijackConnection",
"(",
"name",
"string",
")",
"*",
"redisConnection",
"{",
"return",
"&",
"redisConnection",
"{",
"Name",
":",
"name",
",",
"heartbeatKey",
":",
"strings",
".",
"Replace",
"(",
"connectionHeartbeatTemplate",
",",
"phConnection",
",",
"name",
",",
"1",
")",
",",
"queuesKey",
":",
"strings",
".",
"Replace",
"(",
"connectionQueuesTemplate",
",",
"phConnection",
",",
"name",
",",
"1",
")",
",",
"redisClient",
":",
"connection",
".",
"redisClient",
",",
"}",
"\n",
"}"
] | // hijackConnection reopens an existing connection for inspection purposes without starting a heartbeat | [
"hijackConnection",
"reopens",
"an",
"existing",
"connection",
"for",
"inspection",
"purposes",
"without",
"starting",
"a",
"heartbeat"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/connection.go#L160-L167 | train |
adjust/rmq | connection.go | openQueue | func (connection *redisConnection) openQueue(name string) *redisQueue {
return newQueue(name, connection.Name, connection.queuesKey, connection.redisClient)
} | go | func (connection *redisConnection) openQueue(name string) *redisQueue {
return newQueue(name, connection.Name, connection.queuesKey, connection.redisClient)
} | [
"func",
"(",
"connection",
"*",
"redisConnection",
")",
"openQueue",
"(",
"name",
"string",
")",
"*",
"redisQueue",
"{",
"return",
"newQueue",
"(",
"name",
",",
"connection",
".",
"Name",
",",
"connection",
".",
"queuesKey",
",",
"connection",
".",
"redisClient",
")",
"\n",
"}"
] | // openQueue opens a queue without adding it to the set of queues | [
"openQueue",
"opens",
"a",
"queue",
"without",
"adding",
"it",
"to",
"the",
"set",
"of",
"queues"
] | d0da8bbb71c869171bf054c3ae60ecee3012b249 | https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/connection.go#L170-L172 | train |
vdobler/chart | chart.go | Reset | func (r *Range) Reset() {
r.Min, r.Max = 0, 0
r.TMin, r.TMax = time.Time{}, time.Time{}
r.Tics = nil
r.Norm, r.InvNorm = nil, nil
r.Data2Screen, r.Screen2Data = nil, nil
if !r.TicSetting.UserDelta {
r.TicSetting.Delta = 0
r.TicSetting.TDelta = nil
}
} | go | func (r *Range) Reset() {
r.Min, r.Max = 0, 0
r.TMin, r.TMax = time.Time{}, time.Time{}
r.Tics = nil
r.Norm, r.InvNorm = nil, nil
r.Data2Screen, r.Screen2Data = nil, nil
if !r.TicSetting.UserDelta {
r.TicSetting.Delta = 0
r.TicSetting.TDelta = nil
}
} | [
"func",
"(",
"r",
"*",
"Range",
")",
"Reset",
"(",
")",
"{",
"r",
".",
"Min",
",",
"r",
".",
"Max",
"=",
"0",
",",
"0",
"\n",
"r",
".",
"TMin",
",",
"r",
".",
"TMax",
"=",
"time",
".",
"Time",
"{",
"}",
",",
"time",
".",
"Time",
"{",
"}",
"\n",
"r",
".",
"Tics",
"=",
"nil",
"\n",
"r",
".",
"Norm",
",",
"r",
".",
"InvNorm",
"=",
"nil",
",",
"nil",
"\n",
"r",
".",
"Data2Screen",
",",
"r",
".",
"Screen2Data",
"=",
"nil",
",",
"nil",
"\n\n",
"if",
"!",
"r",
".",
"TicSetting",
".",
"UserDelta",
"{",
"r",
".",
"TicSetting",
".",
"Delta",
"=",
"0",
"\n",
"r",
".",
"TicSetting",
".",
"TDelta",
"=",
"nil",
"\n",
"}",
"\n",
"}"
] | // Reset the fields in r which have been set up during a plot. | [
"Reset",
"the",
"fields",
"in",
"r",
"which",
"have",
"been",
"set",
"up",
"during",
"a",
"plot",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/chart.go#L143-L154 | train |
vdobler/chart | chart.go | autoscale | func (r *Range) autoscale(x float64) {
if x < r.DataMin && !r.MinMode.Fixed {
if !r.MinMode.Constrained {
// full autoscaling
r.DataMin = x
} else {
r.DataMin = fmin(fmax(x, r.MinMode.Lower), r.DataMin)
}
}
if x > r.DataMax && !r.MaxMode.Fixed {
if !r.MaxMode.Constrained {
// full autoscaling
r.DataMax = x
} else {
r.DataMax = fmax(fmin(x, r.MaxMode.Upper), r.DataMax)
}
}
} | go | func (r *Range) autoscale(x float64) {
if x < r.DataMin && !r.MinMode.Fixed {
if !r.MinMode.Constrained {
// full autoscaling
r.DataMin = x
} else {
r.DataMin = fmin(fmax(x, r.MinMode.Lower), r.DataMin)
}
}
if x > r.DataMax && !r.MaxMode.Fixed {
if !r.MaxMode.Constrained {
// full autoscaling
r.DataMax = x
} else {
r.DataMax = fmax(fmin(x, r.MaxMode.Upper), r.DataMax)
}
}
} | [
"func",
"(",
"r",
"*",
"Range",
")",
"autoscale",
"(",
"x",
"float64",
")",
"{",
"if",
"x",
"<",
"r",
".",
"DataMin",
"&&",
"!",
"r",
".",
"MinMode",
".",
"Fixed",
"{",
"if",
"!",
"r",
".",
"MinMode",
".",
"Constrained",
"{",
"// full autoscaling",
"r",
".",
"DataMin",
"=",
"x",
"\n",
"}",
"else",
"{",
"r",
".",
"DataMin",
"=",
"fmin",
"(",
"fmax",
"(",
"x",
",",
"r",
".",
"MinMode",
".",
"Lower",
")",
",",
"r",
".",
"DataMin",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"x",
">",
"r",
".",
"DataMax",
"&&",
"!",
"r",
".",
"MaxMode",
".",
"Fixed",
"{",
"if",
"!",
"r",
".",
"MaxMode",
".",
"Constrained",
"{",
"// full autoscaling",
"r",
".",
"DataMax",
"=",
"x",
"\n",
"}",
"else",
"{",
"r",
".",
"DataMax",
"=",
"fmax",
"(",
"fmin",
"(",
"x",
",",
"r",
".",
"MaxMode",
".",
"Upper",
")",
",",
"r",
".",
"DataMax",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Update DataMin and DataMax according to the RangeModes. | [
"Update",
"DataMin",
"and",
"DataMax",
"according",
"to",
"the",
"RangeModes",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/chart.go#L213-L232 | train |
vdobler/chart | box.go | AddData | func (c *BoxChart) AddData(name string, data []Box, style Style) {
c.Data = append(c.Data, BoxChartData{name, style, data})
ps := PlotStyle(PlotStylePoints | PlotStyleBox)
c.Key.Entries = append(c.Key.Entries, KeyEntry{Text: name, Style: style, PlotStyle: ps})
// TODO(vodo) min, max
} | go | func (c *BoxChart) AddData(name string, data []Box, style Style) {
c.Data = append(c.Data, BoxChartData{name, style, data})
ps := PlotStyle(PlotStylePoints | PlotStyleBox)
c.Key.Entries = append(c.Key.Entries, KeyEntry{Text: name, Style: style, PlotStyle: ps})
// TODO(vodo) min, max
} | [
"func",
"(",
"c",
"*",
"BoxChart",
")",
"AddData",
"(",
"name",
"string",
",",
"data",
"[",
"]",
"Box",
",",
"style",
"Style",
")",
"{",
"c",
".",
"Data",
"=",
"append",
"(",
"c",
".",
"Data",
",",
"BoxChartData",
"{",
"name",
",",
"style",
",",
"data",
"}",
")",
"\n",
"ps",
":=",
"PlotStyle",
"(",
"PlotStylePoints",
"|",
"PlotStyleBox",
")",
"\n",
"c",
".",
"Key",
".",
"Entries",
"=",
"append",
"(",
"c",
".",
"Key",
".",
"Entries",
",",
"KeyEntry",
"{",
"Text",
":",
"name",
",",
"Style",
":",
"style",
",",
"PlotStyle",
":",
"ps",
"}",
")",
"\n",
"// TODO(vodo) min, max",
"}"
] | // AddData adds all boxes in data to the chart. | [
"AddData",
"adds",
"all",
"boxes",
"in",
"data",
"to",
"the",
"chart",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/box.go#L32-L37 | train |
vdobler/chart | scatter.go | AddDataGeneric | func (c *ScatterChart) AddDataGeneric(name string, data []XYErrValue, plotstyle PlotStyle, style Style) {
edata := make([]EPoint, len(data))
for i, d := range data {
x, y := d.XVal(), d.YVal()
xl, xh := d.XErr()
yl, yh := d.YErr()
dx, dy := xh-xl, yh-yl
xo, yo := xh-dx/2-x, yh-dy/2-y
edata[i] = EPoint{X: x, Y: y, DeltaX: dx, DeltaY: dy, OffX: xo, OffY: yo}
}
c.AddData(name, edata, plotstyle, style)
} | go | func (c *ScatterChart) AddDataGeneric(name string, data []XYErrValue, plotstyle PlotStyle, style Style) {
edata := make([]EPoint, len(data))
for i, d := range data {
x, y := d.XVal(), d.YVal()
xl, xh := d.XErr()
yl, yh := d.YErr()
dx, dy := xh-xl, yh-yl
xo, yo := xh-dx/2-x, yh-dy/2-y
edata[i] = EPoint{X: x, Y: y, DeltaX: dx, DeltaY: dy, OffX: xo, OffY: yo}
}
c.AddData(name, edata, plotstyle, style)
} | [
"func",
"(",
"c",
"*",
"ScatterChart",
")",
"AddDataGeneric",
"(",
"name",
"string",
",",
"data",
"[",
"]",
"XYErrValue",
",",
"plotstyle",
"PlotStyle",
",",
"style",
"Style",
")",
"{",
"edata",
":=",
"make",
"(",
"[",
"]",
"EPoint",
",",
"len",
"(",
"data",
")",
")",
"\n",
"for",
"i",
",",
"d",
":=",
"range",
"data",
"{",
"x",
",",
"y",
":=",
"d",
".",
"XVal",
"(",
")",
",",
"d",
".",
"YVal",
"(",
")",
"\n",
"xl",
",",
"xh",
":=",
"d",
".",
"XErr",
"(",
")",
"\n",
"yl",
",",
"yh",
":=",
"d",
".",
"YErr",
"(",
")",
"\n",
"dx",
",",
"dy",
":=",
"xh",
"-",
"xl",
",",
"yh",
"-",
"yl",
"\n",
"xo",
",",
"yo",
":=",
"xh",
"-",
"dx",
"/",
"2",
"-",
"x",
",",
"yh",
"-",
"dy",
"/",
"2",
"-",
"y",
"\n",
"edata",
"[",
"i",
"]",
"=",
"EPoint",
"{",
"X",
":",
"x",
",",
"Y",
":",
"y",
",",
"DeltaX",
":",
"dx",
",",
"DeltaY",
":",
"dy",
",",
"OffX",
":",
"xo",
",",
"OffY",
":",
"yo",
"}",
"\n",
"}",
"\n",
"c",
".",
"AddData",
"(",
"name",
",",
"edata",
",",
"plotstyle",
",",
"style",
")",
"\n",
"}"
] | // AddDataGeneric is the generiv version of AddData which allows any type
// to be plotted that implements the XYErrValue interface. | [
"AddDataGeneric",
"is",
"the",
"generiv",
"version",
"of",
"AddData",
"which",
"allows",
"any",
"type",
"to",
"be",
"plotted",
"that",
"implements",
"the",
"XYErrValue",
"interface",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/scatter.go#L97-L108 | train |
vdobler/chart | scatter.go | Plot | func (c *ScatterChart) Plot(g Graphics) {
layout := layout(g, c.Title, c.XRange.Label, c.YRange.Label,
c.XRange.TicSetting.Hide || c.XRange.TicSetting.HideLabels,
c.YRange.TicSetting.Hide || c.YRange.TicSetting.HideLabels,
&c.Key)
width, height := layout.Width, layout.Height
topm, leftm := layout.Top, layout.Left
numxtics, numytics := layout.NumXtics, layout.NumYtics
// fmt.Printf("\nSet up of X-Range (%d)\n", numxtics)
c.XRange.Setup(numxtics, numxtics+2, width, leftm, false)
// fmt.Printf("\nSet up of Y-Range (%d)\n", numytics)
c.YRange.Setup(numytics, numytics+2, height, topm, true)
g.Begin()
if c.Title != "" {
drawTitle(g, c.Title, elementStyle(c.Options, TitleElement))
}
g.XAxis(c.XRange, topm+height, topm, c.Options)
g.YAxis(c.YRange, leftm, leftm+width, c.Options)
// Plot Data
xf, yf := c.XRange.Data2Screen, c.YRange.Data2Screen
xmin, xmax := c.XRange.Min, c.XRange.Max
ymin, ymax := c.YRange.Min, c.YRange.Max
spf := screenPointFunc(xf, yf, xmin, xmax, ymin, ymax)
for i, data := range c.Data {
style := data.Style
if data.Samples != nil {
// Samples
points := make([]EPoint, 0, len(data.Samples))
for _, d := range data.Samples {
if d.X < xmin || d.X > xmax || d.Y < ymin || d.Y > ymax {
continue
}
p := spf(d)
points = append(points, p)
}
g.Scatter(points, data.PlotStyle, style)
} else if data.Func != nil {
c.drawFunction(g, i)
}
}
if !c.Key.Hide {
g.Key(layout.KeyX, layout.KeyY, c.Key, c.Options)
}
g.End()
} | go | func (c *ScatterChart) Plot(g Graphics) {
layout := layout(g, c.Title, c.XRange.Label, c.YRange.Label,
c.XRange.TicSetting.Hide || c.XRange.TicSetting.HideLabels,
c.YRange.TicSetting.Hide || c.YRange.TicSetting.HideLabels,
&c.Key)
width, height := layout.Width, layout.Height
topm, leftm := layout.Top, layout.Left
numxtics, numytics := layout.NumXtics, layout.NumYtics
// fmt.Printf("\nSet up of X-Range (%d)\n", numxtics)
c.XRange.Setup(numxtics, numxtics+2, width, leftm, false)
// fmt.Printf("\nSet up of Y-Range (%d)\n", numytics)
c.YRange.Setup(numytics, numytics+2, height, topm, true)
g.Begin()
if c.Title != "" {
drawTitle(g, c.Title, elementStyle(c.Options, TitleElement))
}
g.XAxis(c.XRange, topm+height, topm, c.Options)
g.YAxis(c.YRange, leftm, leftm+width, c.Options)
// Plot Data
xf, yf := c.XRange.Data2Screen, c.YRange.Data2Screen
xmin, xmax := c.XRange.Min, c.XRange.Max
ymin, ymax := c.YRange.Min, c.YRange.Max
spf := screenPointFunc(xf, yf, xmin, xmax, ymin, ymax)
for i, data := range c.Data {
style := data.Style
if data.Samples != nil {
// Samples
points := make([]EPoint, 0, len(data.Samples))
for _, d := range data.Samples {
if d.X < xmin || d.X > xmax || d.Y < ymin || d.Y > ymax {
continue
}
p := spf(d)
points = append(points, p)
}
g.Scatter(points, data.PlotStyle, style)
} else if data.Func != nil {
c.drawFunction(g, i)
}
}
if !c.Key.Hide {
g.Key(layout.KeyX, layout.KeyY, c.Key, c.Options)
}
g.End()
} | [
"func",
"(",
"c",
"*",
"ScatterChart",
")",
"Plot",
"(",
"g",
"Graphics",
")",
"{",
"layout",
":=",
"layout",
"(",
"g",
",",
"c",
".",
"Title",
",",
"c",
".",
"XRange",
".",
"Label",
",",
"c",
".",
"YRange",
".",
"Label",
",",
"c",
".",
"XRange",
".",
"TicSetting",
".",
"Hide",
"||",
"c",
".",
"XRange",
".",
"TicSetting",
".",
"HideLabels",
",",
"c",
".",
"YRange",
".",
"TicSetting",
".",
"Hide",
"||",
"c",
".",
"YRange",
".",
"TicSetting",
".",
"HideLabels",
",",
"&",
"c",
".",
"Key",
")",
"\n\n",
"width",
",",
"height",
":=",
"layout",
".",
"Width",
",",
"layout",
".",
"Height",
"\n",
"topm",
",",
"leftm",
":=",
"layout",
".",
"Top",
",",
"layout",
".",
"Left",
"\n",
"numxtics",
",",
"numytics",
":=",
"layout",
".",
"NumXtics",
",",
"layout",
".",
"NumYtics",
"\n\n",
"// fmt.Printf(\"\\nSet up of X-Range (%d)\\n\", numxtics)",
"c",
".",
"XRange",
".",
"Setup",
"(",
"numxtics",
",",
"numxtics",
"+",
"2",
",",
"width",
",",
"leftm",
",",
"false",
")",
"\n",
"// fmt.Printf(\"\\nSet up of Y-Range (%d)\\n\", numytics)",
"c",
".",
"YRange",
".",
"Setup",
"(",
"numytics",
",",
"numytics",
"+",
"2",
",",
"height",
",",
"topm",
",",
"true",
")",
"\n\n",
"g",
".",
"Begin",
"(",
")",
"\n\n",
"if",
"c",
".",
"Title",
"!=",
"\"",
"\"",
"{",
"drawTitle",
"(",
"g",
",",
"c",
".",
"Title",
",",
"elementStyle",
"(",
"c",
".",
"Options",
",",
"TitleElement",
")",
")",
"\n",
"}",
"\n\n",
"g",
".",
"XAxis",
"(",
"c",
".",
"XRange",
",",
"topm",
"+",
"height",
",",
"topm",
",",
"c",
".",
"Options",
")",
"\n",
"g",
".",
"YAxis",
"(",
"c",
".",
"YRange",
",",
"leftm",
",",
"leftm",
"+",
"width",
",",
"c",
".",
"Options",
")",
"\n\n",
"// Plot Data",
"xf",
",",
"yf",
":=",
"c",
".",
"XRange",
".",
"Data2Screen",
",",
"c",
".",
"YRange",
".",
"Data2Screen",
"\n",
"xmin",
",",
"xmax",
":=",
"c",
".",
"XRange",
".",
"Min",
",",
"c",
".",
"XRange",
".",
"Max",
"\n",
"ymin",
",",
"ymax",
":=",
"c",
".",
"YRange",
".",
"Min",
",",
"c",
".",
"YRange",
".",
"Max",
"\n",
"spf",
":=",
"screenPointFunc",
"(",
"xf",
",",
"yf",
",",
"xmin",
",",
"xmax",
",",
"ymin",
",",
"ymax",
")",
"\n\n",
"for",
"i",
",",
"data",
":=",
"range",
"c",
".",
"Data",
"{",
"style",
":=",
"data",
".",
"Style",
"\n",
"if",
"data",
".",
"Samples",
"!=",
"nil",
"{",
"// Samples",
"points",
":=",
"make",
"(",
"[",
"]",
"EPoint",
",",
"0",
",",
"len",
"(",
"data",
".",
"Samples",
")",
")",
"\n",
"for",
"_",
",",
"d",
":=",
"range",
"data",
".",
"Samples",
"{",
"if",
"d",
".",
"X",
"<",
"xmin",
"||",
"d",
".",
"X",
">",
"xmax",
"||",
"d",
".",
"Y",
"<",
"ymin",
"||",
"d",
".",
"Y",
">",
"ymax",
"{",
"continue",
"\n",
"}",
"\n",
"p",
":=",
"spf",
"(",
"d",
")",
"\n",
"points",
"=",
"append",
"(",
"points",
",",
"p",
")",
"\n",
"}",
"\n",
"g",
".",
"Scatter",
"(",
"points",
",",
"data",
".",
"PlotStyle",
",",
"style",
")",
"\n",
"}",
"else",
"if",
"data",
".",
"Func",
"!=",
"nil",
"{",
"c",
".",
"drawFunction",
"(",
"g",
",",
"i",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"!",
"c",
".",
"Key",
".",
"Hide",
"{",
"g",
".",
"Key",
"(",
"layout",
".",
"KeyX",
",",
"layout",
".",
"KeyY",
",",
"c",
".",
"Key",
",",
"c",
".",
"Options",
")",
"\n",
"}",
"\n\n",
"g",
".",
"End",
"(",
")",
"\n",
"}"
] | // Plot outputs the scatter chart to the graphic output g. | [
"Plot",
"outputs",
"the",
"scatter",
"chart",
"to",
"the",
"graphic",
"output",
"g",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/scatter.go#L129-L182 | train |
vdobler/chart | scatter.go | clipPoint | func (c *ScatterChart) clipPoint(in, out EPoint, min, max float64) (p EPoint) {
// fmt.Printf("clipPoint: in (%g,%g), out(%g,%g) min/max=%g/%g\n", in.X, in.Y, out.X, out.Y, min, max)
dx, dy := in.X-out.X, in.Y-out.Y
var y float64
if out.Y <= min {
y = min
} else {
y = max
}
x := in.X + dx*(y-in.Y)/dy
p.X, p.Y = x, y
p.DeltaX, p.DeltaY = math.NaN(), math.NaN()
return
} | go | func (c *ScatterChart) clipPoint(in, out EPoint, min, max float64) (p EPoint) {
// fmt.Printf("clipPoint: in (%g,%g), out(%g,%g) min/max=%g/%g\n", in.X, in.Y, out.X, out.Y, min, max)
dx, dy := in.X-out.X, in.Y-out.Y
var y float64
if out.Y <= min {
y = min
} else {
y = max
}
x := in.X + dx*(y-in.Y)/dy
p.X, p.Y = x, y
p.DeltaX, p.DeltaY = math.NaN(), math.NaN()
return
} | [
"func",
"(",
"c",
"*",
"ScatterChart",
")",
"clipPoint",
"(",
"in",
",",
"out",
"EPoint",
",",
"min",
",",
"max",
"float64",
")",
"(",
"p",
"EPoint",
")",
"{",
"// fmt.Printf(\"clipPoint: in (%g,%g), out(%g,%g) min/max=%g/%g\\n\", in.X, in.Y, out.X, out.Y, min, max)",
"dx",
",",
"dy",
":=",
"in",
".",
"X",
"-",
"out",
".",
"X",
",",
"in",
".",
"Y",
"-",
"out",
".",
"Y",
"\n\n",
"var",
"y",
"float64",
"\n",
"if",
"out",
".",
"Y",
"<=",
"min",
"{",
"y",
"=",
"min",
"\n",
"}",
"else",
"{",
"y",
"=",
"max",
"\n",
"}",
"\n",
"x",
":=",
"in",
".",
"X",
"+",
"dx",
"*",
"(",
"y",
"-",
"in",
".",
"Y",
")",
"/",
"dy",
"\n",
"p",
".",
"X",
",",
"p",
".",
"Y",
"=",
"x",
",",
"y",
"\n",
"p",
".",
"DeltaX",
",",
"p",
".",
"DeltaY",
"=",
"math",
".",
"NaN",
"(",
")",
",",
"math",
".",
"NaN",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Point in is in valid y range, out is out. Return p which clips the line from in to out to valid y range | [
"Point",
"in",
"is",
"in",
"valid",
"y",
"range",
"out",
"is",
"out",
".",
"Return",
"p",
"which",
"clips",
"the",
"line",
"from",
"in",
"to",
"out",
"to",
"valid",
"y",
"range"
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/scatter.go#L267-L281 | train |
vdobler/chart | scatter.go | screenPointFunc | func screenPointFunc(xf, yf func(float64) int, xmin, xmax, ymin, ymax float64) (spf func(EPoint) EPoint) {
spf = func(d EPoint) (p EPoint) {
xl, yl, xh, yh := d.BoundingBox()
// fmt.Printf("OrigBB: %.1f %.1f %.1f %.1f (%.1f,%.1f)\n", xl,yl,xh,yh,d.X,d.Y)
if xl < xmin {
xl = xmin
}
if xh > xmax {
xh = xmax
}
if yl < ymin {
yl = ymin
}
if yh > ymax {
yh = ymax
}
// fmt.Printf("ClippedBB: %.1f %.1f %.1f %.1f\n", xl,yl,xh,yh)
x := float64(xf(d.X))
y := float64(yf(d.Y))
xsl, xsh := float64(xf(xl)), float64(xf(xh))
ysl, ysh := float64(yf(yl)), float64(yf(yh))
// fmt.Printf("ScreenBB: %.0f %.0f %.0f %.0f (%.0f,%.0f)\n", xsl,ysl,xsh,ysh,x,y)
dx, dy := math.NaN(), math.NaN()
var xo, yo float64
if xsl != xsh {
dx = math.Abs(xsh - xsl)
xo = xsl - x + dx/2
}
if ysl != ysh {
dy = math.Abs(ysh - ysl)
yo = ysh - y + dy/2
}
// fmt.Printf(" >> dx=%.0f dy=%.0f xo=%.0f yo=%.0f\n", dx,dy,xo,yo)
p = EPoint{X: x, Y: y, DeltaX: dx, DeltaY: dy, OffX: xo, OffY: yo}
return
/**************************
if xl < xmin { // happens only if d.Delta!=0,NaN
a := xmin - xl
d.DeltaX -= a
d.OffX += a / 2
}
if xh > xmax {
a := xh - xmax
d.DeltaX -= a
d.OffX -= a / 2
}
if yl < ymin { // happens only if d.Delta!=0,NaN
a := ymin - yl
d.DeltaY -= a
d.OffY += a / 2
}
if yh > ymax {
a := yh - ymax
d.DeltaY -= a
d.OffY -= a / 2
}
x := xf(d.X)
y := yf(d.Y)
dx, dy := math.NaN(), math.NaN()
var xo, yo float64
if !math.IsNaN(d.DeltaX) {
dx = float64(xf(d.DeltaX) - xf(0)) // TODO: abs?
xo = float64(xf(d.OffX) - xf(0))
}
if !math.IsNaN(d.DeltaY) {
dy = float64(yf(d.DeltaY) - yf(0)) // TODO: abs?
yo = float64(yf(d.OffY) - yf(0))
}
// fmt.Printf("Point %d: %f\n", i, dx)
p = EPoint{X: float64(x), Y: float64(y), DeltaX: dx, DeltaY: dy, OffX: xo, OffY: yo}
return
*********************/
}
return
} | go | func screenPointFunc(xf, yf func(float64) int, xmin, xmax, ymin, ymax float64) (spf func(EPoint) EPoint) {
spf = func(d EPoint) (p EPoint) {
xl, yl, xh, yh := d.BoundingBox()
// fmt.Printf("OrigBB: %.1f %.1f %.1f %.1f (%.1f,%.1f)\n", xl,yl,xh,yh,d.X,d.Y)
if xl < xmin {
xl = xmin
}
if xh > xmax {
xh = xmax
}
if yl < ymin {
yl = ymin
}
if yh > ymax {
yh = ymax
}
// fmt.Printf("ClippedBB: %.1f %.1f %.1f %.1f\n", xl,yl,xh,yh)
x := float64(xf(d.X))
y := float64(yf(d.Y))
xsl, xsh := float64(xf(xl)), float64(xf(xh))
ysl, ysh := float64(yf(yl)), float64(yf(yh))
// fmt.Printf("ScreenBB: %.0f %.0f %.0f %.0f (%.0f,%.0f)\n", xsl,ysl,xsh,ysh,x,y)
dx, dy := math.NaN(), math.NaN()
var xo, yo float64
if xsl != xsh {
dx = math.Abs(xsh - xsl)
xo = xsl - x + dx/2
}
if ysl != ysh {
dy = math.Abs(ysh - ysl)
yo = ysh - y + dy/2
}
// fmt.Printf(" >> dx=%.0f dy=%.0f xo=%.0f yo=%.0f\n", dx,dy,xo,yo)
p = EPoint{X: x, Y: y, DeltaX: dx, DeltaY: dy, OffX: xo, OffY: yo}
return
/**************************
if xl < xmin { // happens only if d.Delta!=0,NaN
a := xmin - xl
d.DeltaX -= a
d.OffX += a / 2
}
if xh > xmax {
a := xh - xmax
d.DeltaX -= a
d.OffX -= a / 2
}
if yl < ymin { // happens only if d.Delta!=0,NaN
a := ymin - yl
d.DeltaY -= a
d.OffY += a / 2
}
if yh > ymax {
a := yh - ymax
d.DeltaY -= a
d.OffY -= a / 2
}
x := xf(d.X)
y := yf(d.Y)
dx, dy := math.NaN(), math.NaN()
var xo, yo float64
if !math.IsNaN(d.DeltaX) {
dx = float64(xf(d.DeltaX) - xf(0)) // TODO: abs?
xo = float64(xf(d.OffX) - xf(0))
}
if !math.IsNaN(d.DeltaY) {
dy = float64(yf(d.DeltaY) - yf(0)) // TODO: abs?
yo = float64(yf(d.OffY) - yf(0))
}
// fmt.Printf("Point %d: %f\n", i, dx)
p = EPoint{X: float64(x), Y: float64(y), DeltaX: dx, DeltaY: dy, OffX: xo, OffY: yo}
return
*********************/
}
return
} | [
"func",
"screenPointFunc",
"(",
"xf",
",",
"yf",
"func",
"(",
"float64",
")",
"int",
",",
"xmin",
",",
"xmax",
",",
"ymin",
",",
"ymax",
"float64",
")",
"(",
"spf",
"func",
"(",
"EPoint",
")",
"EPoint",
")",
"{",
"spf",
"=",
"func",
"(",
"d",
"EPoint",
")",
"(",
"p",
"EPoint",
")",
"{",
"xl",
",",
"yl",
",",
"xh",
",",
"yh",
":=",
"d",
".",
"BoundingBox",
"(",
")",
"\n",
"// fmt.Printf(\"OrigBB: %.1f %.1f %.1f %.1f (%.1f,%.1f)\\n\", xl,yl,xh,yh,d.X,d.Y)",
"if",
"xl",
"<",
"xmin",
"{",
"xl",
"=",
"xmin",
"\n",
"}",
"\n",
"if",
"xh",
">",
"xmax",
"{",
"xh",
"=",
"xmax",
"\n",
"}",
"\n",
"if",
"yl",
"<",
"ymin",
"{",
"yl",
"=",
"ymin",
"\n",
"}",
"\n",
"if",
"yh",
">",
"ymax",
"{",
"yh",
"=",
"ymax",
"\n",
"}",
"\n",
"// fmt.Printf(\"ClippedBB: %.1f %.1f %.1f %.1f\\n\", xl,yl,xh,yh)",
"x",
":=",
"float64",
"(",
"xf",
"(",
"d",
".",
"X",
")",
")",
"\n",
"y",
":=",
"float64",
"(",
"yf",
"(",
"d",
".",
"Y",
")",
")",
"\n",
"xsl",
",",
"xsh",
":=",
"float64",
"(",
"xf",
"(",
"xl",
")",
")",
",",
"float64",
"(",
"xf",
"(",
"xh",
")",
")",
"\n",
"ysl",
",",
"ysh",
":=",
"float64",
"(",
"yf",
"(",
"yl",
")",
")",
",",
"float64",
"(",
"yf",
"(",
"yh",
")",
")",
"\n",
"// fmt.Printf(\"ScreenBB: %.0f %.0f %.0f %.0f (%.0f,%.0f)\\n\", xsl,ysl,xsh,ysh,x,y)",
"dx",
",",
"dy",
":=",
"math",
".",
"NaN",
"(",
")",
",",
"math",
".",
"NaN",
"(",
")",
"\n",
"var",
"xo",
",",
"yo",
"float64",
"\n\n",
"if",
"xsl",
"!=",
"xsh",
"{",
"dx",
"=",
"math",
".",
"Abs",
"(",
"xsh",
"-",
"xsl",
")",
"\n",
"xo",
"=",
"xsl",
"-",
"x",
"+",
"dx",
"/",
"2",
"\n",
"}",
"\n",
"if",
"ysl",
"!=",
"ysh",
"{",
"dy",
"=",
"math",
".",
"Abs",
"(",
"ysh",
"-",
"ysl",
")",
"\n",
"yo",
"=",
"ysh",
"-",
"y",
"+",
"dy",
"/",
"2",
"\n",
"}",
"\n",
"// fmt.Printf(\" >> dx=%.0f dy=%.0f xo=%.0f yo=%.0f\\n\", dx,dy,xo,yo)",
"p",
"=",
"EPoint",
"{",
"X",
":",
"x",
",",
"Y",
":",
"y",
",",
"DeltaX",
":",
"dx",
",",
"DeltaY",
":",
"dy",
",",
"OffX",
":",
"xo",
",",
"OffY",
":",
"yo",
"}",
"\n",
"return",
"\n\n",
"/**************************\n\t\tif xl < xmin { // happens only if d.Delta!=0,NaN\n\t\t\ta := xmin - xl\n\t\t\td.DeltaX -= a\n\t\t\td.OffX += a / 2\n\t\t}\n\t\tif xh > xmax {\n\t\t\ta := xh - xmax\n\t\t\td.DeltaX -= a\n\t\t\td.OffX -= a / 2\n\t\t}\n\t\tif yl < ymin { // happens only if d.Delta!=0,NaN\n\t\t\ta := ymin - yl\n\t\t\td.DeltaY -= a\n\t\t\td.OffY += a / 2\n\t\t}\n\t\tif yh > ymax {\n\t\t\ta := yh - ymax\n\t\t\td.DeltaY -= a\n\t\t\td.OffY -= a / 2\n\t\t}\n\n\t\tx := xf(d.X)\n\t\ty := yf(d.Y)\n\t\tdx, dy := math.NaN(), math.NaN()\n\t\tvar xo, yo float64\n\t\tif !math.IsNaN(d.DeltaX) {\n\t\t\tdx = float64(xf(d.DeltaX) - xf(0)) // TODO: abs?\n\t\t\txo = float64(xf(d.OffX) - xf(0))\n\t\t}\n\t\tif !math.IsNaN(d.DeltaY) {\n\t\t\tdy = float64(yf(d.DeltaY) - yf(0)) // TODO: abs?\n\t\t\tyo = float64(yf(d.OffY) - yf(0))\n\t\t}\n\t\t// fmt.Printf(\"Point %d: %f\\n\", i, dx)\n\t\tp = EPoint{X: float64(x), Y: float64(y), DeltaX: dx, DeltaY: dy, OffX: xo, OffY: yo}\n\t\treturn\n\t\t *********************/",
"}",
"\n",
"return",
"\n",
"}"
] | // Set up function which handles mappig data->screen coordinates and does
// proper clipping on the error bars. | [
"Set",
"up",
"function",
"which",
"handles",
"mappig",
"data",
"-",
">",
"screen",
"coordinates",
"and",
"does",
"proper",
"clipping",
"on",
"the",
"error",
"bars",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/scatter.go#L304-L384 | train |
vdobler/chart | imgg/image.go | New | func New(width, height int, bgcol color.RGBA, font *truetype.Font, fontsize map[chart.FontSize]float64) *ImageGraphics {
img := image.NewRGBA(image.Rect(0, 0, width, height))
gc := draw2dimg.NewGraphicContext(img)
gc.SetLineJoin(draw2d.BevelJoin)
gc.SetLineCap(draw2d.SquareCap)
gc.SetStrokeColor(image.Black)
gc.SetFillColor(bgcol)
gc.Translate(0.5, 0.5)
gc.Clear()
if font == nil {
font = defaultFont
}
if len(fontsize) == 0 {
fontsize = ConstructFontSizes(13)
}
return &ImageGraphics{Image: img, x0: 0, y0: 0, w: width, h: height,
bg: bgcol, gc: gc, font: font, fs: fontsize}
} | go | func New(width, height int, bgcol color.RGBA, font *truetype.Font, fontsize map[chart.FontSize]float64) *ImageGraphics {
img := image.NewRGBA(image.Rect(0, 0, width, height))
gc := draw2dimg.NewGraphicContext(img)
gc.SetLineJoin(draw2d.BevelJoin)
gc.SetLineCap(draw2d.SquareCap)
gc.SetStrokeColor(image.Black)
gc.SetFillColor(bgcol)
gc.Translate(0.5, 0.5)
gc.Clear()
if font == nil {
font = defaultFont
}
if len(fontsize) == 0 {
fontsize = ConstructFontSizes(13)
}
return &ImageGraphics{Image: img, x0: 0, y0: 0, w: width, h: height,
bg: bgcol, gc: gc, font: font, fs: fontsize}
} | [
"func",
"New",
"(",
"width",
",",
"height",
"int",
",",
"bgcol",
"color",
".",
"RGBA",
",",
"font",
"*",
"truetype",
".",
"Font",
",",
"fontsize",
"map",
"[",
"chart",
".",
"FontSize",
"]",
"float64",
")",
"*",
"ImageGraphics",
"{",
"img",
":=",
"image",
".",
"NewRGBA",
"(",
"image",
".",
"Rect",
"(",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
")",
"\n",
"gc",
":=",
"draw2dimg",
".",
"NewGraphicContext",
"(",
"img",
")",
"\n",
"gc",
".",
"SetLineJoin",
"(",
"draw2d",
".",
"BevelJoin",
")",
"\n",
"gc",
".",
"SetLineCap",
"(",
"draw2d",
".",
"SquareCap",
")",
"\n",
"gc",
".",
"SetStrokeColor",
"(",
"image",
".",
"Black",
")",
"\n",
"gc",
".",
"SetFillColor",
"(",
"bgcol",
")",
"\n",
"gc",
".",
"Translate",
"(",
"0.5",
",",
"0.5",
")",
"\n",
"gc",
".",
"Clear",
"(",
")",
"\n",
"if",
"font",
"==",
"nil",
"{",
"font",
"=",
"defaultFont",
"\n",
"}",
"\n",
"if",
"len",
"(",
"fontsize",
")",
"==",
"0",
"{",
"fontsize",
"=",
"ConstructFontSizes",
"(",
"13",
")",
"\n",
"}",
"\n",
"return",
"&",
"ImageGraphics",
"{",
"Image",
":",
"img",
",",
"x0",
":",
"0",
",",
"y0",
":",
"0",
",",
"w",
":",
"width",
",",
"h",
":",
"height",
",",
"bg",
":",
"bgcol",
",",
"gc",
":",
"gc",
",",
"font",
":",
"font",
",",
"fs",
":",
"fontsize",
"}",
"\n",
"}"
] | // New creates a new ImageGraphics including an image.RGBA of dimension w x h
// with background bgcol. If font is nil it will use a builtin font.
// If fontsize is empty useful default are used. | [
"New",
"creates",
"a",
"new",
"ImageGraphics",
"including",
"an",
"image",
".",
"RGBA",
"of",
"dimension",
"w",
"x",
"h",
"with",
"background",
"bgcol",
".",
"If",
"font",
"is",
"nil",
"it",
"will",
"use",
"a",
"builtin",
"font",
".",
"If",
"fontsize",
"is",
"empty",
"useful",
"default",
"are",
"used",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/imgg/image.go#L46-L63 | train |
vdobler/chart | imgg/image.go | textBox | func (ig *ImageGraphics) textBox(t string, font chart.Font, textCol color.Color) image.Image {
// Initialize the context.
bg := image.NewUniform(color.Alpha{0})
fg := image.NewUniform(textCol)
width := ig.TextLen(t, font)
size := ig.relFontsizeToPixel(font.Size)
c := freetype.NewContext()
c.SetDPI(dpi)
c.SetFont(ig.font)
c.SetFontSize(size)
bb := ig.font.Bounds(c.PointToFixed(float64(size)))
bbDelta := bb.Max.Sub(bb.Min)
height := int(bbDelta.Y+32) >> 6
canvas := image.NewRGBA(image.Rect(0, 0, width, height))
draw.Draw(canvas, canvas.Bounds(), bg, image.ZP, draw.Src)
c.SetDst(canvas)
c.SetSrc(fg)
c.SetClip(canvas.Bounds())
// Draw the text.
extent, err := c.DrawString(t, fixed.Point26_6{X: 0, Y: bb.Max.Y})
if err != nil {
log.Println(err)
return nil
}
// Ugly heuristic hack: font bounds are pretty high resulting in white top border: Trim.
topskip := 1
if size > 15 {
topskip = 2
} else if size > 20 {
topskip = 3
}
return canvas.SubImage(image.Rect(0, topskip, int(extent.X)>>6, height))
} | go | func (ig *ImageGraphics) textBox(t string, font chart.Font, textCol color.Color) image.Image {
// Initialize the context.
bg := image.NewUniform(color.Alpha{0})
fg := image.NewUniform(textCol)
width := ig.TextLen(t, font)
size := ig.relFontsizeToPixel(font.Size)
c := freetype.NewContext()
c.SetDPI(dpi)
c.SetFont(ig.font)
c.SetFontSize(size)
bb := ig.font.Bounds(c.PointToFixed(float64(size)))
bbDelta := bb.Max.Sub(bb.Min)
height := int(bbDelta.Y+32) >> 6
canvas := image.NewRGBA(image.Rect(0, 0, width, height))
draw.Draw(canvas, canvas.Bounds(), bg, image.ZP, draw.Src)
c.SetDst(canvas)
c.SetSrc(fg)
c.SetClip(canvas.Bounds())
// Draw the text.
extent, err := c.DrawString(t, fixed.Point26_6{X: 0, Y: bb.Max.Y})
if err != nil {
log.Println(err)
return nil
}
// Ugly heuristic hack: font bounds are pretty high resulting in white top border: Trim.
topskip := 1
if size > 15 {
topskip = 2
} else if size > 20 {
topskip = 3
}
return canvas.SubImage(image.Rect(0, topskip, int(extent.X)>>6, height))
} | [
"func",
"(",
"ig",
"*",
"ImageGraphics",
")",
"textBox",
"(",
"t",
"string",
",",
"font",
"chart",
".",
"Font",
",",
"textCol",
"color",
".",
"Color",
")",
"image",
".",
"Image",
"{",
"// Initialize the context.",
"bg",
":=",
"image",
".",
"NewUniform",
"(",
"color",
".",
"Alpha",
"{",
"0",
"}",
")",
"\n",
"fg",
":=",
"image",
".",
"NewUniform",
"(",
"textCol",
")",
"\n",
"width",
":=",
"ig",
".",
"TextLen",
"(",
"t",
",",
"font",
")",
"\n",
"size",
":=",
"ig",
".",
"relFontsizeToPixel",
"(",
"font",
".",
"Size",
")",
"\n\n",
"c",
":=",
"freetype",
".",
"NewContext",
"(",
")",
"\n",
"c",
".",
"SetDPI",
"(",
"dpi",
")",
"\n",
"c",
".",
"SetFont",
"(",
"ig",
".",
"font",
")",
"\n",
"c",
".",
"SetFontSize",
"(",
"size",
")",
"\n",
"bb",
":=",
"ig",
".",
"font",
".",
"Bounds",
"(",
"c",
".",
"PointToFixed",
"(",
"float64",
"(",
"size",
")",
")",
")",
"\n",
"bbDelta",
":=",
"bb",
".",
"Max",
".",
"Sub",
"(",
"bb",
".",
"Min",
")",
"\n\n",
"height",
":=",
"int",
"(",
"bbDelta",
".",
"Y",
"+",
"32",
")",
">>",
"6",
"\n",
"canvas",
":=",
"image",
".",
"NewRGBA",
"(",
"image",
".",
"Rect",
"(",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
")",
"\n",
"draw",
".",
"Draw",
"(",
"canvas",
",",
"canvas",
".",
"Bounds",
"(",
")",
",",
"bg",
",",
"image",
".",
"ZP",
",",
"draw",
".",
"Src",
")",
"\n",
"c",
".",
"SetDst",
"(",
"canvas",
")",
"\n",
"c",
".",
"SetSrc",
"(",
"fg",
")",
"\n",
"c",
".",
"SetClip",
"(",
"canvas",
".",
"Bounds",
"(",
")",
")",
"\n",
"// Draw the text.",
"extent",
",",
"err",
":=",
"c",
".",
"DrawString",
"(",
"t",
",",
"fixed",
".",
"Point26_6",
"{",
"X",
":",
"0",
",",
"Y",
":",
"bb",
".",
"Max",
".",
"Y",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Println",
"(",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Ugly heuristic hack: font bounds are pretty high resulting in white top border: Trim.",
"topskip",
":=",
"1",
"\n",
"if",
"size",
">",
"15",
"{",
"topskip",
"=",
"2",
"\n",
"}",
"else",
"if",
"size",
">",
"20",
"{",
"topskip",
"=",
"3",
"\n",
"}",
"\n",
"return",
"canvas",
".",
"SubImage",
"(",
"image",
".",
"Rect",
"(",
"0",
",",
"topskip",
",",
"int",
"(",
"extent",
".",
"X",
")",
">>",
"6",
",",
"height",
")",
")",
"\n",
"}"
] | // textBox renders t into a tight fitting image | [
"textBox",
"renders",
"t",
"into",
"a",
"tight",
"fitting",
"image"
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/imgg/image.go#L246-L281 | train |
vdobler/chart | txtg/text.go | New | func New(w, h int) *TextGraphics {
tg := TextGraphics{}
tg.tb = NewTextBuf(w, h)
tg.w, tg.h = w, h
tg.xoff = -1
return &tg
} | go | func New(w, h int) *TextGraphics {
tg := TextGraphics{}
tg.tb = NewTextBuf(w, h)
tg.w, tg.h = w, h
tg.xoff = -1
return &tg
} | [
"func",
"New",
"(",
"w",
",",
"h",
"int",
")",
"*",
"TextGraphics",
"{",
"tg",
":=",
"TextGraphics",
"{",
"}",
"\n",
"tg",
".",
"tb",
"=",
"NewTextBuf",
"(",
"w",
",",
"h",
")",
"\n",
"tg",
".",
"w",
",",
"tg",
".",
"h",
"=",
"w",
",",
"h",
"\n",
"tg",
".",
"xoff",
"=",
"-",
"1",
"\n",
"return",
"&",
"tg",
"\n",
"}"
] | // New creates a TextGraphic of dimensions w x h. | [
"New",
"creates",
"a",
"TextGraphic",
"of",
"dimensions",
"w",
"x",
"h",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/txtg/text.go#L17-L23 | train |
vdobler/chart | hist.go | AddData | func (c *HistChart) AddData(name string, data []float64, style Style) {
// Style
if style.empty() {
style = AutoStyle(len(c.Data), true)
}
// Init axis, add data, autoscale
if len(c.Data) == 0 {
c.XRange.init()
}
c.Data = append(c.Data, HistChartData{name, style, data})
for _, d := range data {
c.XRange.autoscale(d)
}
// Key/Legend
if name != "" {
c.Key.Entries = append(c.Key.Entries, KeyEntry{Text: name, Style: style, PlotStyle: PlotStyleBox})
}
} | go | func (c *HistChart) AddData(name string, data []float64, style Style) {
// Style
if style.empty() {
style = AutoStyle(len(c.Data), true)
}
// Init axis, add data, autoscale
if len(c.Data) == 0 {
c.XRange.init()
}
c.Data = append(c.Data, HistChartData{name, style, data})
for _, d := range data {
c.XRange.autoscale(d)
}
// Key/Legend
if name != "" {
c.Key.Entries = append(c.Key.Entries, KeyEntry{Text: name, Style: style, PlotStyle: PlotStyleBox})
}
} | [
"func",
"(",
"c",
"*",
"HistChart",
")",
"AddData",
"(",
"name",
"string",
",",
"data",
"[",
"]",
"float64",
",",
"style",
"Style",
")",
"{",
"// Style",
"if",
"style",
".",
"empty",
"(",
")",
"{",
"style",
"=",
"AutoStyle",
"(",
"len",
"(",
"c",
".",
"Data",
")",
",",
"true",
")",
"\n",
"}",
"\n\n",
"// Init axis, add data, autoscale",
"if",
"len",
"(",
"c",
".",
"Data",
")",
"==",
"0",
"{",
"c",
".",
"XRange",
".",
"init",
"(",
")",
"\n",
"}",
"\n",
"c",
".",
"Data",
"=",
"append",
"(",
"c",
".",
"Data",
",",
"HistChartData",
"{",
"name",
",",
"style",
",",
"data",
"}",
")",
"\n",
"for",
"_",
",",
"d",
":=",
"range",
"data",
"{",
"c",
".",
"XRange",
".",
"autoscale",
"(",
"d",
")",
"\n",
"}",
"\n\n",
"// Key/Legend",
"if",
"name",
"!=",
"\"",
"\"",
"{",
"c",
".",
"Key",
".",
"Entries",
"=",
"append",
"(",
"c",
".",
"Key",
".",
"Entries",
",",
"KeyEntry",
"{",
"Text",
":",
"name",
",",
"Style",
":",
"style",
",",
"PlotStyle",
":",
"PlotStyleBox",
"}",
")",
"\n",
"}",
"\n",
"}"
] | // AddData will add data to the plot. Legend will be updated by name. | [
"AddData",
"will",
"add",
"data",
"to",
"the",
"plot",
".",
"Legend",
"will",
"be",
"updated",
"by",
"name",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/hist.go#L93-L112 | train |
vdobler/chart | hist.go | AddDataGeneric | func (c *HistChart) AddDataGeneric(name string, data []Value, style Style) {
fdata := make([]float64, len(data))
for i, d := range data {
fdata[i] = d.XVal()
}
c.AddData(name, fdata, style)
} | go | func (c *HistChart) AddDataGeneric(name string, data []Value, style Style) {
fdata := make([]float64, len(data))
for i, d := range data {
fdata[i] = d.XVal()
}
c.AddData(name, fdata, style)
} | [
"func",
"(",
"c",
"*",
"HistChart",
")",
"AddDataGeneric",
"(",
"name",
"string",
",",
"data",
"[",
"]",
"Value",
",",
"style",
"Style",
")",
"{",
"fdata",
":=",
"make",
"(",
"[",
"]",
"float64",
",",
"len",
"(",
"data",
")",
")",
"\n",
"for",
"i",
",",
"d",
":=",
"range",
"data",
"{",
"fdata",
"[",
"i",
"]",
"=",
"d",
".",
"XVal",
"(",
")",
"\n",
"}",
"\n",
"c",
".",
"AddData",
"(",
"name",
",",
"fdata",
",",
"style",
")",
"\n",
"}"
] | // AddDataGeneric is the generic version which allows the addition of any type
// implementing the Value interface. | [
"AddDataGeneric",
"is",
"the",
"generic",
"version",
"which",
"allows",
"the",
"addition",
"of",
"any",
"type",
"implementing",
"the",
"Value",
"interface",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/hist.go#L126-L132 | train |
vdobler/chart | hist.go | binify | func (c *HistChart) binify(binStart, binWidth float64, binCnt int) (freqs [][]float64, max float64) {
x2bin := func(x float64) int { return int((x - binStart) / binWidth) }
freqs = make([][]float64, len(c.Data)) // freqs[d][b] is frequency/count of bin b in dataset d
max = 0
for i, data := range c.Data {
freq := make([]float64, binCnt)
drops := 0
for _, x := range data.Samples {
bin := x2bin(x)
if bin < 0 || bin >= binCnt {
// fmt.Printf("!!!!! Lost %.3f (bin=%d)\n", x, bin)
drops++
continue
}
freq[bin] = freq[bin] + 1
//fmt.Printf("Value %.2f sorted into bin %d, count now %d\n", x, bin, int(freq[bin]))
}
// scale if requested and determine max
n := float64(len(data.Samples) - drops)
// DebugLogger.Printf("Dataset %d has %d samples (by %d drops).\n", i, int(n), drops)
ff := 0.0
for bin := 0; bin < binCnt; bin++ {
if !c.Counts {
freq[bin] = 100 * freq[bin] / n
}
ff += freq[bin]
if freq[bin] > max {
max = freq[bin]
}
}
freqs[i] = freq
}
// DebugLogger.Printf("Maximum : %.2f\n", max)
if c.Stacked { // recalculate max
max = 0
for bin := 0; bin < binCnt; bin++ {
sum := 0.0
for i := range freqs {
sum += freqs[i][bin]
}
// fmt.Printf("sum of bin %d = %d\n", bin, sum)
if sum > max {
max = sum
}
}
// DebugLogger.Printf("Re-Maxed (stacked) to: %.2f\n", max)
}
return
} | go | func (c *HistChart) binify(binStart, binWidth float64, binCnt int) (freqs [][]float64, max float64) {
x2bin := func(x float64) int { return int((x - binStart) / binWidth) }
freqs = make([][]float64, len(c.Data)) // freqs[d][b] is frequency/count of bin b in dataset d
max = 0
for i, data := range c.Data {
freq := make([]float64, binCnt)
drops := 0
for _, x := range data.Samples {
bin := x2bin(x)
if bin < 0 || bin >= binCnt {
// fmt.Printf("!!!!! Lost %.3f (bin=%d)\n", x, bin)
drops++
continue
}
freq[bin] = freq[bin] + 1
//fmt.Printf("Value %.2f sorted into bin %d, count now %d\n", x, bin, int(freq[bin]))
}
// scale if requested and determine max
n := float64(len(data.Samples) - drops)
// DebugLogger.Printf("Dataset %d has %d samples (by %d drops).\n", i, int(n), drops)
ff := 0.0
for bin := 0; bin < binCnt; bin++ {
if !c.Counts {
freq[bin] = 100 * freq[bin] / n
}
ff += freq[bin]
if freq[bin] > max {
max = freq[bin]
}
}
freqs[i] = freq
}
// DebugLogger.Printf("Maximum : %.2f\n", max)
if c.Stacked { // recalculate max
max = 0
for bin := 0; bin < binCnt; bin++ {
sum := 0.0
for i := range freqs {
sum += freqs[i][bin]
}
// fmt.Printf("sum of bin %d = %d\n", bin, sum)
if sum > max {
max = sum
}
}
// DebugLogger.Printf("Re-Maxed (stacked) to: %.2f\n", max)
}
return
} | [
"func",
"(",
"c",
"*",
"HistChart",
")",
"binify",
"(",
"binStart",
",",
"binWidth",
"float64",
",",
"binCnt",
"int",
")",
"(",
"freqs",
"[",
"]",
"[",
"]",
"float64",
",",
"max",
"float64",
")",
"{",
"x2bin",
":=",
"func",
"(",
"x",
"float64",
")",
"int",
"{",
"return",
"int",
"(",
"(",
"x",
"-",
"binStart",
")",
"/",
"binWidth",
")",
"}",
"\n\n",
"freqs",
"=",
"make",
"(",
"[",
"]",
"[",
"]",
"float64",
",",
"len",
"(",
"c",
".",
"Data",
")",
")",
"// freqs[d][b] is frequency/count of bin b in dataset d",
"\n",
"max",
"=",
"0",
"\n",
"for",
"i",
",",
"data",
":=",
"range",
"c",
".",
"Data",
"{",
"freq",
":=",
"make",
"(",
"[",
"]",
"float64",
",",
"binCnt",
")",
"\n",
"drops",
":=",
"0",
"\n",
"for",
"_",
",",
"x",
":=",
"range",
"data",
".",
"Samples",
"{",
"bin",
":=",
"x2bin",
"(",
"x",
")",
"\n",
"if",
"bin",
"<",
"0",
"||",
"bin",
">=",
"binCnt",
"{",
"// fmt.Printf(\"!!!!! Lost %.3f (bin=%d)\\n\", x, bin)",
"drops",
"++",
"\n",
"continue",
"\n",
"}",
"\n",
"freq",
"[",
"bin",
"]",
"=",
"freq",
"[",
"bin",
"]",
"+",
"1",
"\n",
"//fmt.Printf(\"Value %.2f sorted into bin %d, count now %d\\n\", x, bin, int(freq[bin]))",
"}",
"\n",
"// scale if requested and determine max",
"n",
":=",
"float64",
"(",
"len",
"(",
"data",
".",
"Samples",
")",
"-",
"drops",
")",
"\n",
"// DebugLogger.Printf(\"Dataset %d has %d samples (by %d drops).\\n\", i, int(n), drops)",
"ff",
":=",
"0.0",
"\n",
"for",
"bin",
":=",
"0",
";",
"bin",
"<",
"binCnt",
";",
"bin",
"++",
"{",
"if",
"!",
"c",
".",
"Counts",
"{",
"freq",
"[",
"bin",
"]",
"=",
"100",
"*",
"freq",
"[",
"bin",
"]",
"/",
"n",
"\n",
"}",
"\n",
"ff",
"+=",
"freq",
"[",
"bin",
"]",
"\n",
"if",
"freq",
"[",
"bin",
"]",
">",
"max",
"{",
"max",
"=",
"freq",
"[",
"bin",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"freqs",
"[",
"i",
"]",
"=",
"freq",
"\n",
"}",
"\n",
"// DebugLogger.Printf(\"Maximum : %.2f\\n\", max)",
"if",
"c",
".",
"Stacked",
"{",
"// recalculate max",
"max",
"=",
"0",
"\n",
"for",
"bin",
":=",
"0",
";",
"bin",
"<",
"binCnt",
";",
"bin",
"++",
"{",
"sum",
":=",
"0.0",
"\n",
"for",
"i",
":=",
"range",
"freqs",
"{",
"sum",
"+=",
"freqs",
"[",
"i",
"]",
"[",
"bin",
"]",
"\n",
"}",
"\n",
"// fmt.Printf(\"sum of bin %d = %d\\n\", bin, sum)",
"if",
"sum",
">",
"max",
"{",
"max",
"=",
"sum",
"\n",
"}",
"\n",
"}",
"\n",
"// DebugLogger.Printf(\"Re-Maxed (stacked) to: %.2f\\n\", max)",
"}",
"\n",
"return",
"\n",
"}"
] | // Prepare binCnt bins of width binWidth starting from binStart and count
// data samples per bin for each data set. If c.Counts is true than the
// absolute counts are returned instead if the frequencies. max is the
// largest y-value which will occur in our plot. | [
"Prepare",
"binCnt",
"bins",
"of",
"width",
"binWidth",
"starting",
"from",
"binStart",
"and",
"count",
"data",
"samples",
"per",
"bin",
"for",
"each",
"data",
"set",
".",
"If",
"c",
".",
"Counts",
"is",
"true",
"than",
"the",
"absolute",
"counts",
"are",
"returned",
"instead",
"if",
"the",
"frequencies",
".",
"max",
"is",
"the",
"largest",
"y",
"-",
"value",
"which",
"will",
"occur",
"in",
"our",
"plot",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/hist.go#L181-L230 | train |
vdobler/chart | time.go | RoundUp | func RoundUp(t time.Time, d TimeDelta) time.Time {
// works only because all TimeDeltas are more than 1.5 times as large as the next lower
shift := d.Seconds()
shift += shift / 2
t = d.RoundDown(t)
t = t.Add(time.Duration(shift) * time.Second)
t = d.RoundDown(t)
DebugLogger.Printf("RoundUp( %s, %s ) --> %s ", t.Format("2006-01-02 15:04:05 (Mon)"), d.String(),
t.Format("2006-01-02 15:04:05 (Mon)"))
return t
} | go | func RoundUp(t time.Time, d TimeDelta) time.Time {
// works only because all TimeDeltas are more than 1.5 times as large as the next lower
shift := d.Seconds()
shift += shift / 2
t = d.RoundDown(t)
t = t.Add(time.Duration(shift) * time.Second)
t = d.RoundDown(t)
DebugLogger.Printf("RoundUp( %s, %s ) --> %s ", t.Format("2006-01-02 15:04:05 (Mon)"), d.String(),
t.Format("2006-01-02 15:04:05 (Mon)"))
return t
} | [
"func",
"RoundUp",
"(",
"t",
"time",
".",
"Time",
",",
"d",
"TimeDelta",
")",
"time",
".",
"Time",
"{",
"// works only because all TimeDeltas are more than 1.5 times as large as the next lower",
"shift",
":=",
"d",
".",
"Seconds",
"(",
")",
"\n",
"shift",
"+=",
"shift",
"/",
"2",
"\n",
"t",
"=",
"d",
".",
"RoundDown",
"(",
"t",
")",
"\n",
"t",
"=",
"t",
".",
"Add",
"(",
"time",
".",
"Duration",
"(",
"shift",
")",
"*",
"time",
".",
"Second",
")",
"\n",
"t",
"=",
"d",
".",
"RoundDown",
"(",
"t",
")",
"\n",
"DebugLogger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"t",
".",
"Format",
"(",
"\"",
"\"",
")",
",",
"d",
".",
"String",
"(",
")",
",",
"t",
".",
"Format",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"t",
"\n",
"}"
] | // RoundUp will round tp up to next "full" d. | [
"RoundUp",
"will",
"round",
"tp",
"up",
"to",
"next",
"full",
"d",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/time.go#L170-L180 | train |
vdobler/chart | time.go | RoundNext | func RoundNext(t time.Time, d TimeDelta) time.Time {
DebugLogger.Printf("RoundNext( %s, %s )", t.Format("2006-01-02 15:04:05 (Mon)"), d.String())
os := t.Unix()
lt := d.RoundDown(t)
shift := d.Seconds()
shift += shift / 2
ut := lt.Add(time.Duration(shift) * time.Second) // see RoundUp()
ut = d.RoundDown(ut)
ld := os - lt.Unix()
ud := ut.Unix() - os
if ld < ud {
return lt
}
return ut
} | go | func RoundNext(t time.Time, d TimeDelta) time.Time {
DebugLogger.Printf("RoundNext( %s, %s )", t.Format("2006-01-02 15:04:05 (Mon)"), d.String())
os := t.Unix()
lt := d.RoundDown(t)
shift := d.Seconds()
shift += shift / 2
ut := lt.Add(time.Duration(shift) * time.Second) // see RoundUp()
ut = d.RoundDown(ut)
ld := os - lt.Unix()
ud := ut.Unix() - os
if ld < ud {
return lt
}
return ut
} | [
"func",
"RoundNext",
"(",
"t",
"time",
".",
"Time",
",",
"d",
"TimeDelta",
")",
"time",
".",
"Time",
"{",
"DebugLogger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"t",
".",
"Format",
"(",
"\"",
"\"",
")",
",",
"d",
".",
"String",
"(",
")",
")",
"\n",
"os",
":=",
"t",
".",
"Unix",
"(",
")",
"\n",
"lt",
":=",
"d",
".",
"RoundDown",
"(",
"t",
")",
"\n",
"shift",
":=",
"d",
".",
"Seconds",
"(",
")",
"\n",
"shift",
"+=",
"shift",
"/",
"2",
"\n",
"ut",
":=",
"lt",
".",
"Add",
"(",
"time",
".",
"Duration",
"(",
"shift",
")",
"*",
"time",
".",
"Second",
")",
"// see RoundUp()",
"\n",
"ut",
"=",
"d",
".",
"RoundDown",
"(",
"ut",
")",
"\n",
"ld",
":=",
"os",
"-",
"lt",
".",
"Unix",
"(",
")",
"\n",
"ud",
":=",
"ut",
".",
"Unix",
"(",
")",
"-",
"os",
"\n",
"if",
"ld",
"<",
"ud",
"{",
"return",
"lt",
"\n",
"}",
"\n",
"return",
"ut",
"\n",
"}"
] | // RoundNext will round t to nearest full d. | [
"RoundNext",
"will",
"round",
"t",
"to",
"nearest",
"full",
"d",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/time.go#L183-L197 | train |
vdobler/chart | time.go | RoundDown | func RoundDown(t time.Time, d TimeDelta) time.Time {
td := d.RoundDown(t)
DebugLogger.Printf("RoundDown( %s, %s ) --> %s", t.Format("2006-01-02 15:04:05 (Mon)"), d.String(),
td.Format("2006-01-02 15:04:05 (Mon)"))
return td
} | go | func RoundDown(t time.Time, d TimeDelta) time.Time {
td := d.RoundDown(t)
DebugLogger.Printf("RoundDown( %s, %s ) --> %s", t.Format("2006-01-02 15:04:05 (Mon)"), d.String(),
td.Format("2006-01-02 15:04:05 (Mon)"))
return td
} | [
"func",
"RoundDown",
"(",
"t",
"time",
".",
"Time",
",",
"d",
"TimeDelta",
")",
"time",
".",
"Time",
"{",
"td",
":=",
"d",
".",
"RoundDown",
"(",
"t",
")",
"\n",
"DebugLogger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"t",
".",
"Format",
"(",
"\"",
"\"",
")",
",",
"d",
".",
"String",
"(",
")",
",",
"td",
".",
"Format",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"td",
"\n",
"}"
] | // RoundDown will round tp down to next "full" d. | [
"RoundDown",
"will",
"round",
"tp",
"down",
"to",
"next",
"full",
"d",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/time.go#L200-L205 | train |
vdobler/chart | pie.go | PercentValue | func PercentValue(value, sum float64) (s string) {
value *= 100 / sum
s = AbsoluteValue(value, sum) + "% "
return
} | go | func PercentValue(value, sum float64) (s string) {
value *= 100 / sum
s = AbsoluteValue(value, sum) + "% "
return
} | [
"func",
"PercentValue",
"(",
"value",
",",
"sum",
"float64",
")",
"(",
"s",
"string",
")",
"{",
"value",
"*=",
"100",
"/",
"sum",
"\n",
"s",
"=",
"AbsoluteValue",
"(",
"value",
",",
"sum",
")",
"+",
"\"",
"\"",
"\n",
"return",
"\n",
"}"
] | // PercentValue formats value as percentage of sum.
// It is a convenience function which can be assigned to the
// PieChart.FmtVal or PieChart.FmtKey field. | [
"PercentValue",
"formats",
"value",
"as",
"percentage",
"of",
"sum",
".",
"It",
"is",
"a",
"convenience",
"function",
"which",
"can",
"be",
"assigned",
"to",
"the",
"PieChart",
".",
"FmtVal",
"or",
"PieChart",
".",
"FmtKey",
"field",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/pie.go#L57-L61 | train |
vdobler/chart | pie.go | Plot | func (c *PieChart) Plot(g Graphics) {
layout := layout(g, c.Title, "", "", true, true, &c.Key)
width, height := layout.Width, layout.Height
topm, leftm := layout.Top, layout.Left
width += 0
r := imin(height, width) / 2
x0, y0 := leftm+r, topm+r
// Make sure pie fits into plotting area
rshift := int(float64(r) * PieChartHighlight)
if rshift < 6 {
rshift = 6
}
for _, d := range c.Data[0].Samples {
if d.Flag {
// DebugLogger.Printf("Reduced %d by %d", r, rshift)
r -= rshift / 3
break
}
}
g.Begin()
if c.Title != "" {
drawTitle(g, c.Title, elementStyle(c.Options, TitleElement))
}
for _, data := range c.Data {
var sum float64
for _, d := range data.Samples {
sum += d.Val
}
wedges := make([]Wedgeinfo, len(data.Samples))
var ri int = 0
if c.Inner > 0 {
ri = int(float64(r) * c.Inner)
}
var phi float64 = -math.Pi
for j, d := range data.Samples {
style := data.Style[j]
alpha := 2 * math.Pi * d.Val / sum
shift := 0
var t string
if c.FmtVal != nil {
t = c.FmtVal(d.Val, sum)
}
if d.Flag {
shift = rshift
}
wedges[j] = Wedgeinfo{Phi: phi, Psi: phi + alpha, Text: t, Tp: "c",
Style: style, Font: Font{}, Shift: shift}
phi += alpha
}
g.Rings(wedges, x0, y0, r, ri)
r = int(float64(r) * PieChartShrinkage)
}
if !c.Key.Hide {
g.Key(layout.KeyX, layout.KeyY, c.Key, c.Options)
}
g.End()
} | go | func (c *PieChart) Plot(g Graphics) {
layout := layout(g, c.Title, "", "", true, true, &c.Key)
width, height := layout.Width, layout.Height
topm, leftm := layout.Top, layout.Left
width += 0
r := imin(height, width) / 2
x0, y0 := leftm+r, topm+r
// Make sure pie fits into plotting area
rshift := int(float64(r) * PieChartHighlight)
if rshift < 6 {
rshift = 6
}
for _, d := range c.Data[0].Samples {
if d.Flag {
// DebugLogger.Printf("Reduced %d by %d", r, rshift)
r -= rshift / 3
break
}
}
g.Begin()
if c.Title != "" {
drawTitle(g, c.Title, elementStyle(c.Options, TitleElement))
}
for _, data := range c.Data {
var sum float64
for _, d := range data.Samples {
sum += d.Val
}
wedges := make([]Wedgeinfo, len(data.Samples))
var ri int = 0
if c.Inner > 0 {
ri = int(float64(r) * c.Inner)
}
var phi float64 = -math.Pi
for j, d := range data.Samples {
style := data.Style[j]
alpha := 2 * math.Pi * d.Val / sum
shift := 0
var t string
if c.FmtVal != nil {
t = c.FmtVal(d.Val, sum)
}
if d.Flag {
shift = rshift
}
wedges[j] = Wedgeinfo{Phi: phi, Psi: phi + alpha, Text: t, Tp: "c",
Style: style, Font: Font{}, Shift: shift}
phi += alpha
}
g.Rings(wedges, x0, y0, r, ri)
r = int(float64(r) * PieChartShrinkage)
}
if !c.Key.Hide {
g.Key(layout.KeyX, layout.KeyY, c.Key, c.Options)
}
g.End()
} | [
"func",
"(",
"c",
"*",
"PieChart",
")",
"Plot",
"(",
"g",
"Graphics",
")",
"{",
"layout",
":=",
"layout",
"(",
"g",
",",
"c",
".",
"Title",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"true",
",",
"true",
",",
"&",
"c",
".",
"Key",
")",
"\n\n",
"width",
",",
"height",
":=",
"layout",
".",
"Width",
",",
"layout",
".",
"Height",
"\n",
"topm",
",",
"leftm",
":=",
"layout",
".",
"Top",
",",
"layout",
".",
"Left",
"\n",
"width",
"+=",
"0",
"\n\n",
"r",
":=",
"imin",
"(",
"height",
",",
"width",
")",
"/",
"2",
"\n",
"x0",
",",
"y0",
":=",
"leftm",
"+",
"r",
",",
"topm",
"+",
"r",
"\n\n",
"// Make sure pie fits into plotting area",
"rshift",
":=",
"int",
"(",
"float64",
"(",
"r",
")",
"*",
"PieChartHighlight",
")",
"\n",
"if",
"rshift",
"<",
"6",
"{",
"rshift",
"=",
"6",
"\n",
"}",
"\n",
"for",
"_",
",",
"d",
":=",
"range",
"c",
".",
"Data",
"[",
"0",
"]",
".",
"Samples",
"{",
"if",
"d",
".",
"Flag",
"{",
"// DebugLogger.Printf(\"Reduced %d by %d\", r, rshift)",
"r",
"-=",
"rshift",
"/",
"3",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"g",
".",
"Begin",
"(",
")",
"\n\n",
"if",
"c",
".",
"Title",
"!=",
"\"",
"\"",
"{",
"drawTitle",
"(",
"g",
",",
"c",
".",
"Title",
",",
"elementStyle",
"(",
"c",
".",
"Options",
",",
"TitleElement",
")",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"data",
":=",
"range",
"c",
".",
"Data",
"{",
"var",
"sum",
"float64",
"\n",
"for",
"_",
",",
"d",
":=",
"range",
"data",
".",
"Samples",
"{",
"sum",
"+=",
"d",
".",
"Val",
"\n",
"}",
"\n\n",
"wedges",
":=",
"make",
"(",
"[",
"]",
"Wedgeinfo",
",",
"len",
"(",
"data",
".",
"Samples",
")",
")",
"\n",
"var",
"ri",
"int",
"=",
"0",
"\n",
"if",
"c",
".",
"Inner",
">",
"0",
"{",
"ri",
"=",
"int",
"(",
"float64",
"(",
"r",
")",
"*",
"c",
".",
"Inner",
")",
"\n",
"}",
"\n\n",
"var",
"phi",
"float64",
"=",
"-",
"math",
".",
"Pi",
"\n",
"for",
"j",
",",
"d",
":=",
"range",
"data",
".",
"Samples",
"{",
"style",
":=",
"data",
".",
"Style",
"[",
"j",
"]",
"\n",
"alpha",
":=",
"2",
"*",
"math",
".",
"Pi",
"*",
"d",
".",
"Val",
"/",
"sum",
"\n",
"shift",
":=",
"0",
"\n\n",
"var",
"t",
"string",
"\n",
"if",
"c",
".",
"FmtVal",
"!=",
"nil",
"{",
"t",
"=",
"c",
".",
"FmtVal",
"(",
"d",
".",
"Val",
",",
"sum",
")",
"\n",
"}",
"\n",
"if",
"d",
".",
"Flag",
"{",
"shift",
"=",
"rshift",
"\n",
"}",
"\n\n",
"wedges",
"[",
"j",
"]",
"=",
"Wedgeinfo",
"{",
"Phi",
":",
"phi",
",",
"Psi",
":",
"phi",
"+",
"alpha",
",",
"Text",
":",
"t",
",",
"Tp",
":",
"\"",
"\"",
",",
"Style",
":",
"style",
",",
"Font",
":",
"Font",
"{",
"}",
",",
"Shift",
":",
"shift",
"}",
"\n\n",
"phi",
"+=",
"alpha",
"\n",
"}",
"\n",
"g",
".",
"Rings",
"(",
"wedges",
",",
"x0",
",",
"y0",
",",
"r",
",",
"ri",
")",
"\n\n",
"r",
"=",
"int",
"(",
"float64",
"(",
"r",
")",
"*",
"PieChartShrinkage",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"c",
".",
"Key",
".",
"Hide",
"{",
"g",
".",
"Key",
"(",
"layout",
".",
"KeyX",
",",
"layout",
".",
"KeyY",
",",
"c",
".",
"Key",
",",
"c",
".",
"Options",
")",
"\n",
"}",
"\n\n",
"g",
".",
"End",
"(",
")",
"\n",
"}"
] | // Plot outputs the scatter chart sc to g. | [
"Plot",
"outputs",
"the",
"scatter",
"chart",
"sc",
"to",
"g",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/pie.go#L121-L191 | train |
vdobler/chart | graphics.go | GenericTextLen | func GenericTextLen(mg MinimalGraphics, t string, font Font) (width int) {
// TODO: how handle newlines? same way like Text does
fw, _, mono := mg.FontMetrics(font)
if mono {
for _ = range t {
width++
}
width = int(float32(width)*fw + 0.5)
} else {
var length float32
for _, r := range t {
if w, ok := CharacterWidth[int(r)]; ok {
length += w
} else {
length += 20 // save above average
}
}
length /= averageCharacterWidth
length *= fw
width = int(length + 0.5)
}
return
} | go | func GenericTextLen(mg MinimalGraphics, t string, font Font) (width int) {
// TODO: how handle newlines? same way like Text does
fw, _, mono := mg.FontMetrics(font)
if mono {
for _ = range t {
width++
}
width = int(float32(width)*fw + 0.5)
} else {
var length float32
for _, r := range t {
if w, ok := CharacterWidth[int(r)]; ok {
length += w
} else {
length += 20 // save above average
}
}
length /= averageCharacterWidth
length *= fw
width = int(length + 0.5)
}
return
} | [
"func",
"GenericTextLen",
"(",
"mg",
"MinimalGraphics",
",",
"t",
"string",
",",
"font",
"Font",
")",
"(",
"width",
"int",
")",
"{",
"// TODO: how handle newlines? same way like Text does",
"fw",
",",
"_",
",",
"mono",
":=",
"mg",
".",
"FontMetrics",
"(",
"font",
")",
"\n",
"if",
"mono",
"{",
"for",
"_",
"=",
"range",
"t",
"{",
"width",
"++",
"\n",
"}",
"\n",
"width",
"=",
"int",
"(",
"float32",
"(",
"width",
")",
"*",
"fw",
"+",
"0.5",
")",
"\n",
"}",
"else",
"{",
"var",
"length",
"float32",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"t",
"{",
"if",
"w",
",",
"ok",
":=",
"CharacterWidth",
"[",
"int",
"(",
"r",
")",
"]",
";",
"ok",
"{",
"length",
"+=",
"w",
"\n",
"}",
"else",
"{",
"length",
"+=",
"20",
"// save above average",
"\n",
"}",
"\n",
"}",
"\n",
"length",
"/=",
"averageCharacterWidth",
"\n",
"length",
"*=",
"fw",
"\n",
"width",
"=",
"int",
"(",
"length",
"+",
"0.5",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // GenericTextLen tries to determine the width in pixel of t if rendered into mg in using font. | [
"GenericTextLen",
"tries",
"to",
"determine",
"the",
"width",
"in",
"pixel",
"of",
"t",
"if",
"rendered",
"into",
"mg",
"in",
"using",
"font",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/graphics.go#L72-L94 | train |
vdobler/chart | graphics.go | GenericXAxis | func GenericXAxis(bg BasicGraphics, rng Range, y, ym int, options PlotOptions) {
_, fontheight, _ := bg.FontMetrics(elementStyle(options, MajorTicElement).Font)
var ticLen int = 0
if !rng.TicSetting.Hide {
ticLen = imin(12, imax(4, fontheight/2))
}
xa, xe := rng.Data2Screen(rng.Min), rng.Data2Screen(rng.Max)
// Axis label and range limits
aly := y + 2*ticLen
if !rng.TicSetting.Hide {
aly += (3 * fontheight) / 2
}
if rng.ShowLimits {
font := elementStyle(options, RangeLimitElement).Font
if rng.Time {
bg.Text(xa, aly, rng.TMin.Format("2006-01-02 15:04:05"), "tl", 0, font)
bg.Text(xe, aly, rng.TMax.Format("2006-01-02 15:04:05"), "tr", 0, font)
} else {
bg.Text(xa, aly, fmt.Sprintf("%g", rng.Min), "tl", 0, font)
bg.Text(xe, aly, fmt.Sprintf("%g", rng.Max), "tr", 0, font)
}
}
if rng.Label != "" { // draw label _after_ (=over) range limits
font := elementStyle(options, MajorAxisElement).Font
bg.Text((xa+xe)/2, aly, " "+rng.Label+" ", "tc", 0, font)
}
// Tics and Grid
if !rng.TicSetting.Hide {
drawXTics(bg, rng, y, ym, ticLen, options)
}
// Axis itself, mirrord axis and zero
bg.Line(xa, y, xe, y, elementStyle(options, MajorAxisElement))
if rng.TicSetting.Mirror >= 1 {
bg.Line(xa, ym, xe, ym, elementStyle(options, MinorAxisElement))
}
if rng.ShowZero && rng.Min < 0 && rng.Max > 0 {
z := rng.Data2Screen(0)
bg.Line(z, y, z, ym, elementStyle(options, ZeroAxisElement))
}
} | go | func GenericXAxis(bg BasicGraphics, rng Range, y, ym int, options PlotOptions) {
_, fontheight, _ := bg.FontMetrics(elementStyle(options, MajorTicElement).Font)
var ticLen int = 0
if !rng.TicSetting.Hide {
ticLen = imin(12, imax(4, fontheight/2))
}
xa, xe := rng.Data2Screen(rng.Min), rng.Data2Screen(rng.Max)
// Axis label and range limits
aly := y + 2*ticLen
if !rng.TicSetting.Hide {
aly += (3 * fontheight) / 2
}
if rng.ShowLimits {
font := elementStyle(options, RangeLimitElement).Font
if rng.Time {
bg.Text(xa, aly, rng.TMin.Format("2006-01-02 15:04:05"), "tl", 0, font)
bg.Text(xe, aly, rng.TMax.Format("2006-01-02 15:04:05"), "tr", 0, font)
} else {
bg.Text(xa, aly, fmt.Sprintf("%g", rng.Min), "tl", 0, font)
bg.Text(xe, aly, fmt.Sprintf("%g", rng.Max), "tr", 0, font)
}
}
if rng.Label != "" { // draw label _after_ (=over) range limits
font := elementStyle(options, MajorAxisElement).Font
bg.Text((xa+xe)/2, aly, " "+rng.Label+" ", "tc", 0, font)
}
// Tics and Grid
if !rng.TicSetting.Hide {
drawXTics(bg, rng, y, ym, ticLen, options)
}
// Axis itself, mirrord axis and zero
bg.Line(xa, y, xe, y, elementStyle(options, MajorAxisElement))
if rng.TicSetting.Mirror >= 1 {
bg.Line(xa, ym, xe, ym, elementStyle(options, MinorAxisElement))
}
if rng.ShowZero && rng.Min < 0 && rng.Max > 0 {
z := rng.Data2Screen(0)
bg.Line(z, y, z, ym, elementStyle(options, ZeroAxisElement))
}
} | [
"func",
"GenericXAxis",
"(",
"bg",
"BasicGraphics",
",",
"rng",
"Range",
",",
"y",
",",
"ym",
"int",
",",
"options",
"PlotOptions",
")",
"{",
"_",
",",
"fontheight",
",",
"_",
":=",
"bg",
".",
"FontMetrics",
"(",
"elementStyle",
"(",
"options",
",",
"MajorTicElement",
")",
".",
"Font",
")",
"\n",
"var",
"ticLen",
"int",
"=",
"0",
"\n",
"if",
"!",
"rng",
".",
"TicSetting",
".",
"Hide",
"{",
"ticLen",
"=",
"imin",
"(",
"12",
",",
"imax",
"(",
"4",
",",
"fontheight",
"/",
"2",
")",
")",
"\n",
"}",
"\n",
"xa",
",",
"xe",
":=",
"rng",
".",
"Data2Screen",
"(",
"rng",
".",
"Min",
")",
",",
"rng",
".",
"Data2Screen",
"(",
"rng",
".",
"Max",
")",
"\n\n",
"// Axis label and range limits",
"aly",
":=",
"y",
"+",
"2",
"*",
"ticLen",
"\n",
"if",
"!",
"rng",
".",
"TicSetting",
".",
"Hide",
"{",
"aly",
"+=",
"(",
"3",
"*",
"fontheight",
")",
"/",
"2",
"\n",
"}",
"\n",
"if",
"rng",
".",
"ShowLimits",
"{",
"font",
":=",
"elementStyle",
"(",
"options",
",",
"RangeLimitElement",
")",
".",
"Font",
"\n",
"if",
"rng",
".",
"Time",
"{",
"bg",
".",
"Text",
"(",
"xa",
",",
"aly",
",",
"rng",
".",
"TMin",
".",
"Format",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
",",
"0",
",",
"font",
")",
"\n",
"bg",
".",
"Text",
"(",
"xe",
",",
"aly",
",",
"rng",
".",
"TMax",
".",
"Format",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
",",
"0",
",",
"font",
")",
"\n",
"}",
"else",
"{",
"bg",
".",
"Text",
"(",
"xa",
",",
"aly",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"rng",
".",
"Min",
")",
",",
"\"",
"\"",
",",
"0",
",",
"font",
")",
"\n",
"bg",
".",
"Text",
"(",
"xe",
",",
"aly",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"rng",
".",
"Max",
")",
",",
"\"",
"\"",
",",
"0",
",",
"font",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"rng",
".",
"Label",
"!=",
"\"",
"\"",
"{",
"// draw label _after_ (=over) range limits",
"font",
":=",
"elementStyle",
"(",
"options",
",",
"MajorAxisElement",
")",
".",
"Font",
"\n",
"bg",
".",
"Text",
"(",
"(",
"xa",
"+",
"xe",
")",
"/",
"2",
",",
"aly",
",",
"\"",
"\"",
"+",
"rng",
".",
"Label",
"+",
"\"",
"\"",
",",
"\"",
"\"",
",",
"0",
",",
"font",
")",
"\n",
"}",
"\n\n",
"// Tics and Grid",
"if",
"!",
"rng",
".",
"TicSetting",
".",
"Hide",
"{",
"drawXTics",
"(",
"bg",
",",
"rng",
",",
"y",
",",
"ym",
",",
"ticLen",
",",
"options",
")",
"\n",
"}",
"\n\n",
"// Axis itself, mirrord axis and zero",
"bg",
".",
"Line",
"(",
"xa",
",",
"y",
",",
"xe",
",",
"y",
",",
"elementStyle",
"(",
"options",
",",
"MajorAxisElement",
")",
")",
"\n",
"if",
"rng",
".",
"TicSetting",
".",
"Mirror",
">=",
"1",
"{",
"bg",
".",
"Line",
"(",
"xa",
",",
"ym",
",",
"xe",
",",
"ym",
",",
"elementStyle",
"(",
"options",
",",
"MinorAxisElement",
")",
")",
"\n",
"}",
"\n",
"if",
"rng",
".",
"ShowZero",
"&&",
"rng",
".",
"Min",
"<",
"0",
"&&",
"rng",
".",
"Max",
">",
"0",
"{",
"z",
":=",
"rng",
".",
"Data2Screen",
"(",
"0",
")",
"\n",
"bg",
".",
"Line",
"(",
"z",
",",
"y",
",",
"z",
",",
"ym",
",",
"elementStyle",
"(",
"options",
",",
"ZeroAxisElement",
")",
")",
"\n",
"}",
"\n\n",
"}"
] | // GenericXAxis draws the x-axis with range rng solely by graphic primitives of bg.
// The x-axis is drawn at y on the screen and the mirrored x-axis is drawn at ym. | [
"GenericXAxis",
"draws",
"the",
"x",
"-",
"axis",
"with",
"range",
"rng",
"solely",
"by",
"graphic",
"primitives",
"of",
"bg",
".",
"The",
"x",
"-",
"axis",
"is",
"drawn",
"at",
"y",
"on",
"the",
"screen",
"and",
"the",
"mirrored",
"x",
"-",
"axis",
"is",
"drawn",
"at",
"ym",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/graphics.go#L206-L249 | train |
vdobler/chart | graphics.go | GenericYAxis | func GenericYAxis(bg BasicGraphics, rng Range, x, xm int, options PlotOptions) {
font := elementStyle(options, MajorAxisElement).Font
_, fontheight, _ := bg.FontMetrics(font)
var ticLen int = 0
if !rng.TicSetting.Hide {
ticLen = imin(10, imax(4, fontheight/2))
}
ya, ye := rng.Data2Screen(rng.Min), rng.Data2Screen(rng.Max)
// Label and axis ranges
alx := 2 * fontheight
if rng.ShowLimits {
/* TODO
st := bg.Style("rangelimit")
if rng.Time {
bg.Text(xa, aly, rng.TMin.Format("2006-01-02 15:04:05"), "tl", 0, st)
bg.Text(xe, aly, rng.TMax.Format("2006-01-02 15:04:05"), "tr", 0, st)
} else {
bg.Text(xa, aly, fmt.Sprintf("%g", rng.Min), "tl", 0, st)
bg.Text(xe, aly, fmt.Sprintf("%g", rng.Max), "tr", 0, st)
}
*/
}
if rng.Label != "" {
y := (ya + ye) / 2
bg.Text(alx, y, rng.Label, "bc", 90, font)
}
if !rng.TicSetting.Hide {
drawYTics(bg, rng, x, xm, ticLen, options)
}
// Axis itself, mirrord axis and zero
bg.Line(x, ya, x, ye, elementStyle(options, MajorAxisElement))
if rng.TicSetting.Mirror >= 1 {
bg.Line(xm, ya, xm, ye, elementStyle(options, MinorAxisElement))
}
if rng.ShowZero && rng.Min < 0 && rng.Max > 0 {
z := rng.Data2Screen(0)
bg.Line(x, z, xm, z, elementStyle(options, ZeroAxisElement))
}
} | go | func GenericYAxis(bg BasicGraphics, rng Range, x, xm int, options PlotOptions) {
font := elementStyle(options, MajorAxisElement).Font
_, fontheight, _ := bg.FontMetrics(font)
var ticLen int = 0
if !rng.TicSetting.Hide {
ticLen = imin(10, imax(4, fontheight/2))
}
ya, ye := rng.Data2Screen(rng.Min), rng.Data2Screen(rng.Max)
// Label and axis ranges
alx := 2 * fontheight
if rng.ShowLimits {
/* TODO
st := bg.Style("rangelimit")
if rng.Time {
bg.Text(xa, aly, rng.TMin.Format("2006-01-02 15:04:05"), "tl", 0, st)
bg.Text(xe, aly, rng.TMax.Format("2006-01-02 15:04:05"), "tr", 0, st)
} else {
bg.Text(xa, aly, fmt.Sprintf("%g", rng.Min), "tl", 0, st)
bg.Text(xe, aly, fmt.Sprintf("%g", rng.Max), "tr", 0, st)
}
*/
}
if rng.Label != "" {
y := (ya + ye) / 2
bg.Text(alx, y, rng.Label, "bc", 90, font)
}
if !rng.TicSetting.Hide {
drawYTics(bg, rng, x, xm, ticLen, options)
}
// Axis itself, mirrord axis and zero
bg.Line(x, ya, x, ye, elementStyle(options, MajorAxisElement))
if rng.TicSetting.Mirror >= 1 {
bg.Line(xm, ya, xm, ye, elementStyle(options, MinorAxisElement))
}
if rng.ShowZero && rng.Min < 0 && rng.Max > 0 {
z := rng.Data2Screen(0)
bg.Line(x, z, xm, z, elementStyle(options, ZeroAxisElement))
}
} | [
"func",
"GenericYAxis",
"(",
"bg",
"BasicGraphics",
",",
"rng",
"Range",
",",
"x",
",",
"xm",
"int",
",",
"options",
"PlotOptions",
")",
"{",
"font",
":=",
"elementStyle",
"(",
"options",
",",
"MajorAxisElement",
")",
".",
"Font",
"\n",
"_",
",",
"fontheight",
",",
"_",
":=",
"bg",
".",
"FontMetrics",
"(",
"font",
")",
"\n",
"var",
"ticLen",
"int",
"=",
"0",
"\n",
"if",
"!",
"rng",
".",
"TicSetting",
".",
"Hide",
"{",
"ticLen",
"=",
"imin",
"(",
"10",
",",
"imax",
"(",
"4",
",",
"fontheight",
"/",
"2",
")",
")",
"\n",
"}",
"\n",
"ya",
",",
"ye",
":=",
"rng",
".",
"Data2Screen",
"(",
"rng",
".",
"Min",
")",
",",
"rng",
".",
"Data2Screen",
"(",
"rng",
".",
"Max",
")",
"\n\n",
"// Label and axis ranges",
"alx",
":=",
"2",
"*",
"fontheight",
"\n",
"if",
"rng",
".",
"ShowLimits",
"{",
"/* TODO\n\t\tst := bg.Style(\"rangelimit\")\n\t\tif rng.Time {\n\t\t\tbg.Text(xa, aly, rng.TMin.Format(\"2006-01-02 15:04:05\"), \"tl\", 0, st)\n\t\t\tbg.Text(xe, aly, rng.TMax.Format(\"2006-01-02 15:04:05\"), \"tr\", 0, st)\n\t\t} else {\n\t\t\tbg.Text(xa, aly, fmt.Sprintf(\"%g\", rng.Min), \"tl\", 0, st)\n\t\t\tbg.Text(xe, aly, fmt.Sprintf(\"%g\", rng.Max), \"tr\", 0, st)\n\t\t}\n\t\t*/",
"}",
"\n",
"if",
"rng",
".",
"Label",
"!=",
"\"",
"\"",
"{",
"y",
":=",
"(",
"ya",
"+",
"ye",
")",
"/",
"2",
"\n",
"bg",
".",
"Text",
"(",
"alx",
",",
"y",
",",
"rng",
".",
"Label",
",",
"\"",
"\"",
",",
"90",
",",
"font",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"rng",
".",
"TicSetting",
".",
"Hide",
"{",
"drawYTics",
"(",
"bg",
",",
"rng",
",",
"x",
",",
"xm",
",",
"ticLen",
",",
"options",
")",
"\n",
"}",
"\n\n",
"// Axis itself, mirrord axis and zero",
"bg",
".",
"Line",
"(",
"x",
",",
"ya",
",",
"x",
",",
"ye",
",",
"elementStyle",
"(",
"options",
",",
"MajorAxisElement",
")",
")",
"\n",
"if",
"rng",
".",
"TicSetting",
".",
"Mirror",
">=",
"1",
"{",
"bg",
".",
"Line",
"(",
"xm",
",",
"ya",
",",
"xm",
",",
"ye",
",",
"elementStyle",
"(",
"options",
",",
"MinorAxisElement",
")",
")",
"\n",
"}",
"\n",
"if",
"rng",
".",
"ShowZero",
"&&",
"rng",
".",
"Min",
"<",
"0",
"&&",
"rng",
".",
"Max",
">",
"0",
"{",
"z",
":=",
"rng",
".",
"Data2Screen",
"(",
"0",
")",
"\n",
"bg",
".",
"Line",
"(",
"x",
",",
"z",
",",
"xm",
",",
"z",
",",
"elementStyle",
"(",
"options",
",",
"ZeroAxisElement",
")",
")",
"\n",
"}",
"\n\n",
"}"
] | // GenericYAxis draws the y-axis with the range rng solely by graphic primitives of bg.
// The y.axis and the mirrord y-axis are drawn at x and ym respectively. | [
"GenericYAxis",
"draws",
"the",
"y",
"-",
"axis",
"with",
"the",
"range",
"rng",
"solely",
"by",
"graphic",
"primitives",
"of",
"bg",
".",
"The",
"y",
".",
"axis",
"and",
"the",
"mirrord",
"y",
"-",
"axis",
"are",
"drawn",
"at",
"x",
"and",
"ym",
"respectively",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/graphics.go#L320-L362 | train |
vdobler/chart | graphics.go | GenericScatter | func GenericScatter(bg BasicGraphics, points []EPoint, plotstyle PlotStyle, style Style) {
// First pass: Error bars
ebs := style
ebs.LineColor, ebs.LineWidth, ebs.LineStyle = ebs.FillColor, 1, SolidLine
if ebs.LineColor == nil {
ebs.LineColor = color.NRGBA{0x40, 0x40, 0x40, 0xff}
}
if ebs.LineWidth == 0 {
ebs.LineWidth = 1
}
for _, p := range points {
xl, yl, xh, yh := p.BoundingBox()
// fmt.Printf("Draw %d: %f %f-%f; %f %f-%f\n", i, p.DeltaX, xl,xh, p.DeltaY, yl,yh)
if !math.IsNaN(p.DeltaX) {
bg.Line(int(xl), int(p.Y), int(xh), int(p.Y), ebs)
}
if !math.IsNaN(p.DeltaY) {
// fmt.Printf(" Draw %d,%d to %d,%d\n",int(p.X), int(yl), int(p.X), int(yh))
bg.Line(int(p.X), int(yl), int(p.X), int(yh), ebs)
}
}
// Second pass: Line
if (plotstyle&PlotStyleLines) != 0 && len(points) > 0 {
lastx, lasty := int(points[0].X), int(points[0].Y)
for i := 1; i < len(points); i++ {
x, y := int(points[i].X), int(points[i].Y)
bg.Line(lastx, lasty, x, y, style)
lastx, lasty = x, y
}
}
// Third pass: symbols
if (plotstyle&PlotStylePoints) != 0 && len(points) != 0 {
for _, p := range points {
// fmt.Printf("Point %d at %d,%d\n", i, int(p.X), int(p.Y))
bg.Symbol(int(p.X), int(p.Y), style)
}
}
} | go | func GenericScatter(bg BasicGraphics, points []EPoint, plotstyle PlotStyle, style Style) {
// First pass: Error bars
ebs := style
ebs.LineColor, ebs.LineWidth, ebs.LineStyle = ebs.FillColor, 1, SolidLine
if ebs.LineColor == nil {
ebs.LineColor = color.NRGBA{0x40, 0x40, 0x40, 0xff}
}
if ebs.LineWidth == 0 {
ebs.LineWidth = 1
}
for _, p := range points {
xl, yl, xh, yh := p.BoundingBox()
// fmt.Printf("Draw %d: %f %f-%f; %f %f-%f\n", i, p.DeltaX, xl,xh, p.DeltaY, yl,yh)
if !math.IsNaN(p.DeltaX) {
bg.Line(int(xl), int(p.Y), int(xh), int(p.Y), ebs)
}
if !math.IsNaN(p.DeltaY) {
// fmt.Printf(" Draw %d,%d to %d,%d\n",int(p.X), int(yl), int(p.X), int(yh))
bg.Line(int(p.X), int(yl), int(p.X), int(yh), ebs)
}
}
// Second pass: Line
if (plotstyle&PlotStyleLines) != 0 && len(points) > 0 {
lastx, lasty := int(points[0].X), int(points[0].Y)
for i := 1; i < len(points); i++ {
x, y := int(points[i].X), int(points[i].Y)
bg.Line(lastx, lasty, x, y, style)
lastx, lasty = x, y
}
}
// Third pass: symbols
if (plotstyle&PlotStylePoints) != 0 && len(points) != 0 {
for _, p := range points {
// fmt.Printf("Point %d at %d,%d\n", i, int(p.X), int(p.Y))
bg.Symbol(int(p.X), int(p.Y), style)
}
}
} | [
"func",
"GenericScatter",
"(",
"bg",
"BasicGraphics",
",",
"points",
"[",
"]",
"EPoint",
",",
"plotstyle",
"PlotStyle",
",",
"style",
"Style",
")",
"{",
"// First pass: Error bars",
"ebs",
":=",
"style",
"\n",
"ebs",
".",
"LineColor",
",",
"ebs",
".",
"LineWidth",
",",
"ebs",
".",
"LineStyle",
"=",
"ebs",
".",
"FillColor",
",",
"1",
",",
"SolidLine",
"\n",
"if",
"ebs",
".",
"LineColor",
"==",
"nil",
"{",
"ebs",
".",
"LineColor",
"=",
"color",
".",
"NRGBA",
"{",
"0x40",
",",
"0x40",
",",
"0x40",
",",
"0xff",
"}",
"\n",
"}",
"\n",
"if",
"ebs",
".",
"LineWidth",
"==",
"0",
"{",
"ebs",
".",
"LineWidth",
"=",
"1",
"\n",
"}",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"points",
"{",
"xl",
",",
"yl",
",",
"xh",
",",
"yh",
":=",
"p",
".",
"BoundingBox",
"(",
")",
"\n",
"// fmt.Printf(\"Draw %d: %f %f-%f; %f %f-%f\\n\", i, p.DeltaX, xl,xh, p.DeltaY, yl,yh)",
"if",
"!",
"math",
".",
"IsNaN",
"(",
"p",
".",
"DeltaX",
")",
"{",
"bg",
".",
"Line",
"(",
"int",
"(",
"xl",
")",
",",
"int",
"(",
"p",
".",
"Y",
")",
",",
"int",
"(",
"xh",
")",
",",
"int",
"(",
"p",
".",
"Y",
")",
",",
"ebs",
")",
"\n",
"}",
"\n",
"if",
"!",
"math",
".",
"IsNaN",
"(",
"p",
".",
"DeltaY",
")",
"{",
"// fmt.Printf(\" Draw %d,%d to %d,%d\\n\",int(p.X), int(yl), int(p.X), int(yh))",
"bg",
".",
"Line",
"(",
"int",
"(",
"p",
".",
"X",
")",
",",
"int",
"(",
"yl",
")",
",",
"int",
"(",
"p",
".",
"X",
")",
",",
"int",
"(",
"yh",
")",
",",
"ebs",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Second pass: Line",
"if",
"(",
"plotstyle",
"&",
"PlotStyleLines",
")",
"!=",
"0",
"&&",
"len",
"(",
"points",
")",
">",
"0",
"{",
"lastx",
",",
"lasty",
":=",
"int",
"(",
"points",
"[",
"0",
"]",
".",
"X",
")",
",",
"int",
"(",
"points",
"[",
"0",
"]",
".",
"Y",
")",
"\n",
"for",
"i",
":=",
"1",
";",
"i",
"<",
"len",
"(",
"points",
")",
";",
"i",
"++",
"{",
"x",
",",
"y",
":=",
"int",
"(",
"points",
"[",
"i",
"]",
".",
"X",
")",
",",
"int",
"(",
"points",
"[",
"i",
"]",
".",
"Y",
")",
"\n",
"bg",
".",
"Line",
"(",
"lastx",
",",
"lasty",
",",
"x",
",",
"y",
",",
"style",
")",
"\n",
"lastx",
",",
"lasty",
"=",
"x",
",",
"y",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Third pass: symbols",
"if",
"(",
"plotstyle",
"&",
"PlotStylePoints",
")",
"!=",
"0",
"&&",
"len",
"(",
"points",
")",
"!=",
"0",
"{",
"for",
"_",
",",
"p",
":=",
"range",
"points",
"{",
"// fmt.Printf(\"Point %d at %d,%d\\n\", i, int(p.X), int(p.Y))",
"bg",
".",
"Symbol",
"(",
"int",
"(",
"p",
".",
"X",
")",
",",
"int",
"(",
"p",
".",
"Y",
")",
",",
"style",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // GenericScatter draws the given points according to style.
// style.FillColor is used as color of error bars and style.FontSize is used
// as the length of the endmarks of the error bars. Both have suitable defaults
// if the FontXyz are not set. Point coordinates and errors must be provided
// in screen coordinates. | [
"GenericScatter",
"draws",
"the",
"given",
"points",
"according",
"to",
"style",
".",
"style",
".",
"FillColor",
"is",
"used",
"as",
"color",
"of",
"error",
"bars",
"and",
"style",
".",
"FontSize",
"is",
"used",
"as",
"the",
"length",
"of",
"the",
"endmarks",
"of",
"the",
"error",
"bars",
".",
"Both",
"have",
"suitable",
"defaults",
"if",
"the",
"FontXyz",
"are",
"not",
"set",
".",
"Point",
"coordinates",
"and",
"errors",
"must",
"be",
"provided",
"in",
"screen",
"coordinates",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/graphics.go#L369-L410 | train |
vdobler/chart | key.go | Layout | func (key Key) Layout(bg BasicGraphics, m [][]*KeyEntry, font Font) (w, h int, colwidth, rowheight []int) {
fontwidth, fontheight, _ := bg.FontMetrics(font)
cols, rows := len(m), len(m[0])
// Find total width and height
totalh := 0
rowheight = make([]int, rows)
for r := 0; r < rows; r++ {
rh := 0
for c := 0; c < cols; c++ {
e := m[c][r]
if e == nil {
continue
}
// fmt.Printf("Layout1 (%d,%d): %s\n", c,r,e.Text)
_, h := textDim(e.Text)
if h > rh {
rh = h
}
}
rowheight[r] = rh
totalh += rh
}
totalw := 0
colwidth = make([]int, cols)
// fmt.Printf("Making totalw for %d cols\n", cols)
for c := 0; c < cols; c++ {
var rw float32
for r := 0; r < rows; r++ {
e := m[c][r]
if e == nil {
continue
}
// fmt.Printf("Layout2 (%d,%d): %s\n", c,r,e.Text)
w, _ := textDim(e.Text)
if w > rw {
rw = w
}
}
irw := int(rw + 0.75)
colwidth[c] = irw
totalw += irw
// fmt.Printf("Width of col %d: %d. Total now: %d\n", c, irw, totalw)
}
if fontwidth == 1 && fontheight == 1 {
// totalw/h are characters only and still in character-units
totalw += int(KeyColSep) * (cols - 1) // add space between columns
totalw += int(2*KeyHorSep + 0.5) // add space for left/right border
totalw += int(KeySymbolWidth+KeySymbolSep+0.5) * cols // place for symbol and symbol-text sep
totalh += int(KeyRowSep) * (rows - 1) // add space between rows
vsep := KeyVertSep
if vsep < 1 {
vsep = 1
} // make sure there _is_ room (as KeyVertSep < 1)
totalh += int(2 * vsep) // add border at top/bottom
} else {
// totalw/h are characters only and still in character-units
totalw = int(float32(totalw) * fontwidth) // scale to pixels
totalw += int(KeyColSep * (float32(cols-1) * fontwidth)) // add space between columns
totalw += int(2 * KeyHorSep * fontwidth) // add space for left/right border
totalw += int((KeySymbolWidth+KeySymbolSep)*fontwidth) * cols // place for symbol and symbol-text sep
totalh *= fontheight
totalh += int(KeyRowSep * float32((rows-1)*fontheight)) // add space between rows
vsep := KeyVertSep * float32(fontheight)
if vsep < 1 {
vsep = 1
} // make sure there _is_ room (as KeyVertSep < 1)
totalh += int(2 * vsep) // add border at top/bottom
}
return totalw, totalh, colwidth, rowheight
} | go | func (key Key) Layout(bg BasicGraphics, m [][]*KeyEntry, font Font) (w, h int, colwidth, rowheight []int) {
fontwidth, fontheight, _ := bg.FontMetrics(font)
cols, rows := len(m), len(m[0])
// Find total width and height
totalh := 0
rowheight = make([]int, rows)
for r := 0; r < rows; r++ {
rh := 0
for c := 0; c < cols; c++ {
e := m[c][r]
if e == nil {
continue
}
// fmt.Printf("Layout1 (%d,%d): %s\n", c,r,e.Text)
_, h := textDim(e.Text)
if h > rh {
rh = h
}
}
rowheight[r] = rh
totalh += rh
}
totalw := 0
colwidth = make([]int, cols)
// fmt.Printf("Making totalw for %d cols\n", cols)
for c := 0; c < cols; c++ {
var rw float32
for r := 0; r < rows; r++ {
e := m[c][r]
if e == nil {
continue
}
// fmt.Printf("Layout2 (%d,%d): %s\n", c,r,e.Text)
w, _ := textDim(e.Text)
if w > rw {
rw = w
}
}
irw := int(rw + 0.75)
colwidth[c] = irw
totalw += irw
// fmt.Printf("Width of col %d: %d. Total now: %d\n", c, irw, totalw)
}
if fontwidth == 1 && fontheight == 1 {
// totalw/h are characters only and still in character-units
totalw += int(KeyColSep) * (cols - 1) // add space between columns
totalw += int(2*KeyHorSep + 0.5) // add space for left/right border
totalw += int(KeySymbolWidth+KeySymbolSep+0.5) * cols // place for symbol and symbol-text sep
totalh += int(KeyRowSep) * (rows - 1) // add space between rows
vsep := KeyVertSep
if vsep < 1 {
vsep = 1
} // make sure there _is_ room (as KeyVertSep < 1)
totalh += int(2 * vsep) // add border at top/bottom
} else {
// totalw/h are characters only and still in character-units
totalw = int(float32(totalw) * fontwidth) // scale to pixels
totalw += int(KeyColSep * (float32(cols-1) * fontwidth)) // add space between columns
totalw += int(2 * KeyHorSep * fontwidth) // add space for left/right border
totalw += int((KeySymbolWidth+KeySymbolSep)*fontwidth) * cols // place for symbol and symbol-text sep
totalh *= fontheight
totalh += int(KeyRowSep * float32((rows-1)*fontheight)) // add space between rows
vsep := KeyVertSep * float32(fontheight)
if vsep < 1 {
vsep = 1
} // make sure there _is_ room (as KeyVertSep < 1)
totalh += int(2 * vsep) // add border at top/bottom
}
return totalw, totalh, colwidth, rowheight
} | [
"func",
"(",
"key",
"Key",
")",
"Layout",
"(",
"bg",
"BasicGraphics",
",",
"m",
"[",
"]",
"[",
"]",
"*",
"KeyEntry",
",",
"font",
"Font",
")",
"(",
"w",
",",
"h",
"int",
",",
"colwidth",
",",
"rowheight",
"[",
"]",
"int",
")",
"{",
"fontwidth",
",",
"fontheight",
",",
"_",
":=",
"bg",
".",
"FontMetrics",
"(",
"font",
")",
"\n",
"cols",
",",
"rows",
":=",
"len",
"(",
"m",
")",
",",
"len",
"(",
"m",
"[",
"0",
"]",
")",
"\n\n",
"// Find total width and height",
"totalh",
":=",
"0",
"\n",
"rowheight",
"=",
"make",
"(",
"[",
"]",
"int",
",",
"rows",
")",
"\n",
"for",
"r",
":=",
"0",
";",
"r",
"<",
"rows",
";",
"r",
"++",
"{",
"rh",
":=",
"0",
"\n",
"for",
"c",
":=",
"0",
";",
"c",
"<",
"cols",
";",
"c",
"++",
"{",
"e",
":=",
"m",
"[",
"c",
"]",
"[",
"r",
"]",
"\n",
"if",
"e",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"// fmt.Printf(\"Layout1 (%d,%d): %s\\n\", c,r,e.Text)",
"_",
",",
"h",
":=",
"textDim",
"(",
"e",
".",
"Text",
")",
"\n",
"if",
"h",
">",
"rh",
"{",
"rh",
"=",
"h",
"\n",
"}",
"\n",
"}",
"\n",
"rowheight",
"[",
"r",
"]",
"=",
"rh",
"\n",
"totalh",
"+=",
"rh",
"\n",
"}",
"\n\n",
"totalw",
":=",
"0",
"\n",
"colwidth",
"=",
"make",
"(",
"[",
"]",
"int",
",",
"cols",
")",
"\n",
"// fmt.Printf(\"Making totalw for %d cols\\n\", cols)",
"for",
"c",
":=",
"0",
";",
"c",
"<",
"cols",
";",
"c",
"++",
"{",
"var",
"rw",
"float32",
"\n",
"for",
"r",
":=",
"0",
";",
"r",
"<",
"rows",
";",
"r",
"++",
"{",
"e",
":=",
"m",
"[",
"c",
"]",
"[",
"r",
"]",
"\n",
"if",
"e",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"// fmt.Printf(\"Layout2 (%d,%d): %s\\n\", c,r,e.Text)",
"w",
",",
"_",
":=",
"textDim",
"(",
"e",
".",
"Text",
")",
"\n",
"if",
"w",
">",
"rw",
"{",
"rw",
"=",
"w",
"\n",
"}",
"\n",
"}",
"\n",
"irw",
":=",
"int",
"(",
"rw",
"+",
"0.75",
")",
"\n",
"colwidth",
"[",
"c",
"]",
"=",
"irw",
"\n",
"totalw",
"+=",
"irw",
"\n",
"// fmt.Printf(\"Width of col %d: %d. Total now: %d\\n\", c, irw, totalw)",
"}",
"\n\n",
"if",
"fontwidth",
"==",
"1",
"&&",
"fontheight",
"==",
"1",
"{",
"// totalw/h are characters only and still in character-units",
"totalw",
"+=",
"int",
"(",
"KeyColSep",
")",
"*",
"(",
"cols",
"-",
"1",
")",
"// add space between columns",
"\n",
"totalw",
"+=",
"int",
"(",
"2",
"*",
"KeyHorSep",
"+",
"0.5",
")",
"// add space for left/right border",
"\n",
"totalw",
"+=",
"int",
"(",
"KeySymbolWidth",
"+",
"KeySymbolSep",
"+",
"0.5",
")",
"*",
"cols",
"// place for symbol and symbol-text sep",
"\n\n",
"totalh",
"+=",
"int",
"(",
"KeyRowSep",
")",
"*",
"(",
"rows",
"-",
"1",
")",
"// add space between rows",
"\n",
"vsep",
":=",
"KeyVertSep",
"\n",
"if",
"vsep",
"<",
"1",
"{",
"vsep",
"=",
"1",
"\n",
"}",
"// make sure there _is_ room (as KeyVertSep < 1)",
"\n",
"totalh",
"+=",
"int",
"(",
"2",
"*",
"vsep",
")",
"// add border at top/bottom",
"\n",
"}",
"else",
"{",
"// totalw/h are characters only and still in character-units",
"totalw",
"=",
"int",
"(",
"float32",
"(",
"totalw",
")",
"*",
"fontwidth",
")",
"// scale to pixels",
"\n",
"totalw",
"+=",
"int",
"(",
"KeyColSep",
"*",
"(",
"float32",
"(",
"cols",
"-",
"1",
")",
"*",
"fontwidth",
")",
")",
"// add space between columns",
"\n",
"totalw",
"+=",
"int",
"(",
"2",
"*",
"KeyHorSep",
"*",
"fontwidth",
")",
"// add space for left/right border",
"\n",
"totalw",
"+=",
"int",
"(",
"(",
"KeySymbolWidth",
"+",
"KeySymbolSep",
")",
"*",
"fontwidth",
")",
"*",
"cols",
"// place for symbol and symbol-text sep",
"\n\n",
"totalh",
"*=",
"fontheight",
"\n",
"totalh",
"+=",
"int",
"(",
"KeyRowSep",
"*",
"float32",
"(",
"(",
"rows",
"-",
"1",
")",
"*",
"fontheight",
")",
")",
"// add space between rows",
"\n",
"vsep",
":=",
"KeyVertSep",
"*",
"float32",
"(",
"fontheight",
")",
"\n",
"if",
"vsep",
"<",
"1",
"{",
"vsep",
"=",
"1",
"\n",
"}",
"// make sure there _is_ room (as KeyVertSep < 1)",
"\n",
"totalh",
"+=",
"int",
"(",
"2",
"*",
"vsep",
")",
"// add border at top/bottom",
"\n",
"}",
"\n",
"return",
"totalw",
",",
"totalh",
",",
"colwidth",
",",
"rowheight",
"\n",
"}"
] | // Layout determines how wide and broad the places keys in m will be rendered. | [
"Layout",
"determines",
"how",
"wide",
"and",
"broad",
"the",
"places",
"keys",
"in",
"m",
"will",
"be",
"rendered",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/key.go#L137-L212 | train |
vdobler/chart | bar.go | AddData | func (c *BarChart) AddData(name string, data []Point, style Style) {
if len(c.Data) == 0 {
c.XRange.init()
c.YRange.init()
}
c.Data = append(c.Data, BarChartData{name, style, data})
for _, d := range data {
c.XRange.autoscale(d.X)
c.YRange.autoscale(d.Y)
}
if name != "" {
c.Key.Entries = append(c.Key.Entries, KeyEntry{Style: style, Text: name, PlotStyle: PlotStyleBox})
}
} | go | func (c *BarChart) AddData(name string, data []Point, style Style) {
if len(c.Data) == 0 {
c.XRange.init()
c.YRange.init()
}
c.Data = append(c.Data, BarChartData{name, style, data})
for _, d := range data {
c.XRange.autoscale(d.X)
c.YRange.autoscale(d.Y)
}
if name != "" {
c.Key.Entries = append(c.Key.Entries, KeyEntry{Style: style, Text: name, PlotStyle: PlotStyleBox})
}
} | [
"func",
"(",
"c",
"*",
"BarChart",
")",
"AddData",
"(",
"name",
"string",
",",
"data",
"[",
"]",
"Point",
",",
"style",
"Style",
")",
"{",
"if",
"len",
"(",
"c",
".",
"Data",
")",
"==",
"0",
"{",
"c",
".",
"XRange",
".",
"init",
"(",
")",
"\n",
"c",
".",
"YRange",
".",
"init",
"(",
")",
"\n",
"}",
"\n",
"c",
".",
"Data",
"=",
"append",
"(",
"c",
".",
"Data",
",",
"BarChartData",
"{",
"name",
",",
"style",
",",
"data",
"}",
")",
"\n",
"for",
"_",
",",
"d",
":=",
"range",
"data",
"{",
"c",
".",
"XRange",
".",
"autoscale",
"(",
"d",
".",
"X",
")",
"\n",
"c",
".",
"YRange",
".",
"autoscale",
"(",
"d",
".",
"Y",
")",
"\n",
"}",
"\n\n",
"if",
"name",
"!=",
"\"",
"\"",
"{",
"c",
".",
"Key",
".",
"Entries",
"=",
"append",
"(",
"c",
".",
"Key",
".",
"Entries",
",",
"KeyEntry",
"{",
"Style",
":",
"style",
",",
"Text",
":",
"name",
",",
"PlotStyle",
":",
"PlotStyleBox",
"}",
")",
"\n",
"}",
"\n",
"}"
] | // AddData adds the data to the chart. | [
"AddData",
"adds",
"the",
"data",
"to",
"the",
"chart",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/bar.go#L35-L49 | train |
vdobler/chart | style.go | SymbolIndex | func SymbolIndex(s int) (idx int) {
for idx = 0; idx < len(Symbol); idx++ {
if Symbol[idx] == s {
return idx
}
}
return -1
} | go | func SymbolIndex(s int) (idx int) {
for idx = 0; idx < len(Symbol); idx++ {
if Symbol[idx] == s {
return idx
}
}
return -1
} | [
"func",
"SymbolIndex",
"(",
"s",
"int",
")",
"(",
"idx",
"int",
")",
"{",
"for",
"idx",
"=",
"0",
";",
"idx",
"<",
"len",
"(",
"Symbol",
")",
";",
"idx",
"++",
"{",
"if",
"Symbol",
"[",
"idx",
"]",
"==",
"s",
"{",
"return",
"idx",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"-",
"1",
"\n",
"}"
] | // SymbolIndex returns the index of the symbol s in Symbol or -1 if not found. | [
"SymbolIndex",
"returns",
"the",
"index",
"of",
"the",
"symbol",
"s",
"in",
"Symbol",
"or",
"-",
"1",
"if",
"not",
"found",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/style.go#L29-L36 | train |
vdobler/chart | stat.go | PercentilInt | func PercentilInt(data []int, p int) int {
n := len(data)
if n == 0 {
return 0
}
if n == 1 {
return data[0]
}
pos := float64(p) * float64(n+1) / 100
fpos := math.Floor(pos)
intPos := int(fpos)
dif := pos - fpos
if intPos < 1 {
return data[0]
}
if intPos >= n {
return data[n-1]
}
lower := data[intPos-1]
upper := data[intPos]
val := float64(lower) + dif*float64(upper-lower)
return int(math.Floor(val + 0.5))
} | go | func PercentilInt(data []int, p int) int {
n := len(data)
if n == 0 {
return 0
}
if n == 1 {
return data[0]
}
pos := float64(p) * float64(n+1) / 100
fpos := math.Floor(pos)
intPos := int(fpos)
dif := pos - fpos
if intPos < 1 {
return data[0]
}
if intPos >= n {
return data[n-1]
}
lower := data[intPos-1]
upper := data[intPos]
val := float64(lower) + dif*float64(upper-lower)
return int(math.Floor(val + 0.5))
} | [
"func",
"PercentilInt",
"(",
"data",
"[",
"]",
"int",
",",
"p",
"int",
")",
"int",
"{",
"n",
":=",
"len",
"(",
"data",
")",
"\n",
"if",
"n",
"==",
"0",
"{",
"return",
"0",
"\n",
"}",
"\n",
"if",
"n",
"==",
"1",
"{",
"return",
"data",
"[",
"0",
"]",
"\n",
"}",
"\n\n",
"pos",
":=",
"float64",
"(",
"p",
")",
"*",
"float64",
"(",
"n",
"+",
"1",
")",
"/",
"100",
"\n",
"fpos",
":=",
"math",
".",
"Floor",
"(",
"pos",
")",
"\n",
"intPos",
":=",
"int",
"(",
"fpos",
")",
"\n",
"dif",
":=",
"pos",
"-",
"fpos",
"\n",
"if",
"intPos",
"<",
"1",
"{",
"return",
"data",
"[",
"0",
"]",
"\n",
"}",
"\n",
"if",
"intPos",
">=",
"n",
"{",
"return",
"data",
"[",
"n",
"-",
"1",
"]",
"\n",
"}",
"\n",
"lower",
":=",
"data",
"[",
"intPos",
"-",
"1",
"]",
"\n",
"upper",
":=",
"data",
"[",
"intPos",
"]",
"\n",
"val",
":=",
"float64",
"(",
"lower",
")",
"+",
"dif",
"*",
"float64",
"(",
"upper",
"-",
"lower",
")",
"\n",
"return",
"int",
"(",
"math",
".",
"Floor",
"(",
"val",
"+",
"0.5",
")",
")",
"\n",
"}"
] | // Return p percentil of pre-sorted integer data. 0 <= p <= 100. | [
"Return",
"p",
"percentil",
"of",
"pre",
"-",
"sorted",
"integer",
"data",
".",
"0",
"<",
"=",
"p",
"<",
"=",
"100",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/stat.go#L9-L32 | train |
vdobler/chart | svgg/svg.go | New | func New(sp *svg.SVG, width, height int, font string, fontsize int, background color.RGBA) *SvgGraphics {
if font == "" {
font = "Helvetica"
}
if fontsize == 0 {
fontsize = 12
}
s := SvgGraphics{svg: sp, w: width, h: height, font: font, fs: fontsize, bg: background}
return &s
} | go | func New(sp *svg.SVG, width, height int, font string, fontsize int, background color.RGBA) *SvgGraphics {
if font == "" {
font = "Helvetica"
}
if fontsize == 0 {
fontsize = 12
}
s := SvgGraphics{svg: sp, w: width, h: height, font: font, fs: fontsize, bg: background}
return &s
} | [
"func",
"New",
"(",
"sp",
"*",
"svg",
".",
"SVG",
",",
"width",
",",
"height",
"int",
",",
"font",
"string",
",",
"fontsize",
"int",
",",
"background",
"color",
".",
"RGBA",
")",
"*",
"SvgGraphics",
"{",
"if",
"font",
"==",
"\"",
"\"",
"{",
"font",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"fontsize",
"==",
"0",
"{",
"fontsize",
"=",
"12",
"\n",
"}",
"\n",
"s",
":=",
"SvgGraphics",
"{",
"svg",
":",
"sp",
",",
"w",
":",
"width",
",",
"h",
":",
"height",
",",
"font",
":",
"font",
",",
"fs",
":",
"fontsize",
",",
"bg",
":",
"background",
"}",
"\n",
"return",
"&",
"s",
"\n",
"}"
] | // New creates a new SvgGraphics of dimension w x h, with a default font font of size fontsize. | [
"New",
"creates",
"a",
"new",
"SvgGraphics",
"of",
"dimension",
"w",
"x",
"h",
"with",
"a",
"default",
"font",
"font",
"of",
"size",
"fontsize",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/svgg/svg.go#L23-L32 | train |
vdobler/chart | txtg/buf.go | NewTextBuf | func NewTextBuf(w, h int) (tb *TextBuf) {
tb = new(TextBuf)
tb.W, tb.H = w, h
tb.Buf = make([]rune, (w+1)*h)
for i, _ := range tb.Buf {
tb.Buf[i] = ' '
}
for i := 0; i < h; i++ {
tb.Buf[i*(w+1)+w] = '\n'
}
// tb.Buf[0], tb.Buf[(w+1)*h-1] = 'X', 'X'
return
} | go | func NewTextBuf(w, h int) (tb *TextBuf) {
tb = new(TextBuf)
tb.W, tb.H = w, h
tb.Buf = make([]rune, (w+1)*h)
for i, _ := range tb.Buf {
tb.Buf[i] = ' '
}
for i := 0; i < h; i++ {
tb.Buf[i*(w+1)+w] = '\n'
}
// tb.Buf[0], tb.Buf[(w+1)*h-1] = 'X', 'X'
return
} | [
"func",
"NewTextBuf",
"(",
"w",
",",
"h",
"int",
")",
"(",
"tb",
"*",
"TextBuf",
")",
"{",
"tb",
"=",
"new",
"(",
"TextBuf",
")",
"\n",
"tb",
".",
"W",
",",
"tb",
".",
"H",
"=",
"w",
",",
"h",
"\n",
"tb",
".",
"Buf",
"=",
"make",
"(",
"[",
"]",
"rune",
",",
"(",
"w",
"+",
"1",
")",
"*",
"h",
")",
"\n",
"for",
"i",
",",
"_",
":=",
"range",
"tb",
".",
"Buf",
"{",
"tb",
".",
"Buf",
"[",
"i",
"]",
"=",
"' '",
"\n",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"h",
";",
"i",
"++",
"{",
"tb",
".",
"Buf",
"[",
"i",
"*",
"(",
"w",
"+",
"1",
")",
"+",
"w",
"]",
"=",
"'\\n'",
"\n",
"}",
"\n",
"// tb.Buf[0], tb.Buf[(w+1)*h-1] = 'X', 'X'",
"return",
"\n",
"}"
] | // Set up a new TextBuf with width w and height h. | [
"Set",
"up",
"a",
"new",
"TextBuf",
"with",
"width",
"w",
"and",
"height",
"h",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/txtg/buf.go#L17-L29 | train |
vdobler/chart | strip.go | AddData | func (sc *StripChart) AddData(name string, data []float64, style Style) {
n := len(sc.ScatterChart.Data) + 1
pd := make([]EPoint, len(data))
nan := math.NaN()
for i, d := range data {
pd[i].X = d
pd[i].Y = float64(n)
pd[i].DeltaX, pd[i].DeltaY = nan, nan
}
if style.empty() {
style = AutoStyle(len(sc.Data), false)
}
style.LineStyle = 0
sc.ScatterChart.AddData(name, pd, PlotStylePoints, style)
} | go | func (sc *StripChart) AddData(name string, data []float64, style Style) {
n := len(sc.ScatterChart.Data) + 1
pd := make([]EPoint, len(data))
nan := math.NaN()
for i, d := range data {
pd[i].X = d
pd[i].Y = float64(n)
pd[i].DeltaX, pd[i].DeltaY = nan, nan
}
if style.empty() {
style = AutoStyle(len(sc.Data), false)
}
style.LineStyle = 0
sc.ScatterChart.AddData(name, pd, PlotStylePoints, style)
} | [
"func",
"(",
"sc",
"*",
"StripChart",
")",
"AddData",
"(",
"name",
"string",
",",
"data",
"[",
"]",
"float64",
",",
"style",
"Style",
")",
"{",
"n",
":=",
"len",
"(",
"sc",
".",
"ScatterChart",
".",
"Data",
")",
"+",
"1",
"\n",
"pd",
":=",
"make",
"(",
"[",
"]",
"EPoint",
",",
"len",
"(",
"data",
")",
")",
"\n",
"nan",
":=",
"math",
".",
"NaN",
"(",
")",
"\n",
"for",
"i",
",",
"d",
":=",
"range",
"data",
"{",
"pd",
"[",
"i",
"]",
".",
"X",
"=",
"d",
"\n",
"pd",
"[",
"i",
"]",
".",
"Y",
"=",
"float64",
"(",
"n",
")",
"\n",
"pd",
"[",
"i",
"]",
".",
"DeltaX",
",",
"pd",
"[",
"i",
"]",
".",
"DeltaY",
"=",
"nan",
",",
"nan",
"\n",
"}",
"\n",
"if",
"style",
".",
"empty",
"(",
")",
"{",
"style",
"=",
"AutoStyle",
"(",
"len",
"(",
"sc",
".",
"Data",
")",
",",
"false",
")",
"\n",
"}",
"\n",
"style",
".",
"LineStyle",
"=",
"0",
"\n",
"sc",
".",
"ScatterChart",
".",
"AddData",
"(",
"name",
",",
"pd",
",",
"PlotStylePoints",
",",
"style",
")",
"\n",
"}"
] | // AddData adds data to the strip chart. | [
"AddData",
"adds",
"data",
"to",
"the",
"strip",
"chart",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/strip.go#L18-L32 | train |
vdobler/chart | strip.go | Plot | func (sc *StripChart) Plot(g Graphics) {
sc.ScatterChart.YRange.Label = ""
sc.ScatterChart.YRange.TicSetting.Hide = true
sc.ScatterChart.YRange.TicSetting.Delta = 1
sc.ScatterChart.YRange.MinMode.Fixed = true
sc.ScatterChart.YRange.MinMode.Value = 0.5
sc.ScatterChart.YRange.MaxMode.Fixed = true
sc.ScatterChart.YRange.MaxMode.Value = float64(len(sc.ScatterChart.Data)) + 0.5
if sc.Jitter {
// Set up ranging
layout := layout(g, sc.Title, sc.XRange.Label, sc.YRange.Label,
sc.XRange.TicSetting.Hide || sc.XRange.TicSetting.HideLabels,
sc.YRange.TicSetting.Hide || sc.YRange.TicSetting.HideLabels,
&sc.Key)
_, height := layout.Width, layout.Height
topm, _ := layout.Top, layout.Left
_, numytics := layout.NumXtics, layout.NumYtics
sc.YRange.Setup(numytics, numytics+1, height, topm, true)
// amplitude of jitter: not too smal to be visible and useful, not to
// big to be ugly or even overlapp other
null := sc.YRange.Screen2Data(0)
absmin := 1.4 * math.Abs(sc.YRange.Screen2Data(1)-null) // would be one pixel
tenpc := math.Abs(sc.YRange.Screen2Data(height)-null) / 10 // 10 percent of graph area
smplcnt := len(sc.ScatterChart.Data) + 1 // as samples are borders
noverlp := math.Abs(sc.YRange.Screen2Data(height/smplcnt) - null) // do not overlapp other sample
yj := noverlp
if tenpc < yj {
yj = tenpc
}
if yj < absmin {
yj = absmin
}
// yjs := sc.YRange.Data2Screen(yj) - sc.YRange.Data2Screen(0)
// fmt.Printf("yj = %.2f : in screen = %d\n", yj, yjs)
for _, data := range sc.ScatterChart.Data {
if data.Samples == nil {
continue // should not happen
}
for i := range data.Samples {
shift := yj * rand.NormFloat64() * yj
data.Samples[i].Y += shift
}
}
}
sc.ScatterChart.Plot(g)
if sc.Jitter {
// Revert Jitter
for s, data := range sc.ScatterChart.Data {
if data.Samples == nil {
continue // should not happen
}
for i, _ := range data.Samples {
data.Samples[i].Y = float64(s + 1)
}
}
}
} | go | func (sc *StripChart) Plot(g Graphics) {
sc.ScatterChart.YRange.Label = ""
sc.ScatterChart.YRange.TicSetting.Hide = true
sc.ScatterChart.YRange.TicSetting.Delta = 1
sc.ScatterChart.YRange.MinMode.Fixed = true
sc.ScatterChart.YRange.MinMode.Value = 0.5
sc.ScatterChart.YRange.MaxMode.Fixed = true
sc.ScatterChart.YRange.MaxMode.Value = float64(len(sc.ScatterChart.Data)) + 0.5
if sc.Jitter {
// Set up ranging
layout := layout(g, sc.Title, sc.XRange.Label, sc.YRange.Label,
sc.XRange.TicSetting.Hide || sc.XRange.TicSetting.HideLabels,
sc.YRange.TicSetting.Hide || sc.YRange.TicSetting.HideLabels,
&sc.Key)
_, height := layout.Width, layout.Height
topm, _ := layout.Top, layout.Left
_, numytics := layout.NumXtics, layout.NumYtics
sc.YRange.Setup(numytics, numytics+1, height, topm, true)
// amplitude of jitter: not too smal to be visible and useful, not to
// big to be ugly or even overlapp other
null := sc.YRange.Screen2Data(0)
absmin := 1.4 * math.Abs(sc.YRange.Screen2Data(1)-null) // would be one pixel
tenpc := math.Abs(sc.YRange.Screen2Data(height)-null) / 10 // 10 percent of graph area
smplcnt := len(sc.ScatterChart.Data) + 1 // as samples are borders
noverlp := math.Abs(sc.YRange.Screen2Data(height/smplcnt) - null) // do not overlapp other sample
yj := noverlp
if tenpc < yj {
yj = tenpc
}
if yj < absmin {
yj = absmin
}
// yjs := sc.YRange.Data2Screen(yj) - sc.YRange.Data2Screen(0)
// fmt.Printf("yj = %.2f : in screen = %d\n", yj, yjs)
for _, data := range sc.ScatterChart.Data {
if data.Samples == nil {
continue // should not happen
}
for i := range data.Samples {
shift := yj * rand.NormFloat64() * yj
data.Samples[i].Y += shift
}
}
}
sc.ScatterChart.Plot(g)
if sc.Jitter {
// Revert Jitter
for s, data := range sc.ScatterChart.Data {
if data.Samples == nil {
continue // should not happen
}
for i, _ := range data.Samples {
data.Samples[i].Y = float64(s + 1)
}
}
}
} | [
"func",
"(",
"sc",
"*",
"StripChart",
")",
"Plot",
"(",
"g",
"Graphics",
")",
"{",
"sc",
".",
"ScatterChart",
".",
"YRange",
".",
"Label",
"=",
"\"",
"\"",
"\n",
"sc",
".",
"ScatterChart",
".",
"YRange",
".",
"TicSetting",
".",
"Hide",
"=",
"true",
"\n",
"sc",
".",
"ScatterChart",
".",
"YRange",
".",
"TicSetting",
".",
"Delta",
"=",
"1",
"\n",
"sc",
".",
"ScatterChart",
".",
"YRange",
".",
"MinMode",
".",
"Fixed",
"=",
"true",
"\n",
"sc",
".",
"ScatterChart",
".",
"YRange",
".",
"MinMode",
".",
"Value",
"=",
"0.5",
"\n",
"sc",
".",
"ScatterChart",
".",
"YRange",
".",
"MaxMode",
".",
"Fixed",
"=",
"true",
"\n",
"sc",
".",
"ScatterChart",
".",
"YRange",
".",
"MaxMode",
".",
"Value",
"=",
"float64",
"(",
"len",
"(",
"sc",
".",
"ScatterChart",
".",
"Data",
")",
")",
"+",
"0.5",
"\n\n",
"if",
"sc",
".",
"Jitter",
"{",
"// Set up ranging",
"layout",
":=",
"layout",
"(",
"g",
",",
"sc",
".",
"Title",
",",
"sc",
".",
"XRange",
".",
"Label",
",",
"sc",
".",
"YRange",
".",
"Label",
",",
"sc",
".",
"XRange",
".",
"TicSetting",
".",
"Hide",
"||",
"sc",
".",
"XRange",
".",
"TicSetting",
".",
"HideLabels",
",",
"sc",
".",
"YRange",
".",
"TicSetting",
".",
"Hide",
"||",
"sc",
".",
"YRange",
".",
"TicSetting",
".",
"HideLabels",
",",
"&",
"sc",
".",
"Key",
")",
"\n\n",
"_",
",",
"height",
":=",
"layout",
".",
"Width",
",",
"layout",
".",
"Height",
"\n",
"topm",
",",
"_",
":=",
"layout",
".",
"Top",
",",
"layout",
".",
"Left",
"\n",
"_",
",",
"numytics",
":=",
"layout",
".",
"NumXtics",
",",
"layout",
".",
"NumYtics",
"\n\n",
"sc",
".",
"YRange",
".",
"Setup",
"(",
"numytics",
",",
"numytics",
"+",
"1",
",",
"height",
",",
"topm",
",",
"true",
")",
"\n\n",
"// amplitude of jitter: not too smal to be visible and useful, not to",
"// big to be ugly or even overlapp other",
"null",
":=",
"sc",
".",
"YRange",
".",
"Screen2Data",
"(",
"0",
")",
"\n",
"absmin",
":=",
"1.4",
"*",
"math",
".",
"Abs",
"(",
"sc",
".",
"YRange",
".",
"Screen2Data",
"(",
"1",
")",
"-",
"null",
")",
"// would be one pixel",
"\n",
"tenpc",
":=",
"math",
".",
"Abs",
"(",
"sc",
".",
"YRange",
".",
"Screen2Data",
"(",
"height",
")",
"-",
"null",
")",
"/",
"10",
"// 10 percent of graph area",
"\n",
"smplcnt",
":=",
"len",
"(",
"sc",
".",
"ScatterChart",
".",
"Data",
")",
"+",
"1",
"// as samples are borders",
"\n",
"noverlp",
":=",
"math",
".",
"Abs",
"(",
"sc",
".",
"YRange",
".",
"Screen2Data",
"(",
"height",
"/",
"smplcnt",
")",
"-",
"null",
")",
"// do not overlapp other sample",
"\n\n",
"yj",
":=",
"noverlp",
"\n",
"if",
"tenpc",
"<",
"yj",
"{",
"yj",
"=",
"tenpc",
"\n",
"}",
"\n",
"if",
"yj",
"<",
"absmin",
"{",
"yj",
"=",
"absmin",
"\n",
"}",
"\n\n",
"// yjs := sc.YRange.Data2Screen(yj) - sc.YRange.Data2Screen(0)",
"// fmt.Printf(\"yj = %.2f : in screen = %d\\n\", yj, yjs)",
"for",
"_",
",",
"data",
":=",
"range",
"sc",
".",
"ScatterChart",
".",
"Data",
"{",
"if",
"data",
".",
"Samples",
"==",
"nil",
"{",
"continue",
"// should not happen",
"\n",
"}",
"\n",
"for",
"i",
":=",
"range",
"data",
".",
"Samples",
"{",
"shift",
":=",
"yj",
"*",
"rand",
".",
"NormFloat64",
"(",
")",
"*",
"yj",
"\n",
"data",
".",
"Samples",
"[",
"i",
"]",
".",
"Y",
"+=",
"shift",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"sc",
".",
"ScatterChart",
".",
"Plot",
"(",
"g",
")",
"\n\n",
"if",
"sc",
".",
"Jitter",
"{",
"// Revert Jitter",
"for",
"s",
",",
"data",
":=",
"range",
"sc",
".",
"ScatterChart",
".",
"Data",
"{",
"if",
"data",
".",
"Samples",
"==",
"nil",
"{",
"continue",
"// should not happen",
"\n",
"}",
"\n",
"for",
"i",
",",
"_",
":=",
"range",
"data",
".",
"Samples",
"{",
"data",
".",
"Samples",
"[",
"i",
"]",
".",
"Y",
"=",
"float64",
"(",
"s",
"+",
"1",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Plot outputs the strip chart sc to g. | [
"Plot",
"outputs",
"the",
"strip",
"chart",
"sc",
"to",
"g",
"."
] | 6627804132c7c237061d1c8fd2554e3206daecb6 | https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/strip.go#L52-L116 | train |
TheThingsNetwork/ttn | api/health/client.go | Check | func Check(conn *grpc.ClientConn) (bool, error) {
res, err := healthpb.NewHealthClient(conn).Check(context.Background(), &healthpb.HealthCheckRequest{})
if err != nil {
return false, err
}
return res.Status == healthpb.HealthCheckResponse_SERVING, nil
} | go | func Check(conn *grpc.ClientConn) (bool, error) {
res, err := healthpb.NewHealthClient(conn).Check(context.Background(), &healthpb.HealthCheckRequest{})
if err != nil {
return false, err
}
return res.Status == healthpb.HealthCheckResponse_SERVING, nil
} | [
"func",
"Check",
"(",
"conn",
"*",
"grpc",
".",
"ClientConn",
")",
"(",
"bool",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"healthpb",
".",
"NewHealthClient",
"(",
"conn",
")",
".",
"Check",
"(",
"context",
".",
"Background",
"(",
")",
",",
"&",
"healthpb",
".",
"HealthCheckRequest",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"res",
".",
"Status",
"==",
"healthpb",
".",
"HealthCheckResponse_SERVING",
",",
"nil",
"\n",
"}"
] | // Check the health of a connection | [
"Check",
"the",
"health",
"of",
"a",
"connection"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/health/client.go#L13-L19 | train |
TheThingsNetwork/ttn | core/types/parse_hex.go | ParseHEX | func ParseHEX(input string, length int) ([]byte, error) {
if input == "" {
return make([]byte, length), nil
}
pattern := regexp.MustCompile(fmt.Sprintf("^[[:xdigit:]]{%d}$", length*2))
valid := pattern.MatchString(input)
if !valid {
return nil, fmt.Errorf("Invalid input: %s is not hex", input)
}
slice, _ := hex.DecodeString(input)
return slice, nil
} | go | func ParseHEX(input string, length int) ([]byte, error) {
if input == "" {
return make([]byte, length), nil
}
pattern := regexp.MustCompile(fmt.Sprintf("^[[:xdigit:]]{%d}$", length*2))
valid := pattern.MatchString(input)
if !valid {
return nil, fmt.Errorf("Invalid input: %s is not hex", input)
}
slice, _ := hex.DecodeString(input)
return slice, nil
} | [
"func",
"ParseHEX",
"(",
"input",
"string",
",",
"length",
"int",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"input",
"==",
"\"",
"\"",
"{",
"return",
"make",
"(",
"[",
"]",
"byte",
",",
"length",
")",
",",
"nil",
"\n",
"}",
"\n\n",
"pattern",
":=",
"regexp",
".",
"MustCompile",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"length",
"*",
"2",
")",
")",
"\n\n",
"valid",
":=",
"pattern",
".",
"MatchString",
"(",
"input",
")",
"\n",
"if",
"!",
"valid",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"input",
")",
"\n",
"}",
"\n\n",
"slice",
",",
"_",
":=",
"hex",
".",
"DecodeString",
"(",
"input",
")",
"\n\n",
"return",
"slice",
",",
"nil",
"\n",
"}"
] | // ParseHEX parses a string "input" to a byteslice with length "length". | [
"ParseHEX",
"parses",
"a",
"string",
"input",
"to",
"a",
"byteslice",
"with",
"length",
"length",
"."
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/parse_hex.go#L13-L28 | train |
TheThingsNetwork/ttn | core/router/router.go | NewRouter | func NewRouter() Router {
return &router{
gateways: make(map[string]*gateway.Gateway),
brokers: make(map[string]*broker),
}
} | go | func NewRouter() Router {
return &router{
gateways: make(map[string]*gateway.Gateway),
brokers: make(map[string]*broker),
}
} | [
"func",
"NewRouter",
"(",
")",
"Router",
"{",
"return",
"&",
"router",
"{",
"gateways",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"gateway",
".",
"Gateway",
")",
",",
"brokers",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"broker",
")",
",",
"}",
"\n",
"}"
] | // NewRouter creates a new Router | [
"NewRouter",
"creates",
"a",
"new",
"Router"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/router/router.go#L54-L59 | train |
TheThingsNetwork/ttn | core/router/router.go | getGateway | func (r *router) getGateway(id string) *gateway.Gateway {
// We're going to be optimistic and guess that the gateway is already active
r.gatewaysLock.RLock()
gtw, ok := r.gateways[id]
r.gatewaysLock.RUnlock()
if ok {
return gtw
}
// If it doesn't we still have to lock
r.gatewaysLock.Lock()
defer r.gatewaysLock.Unlock()
gtw, ok = r.gateways[id]
if !ok {
gtw = gateway.NewGateway(r.Ctx, id)
ctx := context.Background()
ctx = ttnctx.OutgoingContextWithID(ctx, id)
if r.Identity != nil {
ctx = ttnctx.OutgoingContextWithServiceInfo(ctx, r.Identity.ServiceName, r.Identity.ServiceVersion, r.Identity.NetAddress)
}
gtw.MonitorStream = r.Component.Monitor.GatewayClient(
ctx,
grpc.PerRPCCredentials(auth.WithTokenFunc("id", func(ctxID string) string {
if ctxID != id {
return ""
}
return gtw.Token()
})),
)
r.gateways[id] = gtw
}
return gtw
} | go | func (r *router) getGateway(id string) *gateway.Gateway {
// We're going to be optimistic and guess that the gateway is already active
r.gatewaysLock.RLock()
gtw, ok := r.gateways[id]
r.gatewaysLock.RUnlock()
if ok {
return gtw
}
// If it doesn't we still have to lock
r.gatewaysLock.Lock()
defer r.gatewaysLock.Unlock()
gtw, ok = r.gateways[id]
if !ok {
gtw = gateway.NewGateway(r.Ctx, id)
ctx := context.Background()
ctx = ttnctx.OutgoingContextWithID(ctx, id)
if r.Identity != nil {
ctx = ttnctx.OutgoingContextWithServiceInfo(ctx, r.Identity.ServiceName, r.Identity.ServiceVersion, r.Identity.NetAddress)
}
gtw.MonitorStream = r.Component.Monitor.GatewayClient(
ctx,
grpc.PerRPCCredentials(auth.WithTokenFunc("id", func(ctxID string) string {
if ctxID != id {
return ""
}
return gtw.Token()
})),
)
r.gateways[id] = gtw
}
return gtw
} | [
"func",
"(",
"r",
"*",
"router",
")",
"getGateway",
"(",
"id",
"string",
")",
"*",
"gateway",
".",
"Gateway",
"{",
"// We're going to be optimistic and guess that the gateway is already active",
"r",
".",
"gatewaysLock",
".",
"RLock",
"(",
")",
"\n",
"gtw",
",",
"ok",
":=",
"r",
".",
"gateways",
"[",
"id",
"]",
"\n",
"r",
".",
"gatewaysLock",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"ok",
"{",
"return",
"gtw",
"\n",
"}",
"\n",
"// If it doesn't we still have to lock",
"r",
".",
"gatewaysLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"r",
".",
"gatewaysLock",
".",
"Unlock",
"(",
")",
"\n\n",
"gtw",
",",
"ok",
"=",
"r",
".",
"gateways",
"[",
"id",
"]",
"\n",
"if",
"!",
"ok",
"{",
"gtw",
"=",
"gateway",
".",
"NewGateway",
"(",
"r",
".",
"Ctx",
",",
"id",
")",
"\n",
"ctx",
":=",
"context",
".",
"Background",
"(",
")",
"\n",
"ctx",
"=",
"ttnctx",
".",
"OutgoingContextWithID",
"(",
"ctx",
",",
"id",
")",
"\n",
"if",
"r",
".",
"Identity",
"!=",
"nil",
"{",
"ctx",
"=",
"ttnctx",
".",
"OutgoingContextWithServiceInfo",
"(",
"ctx",
",",
"r",
".",
"Identity",
".",
"ServiceName",
",",
"r",
".",
"Identity",
".",
"ServiceVersion",
",",
"r",
".",
"Identity",
".",
"NetAddress",
")",
"\n",
"}",
"\n",
"gtw",
".",
"MonitorStream",
"=",
"r",
".",
"Component",
".",
"Monitor",
".",
"GatewayClient",
"(",
"ctx",
",",
"grpc",
".",
"PerRPCCredentials",
"(",
"auth",
".",
"WithTokenFunc",
"(",
"\"",
"\"",
",",
"func",
"(",
"ctxID",
"string",
")",
"string",
"{",
"if",
"ctxID",
"!=",
"id",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"gtw",
".",
"Token",
"(",
")",
"\n",
"}",
")",
")",
",",
")",
"\n",
"r",
".",
"gateways",
"[",
"id",
"]",
"=",
"gtw",
"\n",
"}",
"\n\n",
"return",
"gtw",
"\n",
"}"
] | // getGateway gets or creates a Gateway | [
"getGateway",
"gets",
"or",
"creates",
"a",
"Gateway"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/router/router.go#L114-L147 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.