id
int32 0
167k
| 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
listlengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
listlengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
14,800 |
go4org/go4
|
rollsum/rollsum.go
|
OnSplitWithBits
|
func (rs *RollSum) OnSplitWithBits(n uint32) bool {
mask := (uint32(1) << n) - 1
return rs.s2&mask == (^uint32(0))&mask
}
|
go
|
func (rs *RollSum) OnSplitWithBits(n uint32) bool {
mask := (uint32(1) << n) - 1
return rs.s2&mask == (^uint32(0))&mask
}
|
[
"func",
"(",
"rs",
"*",
"RollSum",
")",
"OnSplitWithBits",
"(",
"n",
"uint32",
")",
"bool",
"{",
"mask",
":=",
"(",
"uint32",
"(",
"1",
")",
"<<",
"n",
")",
"-",
"1",
"\n",
"return",
"rs",
".",
"s2",
"&",
"mask",
"==",
"(",
"^",
"uint32",
"(",
"0",
")",
")",
"&",
"mask",
"\n",
"}"
] |
// OnSplitWithBits reports whether at least n consecutive trailing bits
// of the current checksum are set the same way.
|
[
"OnSplitWithBits",
"reports",
"whether",
"at",
"least",
"n",
"consecutive",
"trailing",
"bits",
"of",
"the",
"current",
"checksum",
"are",
"set",
"the",
"same",
"way",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/rollsum/rollsum.go#L69-L72
|
14,801 |
go4org/go4
|
sort/sort.go
|
MakeInterface
|
func MakeInterface(length int, swap func(i, j int), less func(i, j int) bool) Interface {
return &funcs{length, lessSwap{less, swap}}
}
|
go
|
func MakeInterface(length int, swap func(i, j int), less func(i, j int) bool) Interface {
return &funcs{length, lessSwap{less, swap}}
}
|
[
"func",
"MakeInterface",
"(",
"length",
"int",
",",
"swap",
"func",
"(",
"i",
",",
"j",
"int",
")",
",",
"less",
"func",
"(",
"i",
",",
"j",
"int",
")",
"bool",
")",
"Interface",
"{",
"return",
"&",
"funcs",
"{",
"length",
",",
"lessSwap",
"{",
"less",
",",
"swap",
"}",
"}",
"\n",
"}"
] |
// MakeInterface returns a sort Interface using the provided length
// and pair of swap and less functions.
|
[
"MakeInterface",
"returns",
"a",
"sort",
"Interface",
"using",
"the",
"provided",
"length",
"and",
"pair",
"of",
"swap",
"and",
"less",
"functions",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/sort/sort.go#L53-L55
|
14,802 |
go4org/go4
|
sort/sort.go
|
SliceSorter
|
func SliceSorter(slice interface{}, less func(i, j int) bool) Interface {
return MakeInterface(reflect.ValueOf(slice).Len(), reflectutil.Swapper(slice), less)
}
|
go
|
func SliceSorter(slice interface{}, less func(i, j int) bool) Interface {
return MakeInterface(reflect.ValueOf(slice).Len(), reflectutil.Swapper(slice), less)
}
|
[
"func",
"SliceSorter",
"(",
"slice",
"interface",
"{",
"}",
",",
"less",
"func",
"(",
"i",
",",
"j",
"int",
")",
"bool",
")",
"Interface",
"{",
"return",
"MakeInterface",
"(",
"reflect",
".",
"ValueOf",
"(",
"slice",
")",
".",
"Len",
"(",
")",
",",
"reflectutil",
".",
"Swapper",
"(",
"slice",
")",
",",
"less",
")",
"\n",
"}"
] |
// SliceSorter returns a sort.Interface to sort the provided slice
// using the provided less function.
// If the provided interface is not a slice, the function panics.
|
[
"SliceSorter",
"returns",
"a",
"sort",
".",
"Interface",
"to",
"sort",
"the",
"provided",
"slice",
"using",
"the",
"provided",
"less",
"function",
".",
"If",
"the",
"provided",
"interface",
"is",
"not",
"a",
"slice",
"the",
"function",
"panics",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/sort/sort.go#L60-L62
|
14,803 |
go4org/go4
|
sort/sort.go
|
Slice
|
func Slice(slice interface{}, less func(i, j int) bool) {
Sort(SliceSorter(slice, less))
}
|
go
|
func Slice(slice interface{}, less func(i, j int) bool) {
Sort(SliceSorter(slice, less))
}
|
[
"func",
"Slice",
"(",
"slice",
"interface",
"{",
"}",
",",
"less",
"func",
"(",
"i",
",",
"j",
"int",
")",
"bool",
")",
"{",
"Sort",
"(",
"SliceSorter",
"(",
"slice",
",",
"less",
")",
")",
"\n",
"}"
] |
// Slice sorts the provided slice using less.
// If the provided interface is not a slice, the function panics.
// The sort is not stable. For a stable sort, use sort.Stable with sort.SliceSorter.
|
[
"Slice",
"sorts",
"the",
"provided",
"slice",
"using",
"less",
".",
"If",
"the",
"provided",
"interface",
"is",
"not",
"a",
"slice",
"the",
"function",
"panics",
".",
"The",
"sort",
"is",
"not",
"stable",
".",
"For",
"a",
"stable",
"sort",
"use",
"sort",
".",
"Stable",
"with",
"sort",
".",
"SliceSorter",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/sort/sort.go#L67-L69
|
14,804 |
go4org/go4
|
sort/sort.go
|
With
|
func With(length int, swap func(i, j int), less func(i, j int) bool) {
quickSort_func(lessSwap{less, swap}, 0, length, maxDepth(length))
}
|
go
|
func With(length int, swap func(i, j int), less func(i, j int) bool) {
quickSort_func(lessSwap{less, swap}, 0, length, maxDepth(length))
}
|
[
"func",
"With",
"(",
"length",
"int",
",",
"swap",
"func",
"(",
"i",
",",
"j",
"int",
")",
",",
"less",
"func",
"(",
"i",
",",
"j",
"int",
")",
"bool",
")",
"{",
"quickSort_func",
"(",
"lessSwap",
"{",
"less",
",",
"swap",
"}",
",",
"0",
",",
"length",
",",
"maxDepth",
"(",
"length",
")",
")",
"\n",
"}"
] |
// With sorts data given the provided length, swap, and less
// functions.
// The sort is not guaranteed to be stable.
|
[
"With",
"sorts",
"data",
"given",
"the",
"provided",
"length",
"swap",
"and",
"less",
"functions",
".",
"The",
"sort",
"is",
"not",
"guaranteed",
"to",
"be",
"stable",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/sort/sort.go#L290-L292
|
14,805 |
go4org/go4
|
sort/sort.go
|
Less
|
func (r reverse) Less(i, j int) bool {
return r.Interface.Less(j, i)
}
|
go
|
func (r reverse) Less(i, j int) bool {
return r.Interface.Less(j, i)
}
|
[
"func",
"(",
"r",
"reverse",
")",
"Less",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"return",
"r",
".",
"Interface",
".",
"Less",
"(",
"j",
",",
"i",
")",
"\n",
"}"
] |
// Less returns the opposite of the embedded implementation's Less method.
|
[
"Less",
"returns",
"the",
"opposite",
"of",
"the",
"embedded",
"implementation",
"s",
"Less",
"method",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/sort/sort.go#L311-L313
|
14,806 |
go4org/go4
|
sort/sort.go
|
IsSorted
|
func IsSorted(data Interface) bool {
n := data.Len()
for i := n - 1; i > 0; i-- {
if data.Less(i, i-1) {
return false
}
}
return true
}
|
go
|
func IsSorted(data Interface) bool {
n := data.Len()
for i := n - 1; i > 0; i-- {
if data.Less(i, i-1) {
return false
}
}
return true
}
|
[
"func",
"IsSorted",
"(",
"data",
"Interface",
")",
"bool",
"{",
"n",
":=",
"data",
".",
"Len",
"(",
")",
"\n",
"for",
"i",
":=",
"n",
"-",
"1",
";",
"i",
">",
"0",
";",
"i",
"--",
"{",
"if",
"data",
".",
"Less",
"(",
"i",
",",
"i",
"-",
"1",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// IsSorted reports whether data is sorted.
|
[
"IsSorted",
"reports",
"whether",
"data",
"is",
"sorted",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/sort/sort.go#L321-L329
|
14,807 |
go4org/go4
|
media/heif/heif.go
|
EXIFItemID
|
func (m *BoxMeta) EXIFItemID() uint32 {
if m.ItemInfo == nil {
return 0
}
for _, ife := range m.ItemInfo.ItemInfos {
if ife.ItemType == "Exif" {
return uint32(ife.ItemID)
}
}
return 0
}
|
go
|
func (m *BoxMeta) EXIFItemID() uint32 {
if m.ItemInfo == nil {
return 0
}
for _, ife := range m.ItemInfo.ItemInfos {
if ife.ItemType == "Exif" {
return uint32(ife.ItemID)
}
}
return 0
}
|
[
"func",
"(",
"m",
"*",
"BoxMeta",
")",
"EXIFItemID",
"(",
")",
"uint32",
"{",
"if",
"m",
".",
"ItemInfo",
"==",
"nil",
"{",
"return",
"0",
"\n",
"}",
"\n",
"for",
"_",
",",
"ife",
":=",
"range",
"m",
".",
"ItemInfo",
".",
"ItemInfos",
"{",
"if",
"ife",
".",
"ItemType",
"==",
"\"",
"\"",
"{",
"return",
"uint32",
"(",
"ife",
".",
"ItemID",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"0",
"\n",
"}"
] |
// EXIFItemID returns the item ID of the EXIF part, or 0 if not found.
|
[
"EXIFItemID",
"returns",
"the",
"item",
"ID",
"of",
"the",
"EXIF",
"part",
"or",
"0",
"if",
"not",
"found",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/media/heif/heif.go#L56-L66
|
14,808 |
go4org/go4
|
media/heif/heif.go
|
SpatialExtents
|
func (it *Item) SpatialExtents() (width, height int, ok bool) {
for _, p := range it.Properties {
if p, ok := p.(*bmff.ImageSpatialExtentsProperty); ok {
return int(p.ImageWidth), int(p.ImageHeight), true
}
}
return
}
|
go
|
func (it *Item) SpatialExtents() (width, height int, ok bool) {
for _, p := range it.Properties {
if p, ok := p.(*bmff.ImageSpatialExtentsProperty); ok {
return int(p.ImageWidth), int(p.ImageHeight), true
}
}
return
}
|
[
"func",
"(",
"it",
"*",
"Item",
")",
"SpatialExtents",
"(",
")",
"(",
"width",
",",
"height",
"int",
",",
"ok",
"bool",
")",
"{",
"for",
"_",
",",
"p",
":=",
"range",
"it",
".",
"Properties",
"{",
"if",
"p",
",",
"ok",
":=",
"p",
".",
"(",
"*",
"bmff",
".",
"ImageSpatialExtentsProperty",
")",
";",
"ok",
"{",
"return",
"int",
"(",
"p",
".",
"ImageWidth",
")",
",",
"int",
"(",
"p",
".",
"ImageHeight",
")",
",",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// SpatialExtents returns the item's spatial extents property values, if present,
// not correcting from any camera rotation metadata.
|
[
"SpatialExtents",
"returns",
"the",
"item",
"s",
"spatial",
"extents",
"property",
"values",
"if",
"present",
"not",
"correcting",
"from",
"any",
"camera",
"rotation",
"metadata",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/media/heif/heif.go#L80-L87
|
14,809 |
go4org/go4
|
media/heif/heif.go
|
VisualDimensions
|
func (it *Item) VisualDimensions() (width, height int, ok bool) {
width, height, ok = it.SpatialExtents()
for i := 0; i < it.Rotations(); i++ {
width, height = height, width
}
return
}
|
go
|
func (it *Item) VisualDimensions() (width, height int, ok bool) {
width, height, ok = it.SpatialExtents()
for i := 0; i < it.Rotations(); i++ {
width, height = height, width
}
return
}
|
[
"func",
"(",
"it",
"*",
"Item",
")",
"VisualDimensions",
"(",
")",
"(",
"width",
",",
"height",
"int",
",",
"ok",
"bool",
")",
"{",
"width",
",",
"height",
",",
"ok",
"=",
"it",
".",
"SpatialExtents",
"(",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"it",
".",
"Rotations",
"(",
")",
";",
"i",
"++",
"{",
"width",
",",
"height",
"=",
"height",
",",
"width",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// VisualDimensions returns the item's width and height after correcting
// for any rotations.
|
[
"VisualDimensions",
"returns",
"the",
"item",
"s",
"width",
"and",
"height",
"after",
"correcting",
"for",
"any",
"rotations",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/media/heif/heif.go#L102-L108
|
14,810 |
go4org/go4
|
media/heif/heif.go
|
PrimaryItem
|
func (f *File) PrimaryItem() (*Item, error) {
meta, err := f.getMeta()
if err != nil {
return nil, err
}
if meta.PrimaryItem == nil {
return nil, errors.New("heif: HEIF file lacks primary item box")
}
return f.ItemByID(uint32(meta.PrimaryItem.ItemID))
}
|
go
|
func (f *File) PrimaryItem() (*Item, error) {
meta, err := f.getMeta()
if err != nil {
return nil, err
}
if meta.PrimaryItem == nil {
return nil, errors.New("heif: HEIF file lacks primary item box")
}
return f.ItemByID(uint32(meta.PrimaryItem.ItemID))
}
|
[
"func",
"(",
"f",
"*",
"File",
")",
"PrimaryItem",
"(",
")",
"(",
"*",
"Item",
",",
"error",
")",
"{",
"meta",
",",
"err",
":=",
"f",
".",
"getMeta",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"meta",
".",
"PrimaryItem",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"f",
".",
"ItemByID",
"(",
"uint32",
"(",
"meta",
".",
"PrimaryItem",
".",
"ItemID",
")",
")",
"\n",
"}"
] |
// PrimaryItem returns the HEIF file's primary item.
|
[
"PrimaryItem",
"returns",
"the",
"HEIF",
"file",
"s",
"primary",
"item",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/media/heif/heif.go#L220-L229
|
14,811 |
go4org/go4
|
media/heif/heif.go
|
ItemByID
|
func (f *File) ItemByID(id uint32) (*Item, error) {
meta, err := f.getMeta()
if err != nil {
return nil, err
}
it := &Item{
f: f,
ID: id,
}
if meta.ItemLocation != nil {
for _, ilbe := range meta.ItemLocation.Items {
if uint32(ilbe.ItemID) == id {
shallowCopy := ilbe
it.Location = &shallowCopy
}
}
}
if meta.ItemInfo != nil {
for _, iie := range meta.ItemInfo.ItemInfos {
if uint32(iie.ItemID) == id {
it.Info = iie
}
}
}
if it.Info == nil {
return nil, ErrUnknownItem
}
if meta.Properties != nil {
allProps := meta.Properties.PropertyContainer.Properties
for _, ipa := range meta.Properties.Associations {
// TODO: I've never seen a file with more than
// top-level ItemPropertyAssociation box, but
// apparently they can exist with different
// versions/flags. For now we just merge them
// all together, but that's not really right.
// So for now, just bail once a previous loop
// found anything.
if len(it.Properties) > 0 {
break
}
for _, ipai := range ipa.Entries {
if ipai.ItemID != id {
continue
}
for _, ass := range ipai.Associations {
if ass.Index != 0 && int(ass.Index) <= len(allProps) {
box := allProps[ass.Index-1]
boxp, err := box.Parse()
if err == nil {
box = boxp
}
it.Properties = append(it.Properties, box)
}
}
}
}
}
return it, nil
}
|
go
|
func (f *File) ItemByID(id uint32) (*Item, error) {
meta, err := f.getMeta()
if err != nil {
return nil, err
}
it := &Item{
f: f,
ID: id,
}
if meta.ItemLocation != nil {
for _, ilbe := range meta.ItemLocation.Items {
if uint32(ilbe.ItemID) == id {
shallowCopy := ilbe
it.Location = &shallowCopy
}
}
}
if meta.ItemInfo != nil {
for _, iie := range meta.ItemInfo.ItemInfos {
if uint32(iie.ItemID) == id {
it.Info = iie
}
}
}
if it.Info == nil {
return nil, ErrUnknownItem
}
if meta.Properties != nil {
allProps := meta.Properties.PropertyContainer.Properties
for _, ipa := range meta.Properties.Associations {
// TODO: I've never seen a file with more than
// top-level ItemPropertyAssociation box, but
// apparently they can exist with different
// versions/flags. For now we just merge them
// all together, but that's not really right.
// So for now, just bail once a previous loop
// found anything.
if len(it.Properties) > 0 {
break
}
for _, ipai := range ipa.Entries {
if ipai.ItemID != id {
continue
}
for _, ass := range ipai.Associations {
if ass.Index != 0 && int(ass.Index) <= len(allProps) {
box := allProps[ass.Index-1]
boxp, err := box.Parse()
if err == nil {
box = boxp
}
it.Properties = append(it.Properties, box)
}
}
}
}
}
return it, nil
}
|
[
"func",
"(",
"f",
"*",
"File",
")",
"ItemByID",
"(",
"id",
"uint32",
")",
"(",
"*",
"Item",
",",
"error",
")",
"{",
"meta",
",",
"err",
":=",
"f",
".",
"getMeta",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"it",
":=",
"&",
"Item",
"{",
"f",
":",
"f",
",",
"ID",
":",
"id",
",",
"}",
"\n",
"if",
"meta",
".",
"ItemLocation",
"!=",
"nil",
"{",
"for",
"_",
",",
"ilbe",
":=",
"range",
"meta",
".",
"ItemLocation",
".",
"Items",
"{",
"if",
"uint32",
"(",
"ilbe",
".",
"ItemID",
")",
"==",
"id",
"{",
"shallowCopy",
":=",
"ilbe",
"\n",
"it",
".",
"Location",
"=",
"&",
"shallowCopy",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"meta",
".",
"ItemInfo",
"!=",
"nil",
"{",
"for",
"_",
",",
"iie",
":=",
"range",
"meta",
".",
"ItemInfo",
".",
"ItemInfos",
"{",
"if",
"uint32",
"(",
"iie",
".",
"ItemID",
")",
"==",
"id",
"{",
"it",
".",
"Info",
"=",
"iie",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"it",
".",
"Info",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrUnknownItem",
"\n",
"}",
"\n",
"if",
"meta",
".",
"Properties",
"!=",
"nil",
"{",
"allProps",
":=",
"meta",
".",
"Properties",
".",
"PropertyContainer",
".",
"Properties",
"\n",
"for",
"_",
",",
"ipa",
":=",
"range",
"meta",
".",
"Properties",
".",
"Associations",
"{",
"// TODO: I've never seen a file with more than",
"// top-level ItemPropertyAssociation box, but",
"// apparently they can exist with different",
"// versions/flags. For now we just merge them",
"// all together, but that's not really right.",
"// So for now, just bail once a previous loop",
"// found anything.",
"if",
"len",
"(",
"it",
".",
"Properties",
")",
">",
"0",
"{",
"break",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"ipai",
":=",
"range",
"ipa",
".",
"Entries",
"{",
"if",
"ipai",
".",
"ItemID",
"!=",
"id",
"{",
"continue",
"\n",
"}",
"\n",
"for",
"_",
",",
"ass",
":=",
"range",
"ipai",
".",
"Associations",
"{",
"if",
"ass",
".",
"Index",
"!=",
"0",
"&&",
"int",
"(",
"ass",
".",
"Index",
")",
"<=",
"len",
"(",
"allProps",
")",
"{",
"box",
":=",
"allProps",
"[",
"ass",
".",
"Index",
"-",
"1",
"]",
"\n",
"boxp",
",",
"err",
":=",
"box",
".",
"Parse",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"box",
"=",
"boxp",
"\n",
"}",
"\n",
"it",
".",
"Properties",
"=",
"append",
"(",
"it",
".",
"Properties",
",",
"box",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"it",
",",
"nil",
"\n",
"}"
] |
// ItemByID by returns the file's Item of a given ID.
// If the ID is known, the returned error is ErrUnknownItem.
|
[
"ItemByID",
"by",
"returns",
"the",
"file",
"s",
"Item",
"of",
"a",
"given",
"ID",
".",
"If",
"the",
"ID",
"is",
"known",
"the",
"returned",
"error",
"is",
"ErrUnknownItem",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/media/heif/heif.go#L233-L292
|
14,812 |
go4org/go4
|
syncutil/sem.go
|
NewSem
|
func NewSem(max int64) *Sem {
return &Sem{
c: sync.NewCond(new(sync.Mutex)),
free: max,
max: max,
}
}
|
go
|
func NewSem(max int64) *Sem {
return &Sem{
c: sync.NewCond(new(sync.Mutex)),
free: max,
max: max,
}
}
|
[
"func",
"NewSem",
"(",
"max",
"int64",
")",
"*",
"Sem",
"{",
"return",
"&",
"Sem",
"{",
"c",
":",
"sync",
".",
"NewCond",
"(",
"new",
"(",
"sync",
".",
"Mutex",
")",
")",
",",
"free",
":",
"max",
",",
"max",
":",
"max",
",",
"}",
"\n",
"}"
] |
// NewSem creates a semaphore with max units available for acquisition.
|
[
"NewSem",
"creates",
"a",
"semaphore",
"with",
"max",
"units",
"available",
"for",
"acquisition",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/syncutil/sem.go#L27-L33
|
14,813 |
go4org/go4
|
syncutil/sem.go
|
Acquire
|
func (s *Sem) Acquire(n int64) error {
if n > s.max {
return fmt.Errorf("sem: attempt to acquire more units than semaphore size %d > %d", n, s.max)
}
s.c.L.Lock()
defer s.c.L.Unlock()
for {
debug.Printf("Acquire check max %d free %d, n %d", s.max, s.free, n)
if s.free >= n {
s.free -= n
return nil
}
debug.Printf("Acquire Wait max %d free %d, n %d", s.max, s.free, n)
s.c.Wait()
}
}
|
go
|
func (s *Sem) Acquire(n int64) error {
if n > s.max {
return fmt.Errorf("sem: attempt to acquire more units than semaphore size %d > %d", n, s.max)
}
s.c.L.Lock()
defer s.c.L.Unlock()
for {
debug.Printf("Acquire check max %d free %d, n %d", s.max, s.free, n)
if s.free >= n {
s.free -= n
return nil
}
debug.Printf("Acquire Wait max %d free %d, n %d", s.max, s.free, n)
s.c.Wait()
}
}
|
[
"func",
"(",
"s",
"*",
"Sem",
")",
"Acquire",
"(",
"n",
"int64",
")",
"error",
"{",
"if",
"n",
">",
"s",
".",
"max",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"n",
",",
"s",
".",
"max",
")",
"\n",
"}",
"\n",
"s",
".",
"c",
".",
"L",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"c",
".",
"L",
".",
"Unlock",
"(",
")",
"\n",
"for",
"{",
"debug",
".",
"Printf",
"(",
"\"",
"\"",
",",
"s",
".",
"max",
",",
"s",
".",
"free",
",",
"n",
")",
"\n",
"if",
"s",
".",
"free",
">=",
"n",
"{",
"s",
".",
"free",
"-=",
"n",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"debug",
".",
"Printf",
"(",
"\"",
"\"",
",",
"s",
".",
"max",
",",
"s",
".",
"free",
",",
"n",
")",
"\n",
"s",
".",
"c",
".",
"Wait",
"(",
")",
"\n",
"}",
"\n",
"}"
] |
// Acquire will deduct n units from the semaphore. If the deduction would
// result in the available units falling below zero, the call will block until
// another go routine returns units via a call to Release. If more units are
// requested than the semaphore is configured to hold, error will be non-nil.
|
[
"Acquire",
"will",
"deduct",
"n",
"units",
"from",
"the",
"semaphore",
".",
"If",
"the",
"deduction",
"would",
"result",
"in",
"the",
"available",
"units",
"falling",
"below",
"zero",
"the",
"call",
"will",
"block",
"until",
"another",
"go",
"routine",
"returns",
"units",
"via",
"a",
"call",
"to",
"Release",
".",
"If",
"more",
"units",
"are",
"requested",
"than",
"the",
"semaphore",
"is",
"configured",
"to",
"hold",
"error",
"will",
"be",
"non",
"-",
"nil",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/syncutil/sem.go#L39-L54
|
14,814 |
go4org/go4
|
syncutil/sem.go
|
Release
|
func (s *Sem) Release(n int64) {
s.c.L.Lock()
defer s.c.L.Unlock()
debug.Printf("Release max %d free %d, n %d", s.max, s.free, n)
s.free += n
s.c.Broadcast()
}
|
go
|
func (s *Sem) Release(n int64) {
s.c.L.Lock()
defer s.c.L.Unlock()
debug.Printf("Release max %d free %d, n %d", s.max, s.free, n)
s.free += n
s.c.Broadcast()
}
|
[
"func",
"(",
"s",
"*",
"Sem",
")",
"Release",
"(",
"n",
"int64",
")",
"{",
"s",
".",
"c",
".",
"L",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"c",
".",
"L",
".",
"Unlock",
"(",
")",
"\n",
"debug",
".",
"Printf",
"(",
"\"",
"\"",
",",
"s",
".",
"max",
",",
"s",
".",
"free",
",",
"n",
")",
"\n",
"s",
".",
"free",
"+=",
"n",
"\n",
"s",
".",
"c",
".",
"Broadcast",
"(",
")",
"\n",
"}"
] |
// Release will return n units to the semaphore and notify any currently
// blocking Acquire calls.
|
[
"Release",
"will",
"return",
"n",
"units",
"to",
"the",
"semaphore",
"and",
"notify",
"any",
"currently",
"blocking",
"Acquire",
"calls",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/syncutil/sem.go#L58-L64
|
14,815 |
go4org/go4
|
xdgdir/xdgdir.go
|
Path
|
func (d Dir) Path() string {
if d.env == "" {
panic("xdgdir.Dir.Path() on zero Dir")
}
p := d.path()
if p != "" && d.userOwned {
info, err := os.Stat(p)
if err != nil {
return ""
}
if !info.IsDir() || info.Mode().Perm() != 0700 {
return ""
}
st, ok := info.Sys().(*syscall.Stat_t)
if !ok || int(st.Uid) != geteuid() {
return ""
}
}
return p
}
|
go
|
func (d Dir) Path() string {
if d.env == "" {
panic("xdgdir.Dir.Path() on zero Dir")
}
p := d.path()
if p != "" && d.userOwned {
info, err := os.Stat(p)
if err != nil {
return ""
}
if !info.IsDir() || info.Mode().Perm() != 0700 {
return ""
}
st, ok := info.Sys().(*syscall.Stat_t)
if !ok || int(st.Uid) != geteuid() {
return ""
}
}
return p
}
|
[
"func",
"(",
"d",
"Dir",
")",
"Path",
"(",
")",
"string",
"{",
"if",
"d",
".",
"env",
"==",
"\"",
"\"",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"p",
":=",
"d",
".",
"path",
"(",
")",
"\n",
"if",
"p",
"!=",
"\"",
"\"",
"&&",
"d",
".",
"userOwned",
"{",
"info",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"!",
"info",
".",
"IsDir",
"(",
")",
"||",
"info",
".",
"Mode",
"(",
")",
".",
"Perm",
"(",
")",
"!=",
"0700",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"st",
",",
"ok",
":=",
"info",
".",
"Sys",
"(",
")",
".",
"(",
"*",
"syscall",
".",
"Stat_t",
")",
"\n",
"if",
"!",
"ok",
"||",
"int",
"(",
"st",
".",
"Uid",
")",
"!=",
"geteuid",
"(",
")",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"p",
"\n",
"}"
] |
// Path returns the absolute path of the primary directory, or an empty
// string if there's no suitable directory present. This is the path
// that should be used for writing files.
|
[
"Path",
"returns",
"the",
"absolute",
"path",
"of",
"the",
"primary",
"directory",
"or",
"an",
"empty",
"string",
"if",
"there",
"s",
"no",
"suitable",
"directory",
"present",
".",
"This",
"is",
"the",
"path",
"that",
"should",
"be",
"used",
"for",
"writing",
"files",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/xdgdir/xdgdir.go#L102-L121
|
14,816 |
go4org/go4
|
xdgdir/xdgdir.go
|
Open
|
func (d Dir) Open(name string) (*os.File, error) {
if d.env == "" {
return nil, errors.New("xdgdir: Open on zero Dir")
}
paths := d.SearchPaths()
if len(paths) == 0 {
return nil, fmt.Errorf("xdgdir: open %s: %s is invalid or not set", name, d.env)
}
var firstErr error
for _, p := range paths {
f, err := os.Open(filepath.Join(p, name))
if err == nil {
return f, nil
} else if !os.IsNotExist(err) {
firstErr = err
}
}
if firstErr != nil {
return nil, firstErr
}
return nil, &os.PathError{
Op: "Open",
Path: filepath.Join("$"+d.env, name),
Err: os.ErrNotExist,
}
}
|
go
|
func (d Dir) Open(name string) (*os.File, error) {
if d.env == "" {
return nil, errors.New("xdgdir: Open on zero Dir")
}
paths := d.SearchPaths()
if len(paths) == 0 {
return nil, fmt.Errorf("xdgdir: open %s: %s is invalid or not set", name, d.env)
}
var firstErr error
for _, p := range paths {
f, err := os.Open(filepath.Join(p, name))
if err == nil {
return f, nil
} else if !os.IsNotExist(err) {
firstErr = err
}
}
if firstErr != nil {
return nil, firstErr
}
return nil, &os.PathError{
Op: "Open",
Path: filepath.Join("$"+d.env, name),
Err: os.ErrNotExist,
}
}
|
[
"func",
"(",
"d",
"Dir",
")",
"Open",
"(",
"name",
"string",
")",
"(",
"*",
"os",
".",
"File",
",",
"error",
")",
"{",
"if",
"d",
".",
"env",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"paths",
":=",
"d",
".",
"SearchPaths",
"(",
")",
"\n",
"if",
"len",
"(",
"paths",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"d",
".",
"env",
")",
"\n",
"}",
"\n",
"var",
"firstErr",
"error",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"paths",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"filepath",
".",
"Join",
"(",
"p",
",",
"name",
")",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"f",
",",
"nil",
"\n",
"}",
"else",
"if",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"firstErr",
"=",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"firstErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"firstErr",
"\n",
"}",
"\n",
"return",
"nil",
",",
"&",
"os",
".",
"PathError",
"{",
"Op",
":",
"\"",
"\"",
",",
"Path",
":",
"filepath",
".",
"Join",
"(",
"\"",
"\"",
"+",
"d",
".",
"env",
",",
"name",
")",
",",
"Err",
":",
"os",
".",
"ErrNotExist",
",",
"}",
"\n",
"}"
] |
// Open opens the named file inside the directory for reading. If the
// directory has multiple search paths, each path is checked in order
// for the file and the first one found is opened.
|
[
"Open",
"opens",
"the",
"named",
"file",
"inside",
"the",
"directory",
"for",
"reading",
".",
"If",
"the",
"directory",
"has",
"multiple",
"search",
"paths",
"each",
"path",
"is",
"checked",
"in",
"order",
"for",
"the",
"file",
"and",
"the",
"first",
"one",
"found",
"is",
"opened",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/xdgdir/xdgdir.go#L174-L199
|
14,817 |
go4org/go4
|
readerutil/readerutil.go
|
NewStatsReader
|
func NewStatsReader(v *expvar.Int, r io.Reader) io.Reader {
return &varStatReader{v, r}
}
|
go
|
func NewStatsReader(v *expvar.Int, r io.Reader) io.Reader {
return &varStatReader{v, r}
}
|
[
"func",
"NewStatsReader",
"(",
"v",
"*",
"expvar",
".",
"Int",
",",
"r",
"io",
".",
"Reader",
")",
"io",
".",
"Reader",
"{",
"return",
"&",
"varStatReader",
"{",
"v",
",",
"r",
"}",
"\n",
"}"
] |
// NewStatsReader returns an io.Reader that will have the number of bytes
// read from r added to v.
|
[
"NewStatsReader",
"returns",
"an",
"io",
".",
"Reader",
"that",
"will",
"have",
"the",
"number",
"of",
"bytes",
"read",
"from",
"r",
"added",
"to",
"v",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/readerutil/readerutil.go#L55-L57
|
14,818 |
go4org/go4
|
readerutil/readerutil.go
|
NewStatsReadSeeker
|
func NewStatsReadSeeker(v *expvar.Int, rs io.ReadSeeker) io.ReadSeeker {
return &varStatReadSeeker{v, rs}
}
|
go
|
func NewStatsReadSeeker(v *expvar.Int, rs io.ReadSeeker) io.ReadSeeker {
return &varStatReadSeeker{v, rs}
}
|
[
"func",
"NewStatsReadSeeker",
"(",
"v",
"*",
"expvar",
".",
"Int",
",",
"rs",
"io",
".",
"ReadSeeker",
")",
"io",
".",
"ReadSeeker",
"{",
"return",
"&",
"varStatReadSeeker",
"{",
"v",
",",
"rs",
"}",
"\n",
"}"
] |
// NewStatsReadSeeker returns an io.ReadSeeker that will have the number of bytes
// read from rs added to v.
|
[
"NewStatsReadSeeker",
"returns",
"an",
"io",
".",
"ReadSeeker",
"that",
"will",
"have",
"the",
"number",
"of",
"bytes",
"read",
"from",
"rs",
"added",
"to",
"v",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/readerutil/readerutil.go#L72-L74
|
14,819 |
go4org/go4
|
writerutil/writerutil.go
|
Bytes
|
func (w *PrefixSuffixSaver) Bytes() []byte {
if w.suffix == nil {
return w.prefix
}
if w.skipped == 0 {
return append(w.prefix, w.suffix...)
}
var buf bytes.Buffer
buf.Grow(len(w.prefix) + len(w.suffix) + 50)
buf.Write(w.prefix)
buf.WriteString("\n... omitting ")
buf.WriteString(strconv.FormatInt(w.skipped, 10))
buf.WriteString(" bytes ...\n")
buf.Write(w.suffix[w.suffixOff:])
buf.Write(w.suffix[:w.suffixOff])
return buf.Bytes()
}
|
go
|
func (w *PrefixSuffixSaver) Bytes() []byte {
if w.suffix == nil {
return w.prefix
}
if w.skipped == 0 {
return append(w.prefix, w.suffix...)
}
var buf bytes.Buffer
buf.Grow(len(w.prefix) + len(w.suffix) + 50)
buf.Write(w.prefix)
buf.WriteString("\n... omitting ")
buf.WriteString(strconv.FormatInt(w.skipped, 10))
buf.WriteString(" bytes ...\n")
buf.Write(w.suffix[w.suffixOff:])
buf.Write(w.suffix[:w.suffixOff])
return buf.Bytes()
}
|
[
"func",
"(",
"w",
"*",
"PrefixSuffixSaver",
")",
"Bytes",
"(",
")",
"[",
"]",
"byte",
"{",
"if",
"w",
".",
"suffix",
"==",
"nil",
"{",
"return",
"w",
".",
"prefix",
"\n",
"}",
"\n",
"if",
"w",
".",
"skipped",
"==",
"0",
"{",
"return",
"append",
"(",
"w",
".",
"prefix",
",",
"w",
".",
"suffix",
"...",
")",
"\n",
"}",
"\n",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"buf",
".",
"Grow",
"(",
"len",
"(",
"w",
".",
"prefix",
")",
"+",
"len",
"(",
"w",
".",
"suffix",
")",
"+",
"50",
")",
"\n",
"buf",
".",
"Write",
"(",
"w",
".",
"prefix",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"\"",
"\\n",
"\"",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"strconv",
".",
"FormatInt",
"(",
"w",
".",
"skipped",
",",
"10",
")",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"\"",
"\\n",
"\"",
")",
"\n",
"buf",
".",
"Write",
"(",
"w",
".",
"suffix",
"[",
"w",
".",
"suffixOff",
":",
"]",
")",
"\n",
"buf",
".",
"Write",
"(",
"w",
".",
"suffix",
"[",
":",
"w",
".",
"suffixOff",
"]",
")",
"\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
"\n",
"}"
] |
// Bytes returns a slice of the bytes, or a copy of the bytes, retained by w.
// If more bytes than could be retained were written to w, it returns a
// concatenation of the N first bytes, a message for how many bytes were dropped,
// and the N last bytes.
|
[
"Bytes",
"returns",
"a",
"slice",
"of",
"the",
"bytes",
"or",
"a",
"copy",
"of",
"the",
"bytes",
"retained",
"by",
"w",
".",
"If",
"more",
"bytes",
"than",
"could",
"be",
"retained",
"were",
"written",
"to",
"w",
"it",
"returns",
"a",
"concatenation",
"of",
"the",
"N",
"first",
"bytes",
"a",
"message",
"for",
"how",
"many",
"bytes",
"were",
"dropped",
"and",
"the",
"N",
"last",
"bytes",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/writerutil/writerutil.go#L82-L98
|
14,820 |
go4org/go4
|
syncutil/syncdebug/syncdebug.go
|
GoroutineID
|
func GoroutineID() int64 {
b := getBuf()
defer putBuf(b)
b = b[:runtime.Stack(b, false)]
// Parse the 4707 out of "goroutine 4707 ["
b = bytes.TrimPrefix(b, goroutineSpace)
i := bytes.IndexByte(b, ' ')
if i < 0 {
panic(fmt.Sprintf("No space found in %q", b))
}
b = b[:i]
n, err := strutil.ParseUintBytes(b, 10, 64)
if err != nil {
panic(fmt.Sprintf("Failed to parse goroutine ID out of %q: %v", b, err))
}
return int64(n)
}
|
go
|
func GoroutineID() int64 {
b := getBuf()
defer putBuf(b)
b = b[:runtime.Stack(b, false)]
// Parse the 4707 out of "goroutine 4707 ["
b = bytes.TrimPrefix(b, goroutineSpace)
i := bytes.IndexByte(b, ' ')
if i < 0 {
panic(fmt.Sprintf("No space found in %q", b))
}
b = b[:i]
n, err := strutil.ParseUintBytes(b, 10, 64)
if err != nil {
panic(fmt.Sprintf("Failed to parse goroutine ID out of %q: %v", b, err))
}
return int64(n)
}
|
[
"func",
"GoroutineID",
"(",
")",
"int64",
"{",
"b",
":=",
"getBuf",
"(",
")",
"\n",
"defer",
"putBuf",
"(",
"b",
")",
"\n",
"b",
"=",
"b",
"[",
":",
"runtime",
".",
"Stack",
"(",
"b",
",",
"false",
")",
"]",
"\n",
"// Parse the 4707 out of \"goroutine 4707 [\"",
"b",
"=",
"bytes",
".",
"TrimPrefix",
"(",
"b",
",",
"goroutineSpace",
")",
"\n",
"i",
":=",
"bytes",
".",
"IndexByte",
"(",
"b",
",",
"' '",
")",
"\n",
"if",
"i",
"<",
"0",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"b",
")",
")",
"\n",
"}",
"\n",
"b",
"=",
"b",
"[",
":",
"i",
"]",
"\n",
"n",
",",
"err",
":=",
"strutil",
".",
"ParseUintBytes",
"(",
"b",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"b",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"return",
"int64",
"(",
"n",
")",
"\n",
"}"
] |
// GoroutineID returns the current goroutine's ID.
// Use of this function is almost always a terrible idea.
// It is also very slow.
// GoroutineID is intended only for debugging.
// In particular, it is used by syncutil.
|
[
"GoroutineID",
"returns",
"the",
"current",
"goroutine",
"s",
"ID",
".",
"Use",
"of",
"this",
"function",
"is",
"almost",
"always",
"a",
"terrible",
"idea",
".",
"It",
"is",
"also",
"very",
"slow",
".",
"GoroutineID",
"is",
"intended",
"only",
"for",
"debugging",
".",
"In",
"particular",
"it",
"is",
"used",
"by",
"syncutil",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/syncutil/syncdebug/syncdebug.go#L78-L94
|
14,821 |
go4org/go4
|
fault/fault.go
|
ShouldFail
|
func (in *Injector) ShouldFail() bool {
return in.failPercent > 0 && in.failPercent > rand.Intn(100)
}
|
go
|
func (in *Injector) ShouldFail() bool {
return in.failPercent > 0 && in.failPercent > rand.Intn(100)
}
|
[
"func",
"(",
"in",
"*",
"Injector",
")",
"ShouldFail",
"(",
")",
"bool",
"{",
"return",
"in",
".",
"failPercent",
">",
"0",
"&&",
"in",
".",
"failPercent",
">",
"rand",
".",
"Intn",
"(",
"100",
")",
"\n",
"}"
] |
// ShouldFail reports whether a fake error should be returned.
|
[
"ShouldFail",
"reports",
"whether",
"a",
"fake",
"error",
"should",
"be",
"returned",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/fault/fault.go#L47-L49
|
14,822 |
go4org/go4
|
fault/fault.go
|
FailErr
|
func (in *Injector) FailErr(err *error) bool {
if !in.ShouldFail() {
return false
}
*err = fakeErr
return true
}
|
go
|
func (in *Injector) FailErr(err *error) bool {
if !in.ShouldFail() {
return false
}
*err = fakeErr
return true
}
|
[
"func",
"(",
"in",
"*",
"Injector",
")",
"FailErr",
"(",
"err",
"*",
"error",
")",
"bool",
"{",
"if",
"!",
"in",
".",
"ShouldFail",
"(",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"*",
"err",
"=",
"fakeErr",
"\n",
"return",
"true",
"\n",
"}"
] |
// FailErr checks ShouldFail and, if true, assigns a fake error to err
// and returns true.
|
[
"FailErr",
"checks",
"ShouldFail",
"and",
"if",
"true",
"assigns",
"a",
"fake",
"error",
"to",
"err",
"and",
"returns",
"true",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/fault/fault.go#L53-L59
|
14,823 |
go4org/go4
|
jsonconfig/jsonconfig.go
|
UnknownKeys
|
func (jc Obj) UnknownKeys() []string {
ei, ok := jc["_knownkeys"]
var known map[string]bool
if ok {
known = ei.(map[string]bool)
}
var unknown []string
for k, _ := range jc {
if ok && known[k] {
continue
}
if strings.HasPrefix(k, "_") {
// Permit keys with a leading underscore as a
// form of comments.
continue
}
unknown = append(unknown, k)
}
sort.Strings(unknown)
return unknown
}
|
go
|
func (jc Obj) UnknownKeys() []string {
ei, ok := jc["_knownkeys"]
var known map[string]bool
if ok {
known = ei.(map[string]bool)
}
var unknown []string
for k, _ := range jc {
if ok && known[k] {
continue
}
if strings.HasPrefix(k, "_") {
// Permit keys with a leading underscore as a
// form of comments.
continue
}
unknown = append(unknown, k)
}
sort.Strings(unknown)
return unknown
}
|
[
"func",
"(",
"jc",
"Obj",
")",
"UnknownKeys",
"(",
")",
"[",
"]",
"string",
"{",
"ei",
",",
"ok",
":=",
"jc",
"[",
"\"",
"\"",
"]",
"\n",
"var",
"known",
"map",
"[",
"string",
"]",
"bool",
"\n",
"if",
"ok",
"{",
"known",
"=",
"ei",
".",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
"\n",
"}",
"\n",
"var",
"unknown",
"[",
"]",
"string",
"\n",
"for",
"k",
",",
"_",
":=",
"range",
"jc",
"{",
"if",
"ok",
"&&",
"known",
"[",
"k",
"]",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"k",
",",
"\"",
"\"",
")",
"{",
"// Permit keys with a leading underscore as a",
"// form of comments.",
"continue",
"\n",
"}",
"\n",
"unknown",
"=",
"append",
"(",
"unknown",
",",
"k",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"unknown",
")",
"\n",
"return",
"unknown",
"\n",
"}"
] |
// UnknownKeys returns the keys from the config that have not yet been discovered by one of the RequiredT or OptionalT calls.
|
[
"UnknownKeys",
"returns",
"the",
"keys",
"from",
"the",
"config",
"that",
"have",
"not",
"yet",
"been",
"discovered",
"by",
"one",
"of",
"the",
"RequiredT",
"or",
"OptionalT",
"calls",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/jsonconfig/jsonconfig.go#L256-L276
|
14,824 |
go4org/go4
|
syncutil/group.go
|
Err
|
func (g *Group) Err() error {
g.wg.Wait()
if len(g.errs) > 0 {
return g.errs[0]
}
return nil
}
|
go
|
func (g *Group) Err() error {
g.wg.Wait()
if len(g.errs) > 0 {
return g.errs[0]
}
return nil
}
|
[
"func",
"(",
"g",
"*",
"Group",
")",
"Err",
"(",
")",
"error",
"{",
"g",
".",
"wg",
".",
"Wait",
"(",
")",
"\n",
"if",
"len",
"(",
"g",
".",
"errs",
")",
">",
"0",
"{",
"return",
"g",
".",
"errs",
"[",
"0",
"]",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Err waits for all previous calls to Go to complete and returns the
// first non-nil error, or nil.
|
[
"Err",
"waits",
"for",
"all",
"previous",
"calls",
"to",
"Go",
"to",
"complete",
"and",
"returns",
"the",
"first",
"non",
"-",
"nil",
"error",
"or",
"nil",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/syncutil/group.go#L51-L57
|
14,825 |
go4org/go4
|
bytereplacer/bytereplacer.go
|
New
|
func New(oldnew ...string) *Replacer {
if len(oldnew)%2 == 1 {
panic("bytes.NewReplacer: odd argument count")
}
allNewBytes := true
for i := 0; i < len(oldnew); i += 2 {
if len(oldnew[i]) != 1 {
return &Replacer{r: makeGenericReplacer(oldnew)}
}
if len(oldnew[i+1]) != 1 {
allNewBytes = false
}
}
if allNewBytes {
r := byteReplacer{}
for i := range r {
r[i] = byte(i)
}
// The first occurrence of old->new map takes precedence
// over the others with the same old string.
for i := len(oldnew) - 2; i >= 0; i -= 2 {
o := oldnew[i][0]
n := oldnew[i+1][0]
r[o] = n
}
return &Replacer{r: &r}
}
return &Replacer{r: makeGenericReplacer(oldnew)}
}
|
go
|
func New(oldnew ...string) *Replacer {
if len(oldnew)%2 == 1 {
panic("bytes.NewReplacer: odd argument count")
}
allNewBytes := true
for i := 0; i < len(oldnew); i += 2 {
if len(oldnew[i]) != 1 {
return &Replacer{r: makeGenericReplacer(oldnew)}
}
if len(oldnew[i+1]) != 1 {
allNewBytes = false
}
}
if allNewBytes {
r := byteReplacer{}
for i := range r {
r[i] = byte(i)
}
// The first occurrence of old->new map takes precedence
// over the others with the same old string.
for i := len(oldnew) - 2; i >= 0; i -= 2 {
o := oldnew[i][0]
n := oldnew[i+1][0]
r[o] = n
}
return &Replacer{r: &r}
}
return &Replacer{r: makeGenericReplacer(oldnew)}
}
|
[
"func",
"New",
"(",
"oldnew",
"...",
"string",
")",
"*",
"Replacer",
"{",
"if",
"len",
"(",
"oldnew",
")",
"%",
"2",
"==",
"1",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"allNewBytes",
":=",
"true",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"oldnew",
")",
";",
"i",
"+=",
"2",
"{",
"if",
"len",
"(",
"oldnew",
"[",
"i",
"]",
")",
"!=",
"1",
"{",
"return",
"&",
"Replacer",
"{",
"r",
":",
"makeGenericReplacer",
"(",
"oldnew",
")",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"oldnew",
"[",
"i",
"+",
"1",
"]",
")",
"!=",
"1",
"{",
"allNewBytes",
"=",
"false",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"allNewBytes",
"{",
"r",
":=",
"byteReplacer",
"{",
"}",
"\n",
"for",
"i",
":=",
"range",
"r",
"{",
"r",
"[",
"i",
"]",
"=",
"byte",
"(",
"i",
")",
"\n",
"}",
"\n",
"// The first occurrence of old->new map takes precedence",
"// over the others with the same old string.",
"for",
"i",
":=",
"len",
"(",
"oldnew",
")",
"-",
"2",
";",
"i",
">=",
"0",
";",
"i",
"-=",
"2",
"{",
"o",
":=",
"oldnew",
"[",
"i",
"]",
"[",
"0",
"]",
"\n",
"n",
":=",
"oldnew",
"[",
"i",
"+",
"1",
"]",
"[",
"0",
"]",
"\n",
"r",
"[",
"o",
"]",
"=",
"n",
"\n",
"}",
"\n",
"return",
"&",
"Replacer",
"{",
"r",
":",
"&",
"r",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"Replacer",
"{",
"r",
":",
"makeGenericReplacer",
"(",
"oldnew",
")",
"}",
"\n",
"}"
] |
// New returns a new Replacer from a list of old, new string pairs.
// Replacements are performed in order, without overlapping matches.
|
[
"New",
"returns",
"a",
"new",
"Replacer",
"from",
"a",
"list",
"of",
"old",
"new",
"string",
"pairs",
".",
"Replacements",
"are",
"performed",
"in",
"order",
"without",
"overlapping",
"matches",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/bytereplacer/bytereplacer.go#L36-L67
|
14,826 |
go4org/go4
|
bytereplacer/bytereplacer.go
|
Replace
|
func (r *Replacer) Replace(s []byte) []byte {
return r.r.Replace(s)
}
|
go
|
func (r *Replacer) Replace(s []byte) []byte {
return r.r.Replace(s)
}
|
[
"func",
"(",
"r",
"*",
"Replacer",
")",
"Replace",
"(",
"s",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"return",
"r",
".",
"r",
".",
"Replace",
"(",
"s",
")",
"\n",
"}"
] |
// Replace performs all replacements in-place on s. If the capacity
// of s is not sufficient, a new slice is allocated, otherwise Replace
// returns s.
|
[
"Replace",
"performs",
"all",
"replacements",
"in",
"-",
"place",
"on",
"s",
".",
"If",
"the",
"capacity",
"of",
"s",
"is",
"not",
"sufficient",
"a",
"new",
"slice",
"is",
"allocated",
"otherwise",
"Replace",
"returns",
"s",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/bytereplacer/bytereplacer.go#L72-L74
|
14,827 |
go4org/go4
|
readerutil/readersize.go
|
Size
|
func Size(r io.Reader) (size int64, ok bool) {
switch rt := r.(type) {
case *bytes.Buffer:
return int64(rt.Len()), true
case *bytes.Reader:
return int64(rt.Len()), true
case *strings.Reader:
return int64(rt.Len()), true
case io.Seeker:
pos, err := rt.Seek(0, os.SEEK_CUR)
if err != nil {
return
}
end, err := rt.Seek(0, os.SEEK_END)
if err != nil {
return
}
size = end - pos
pos1, err := rt.Seek(pos, os.SEEK_SET)
if err != nil || pos1 != pos {
msg := "failed to restore seek position"
if err != nil {
msg += ": " + err.Error()
}
panic(msg)
}
return size, true
}
return 0, false
}
|
go
|
func Size(r io.Reader) (size int64, ok bool) {
switch rt := r.(type) {
case *bytes.Buffer:
return int64(rt.Len()), true
case *bytes.Reader:
return int64(rt.Len()), true
case *strings.Reader:
return int64(rt.Len()), true
case io.Seeker:
pos, err := rt.Seek(0, os.SEEK_CUR)
if err != nil {
return
}
end, err := rt.Seek(0, os.SEEK_END)
if err != nil {
return
}
size = end - pos
pos1, err := rt.Seek(pos, os.SEEK_SET)
if err != nil || pos1 != pos {
msg := "failed to restore seek position"
if err != nil {
msg += ": " + err.Error()
}
panic(msg)
}
return size, true
}
return 0, false
}
|
[
"func",
"Size",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"size",
"int64",
",",
"ok",
"bool",
")",
"{",
"switch",
"rt",
":=",
"r",
".",
"(",
"type",
")",
"{",
"case",
"*",
"bytes",
".",
"Buffer",
":",
"return",
"int64",
"(",
"rt",
".",
"Len",
"(",
")",
")",
",",
"true",
"\n",
"case",
"*",
"bytes",
".",
"Reader",
":",
"return",
"int64",
"(",
"rt",
".",
"Len",
"(",
")",
")",
",",
"true",
"\n",
"case",
"*",
"strings",
".",
"Reader",
":",
"return",
"int64",
"(",
"rt",
".",
"Len",
"(",
")",
")",
",",
"true",
"\n",
"case",
"io",
".",
"Seeker",
":",
"pos",
",",
"err",
":=",
"rt",
".",
"Seek",
"(",
"0",
",",
"os",
".",
"SEEK_CUR",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"end",
",",
"err",
":=",
"rt",
".",
"Seek",
"(",
"0",
",",
"os",
".",
"SEEK_END",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"size",
"=",
"end",
"-",
"pos",
"\n",
"pos1",
",",
"err",
":=",
"rt",
".",
"Seek",
"(",
"pos",
",",
"os",
".",
"SEEK_SET",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"pos1",
"!=",
"pos",
"{",
"msg",
":=",
"\"",
"\"",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"msg",
"+=",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"panic",
"(",
"msg",
")",
"\n",
"}",
"\n",
"return",
"size",
",",
"true",
"\n",
"}",
"\n",
"return",
"0",
",",
"false",
"\n",
"}"
] |
// Size tries to determine the length of r. If r is an io.Seeker, Size may seek
// to guess the length.
|
[
"Size",
"tries",
"to",
"determine",
"the",
"length",
"of",
"r",
".",
"If",
"r",
"is",
"an",
"io",
".",
"Seeker",
"Size",
"may",
"seek",
"to",
"guess",
"the",
"length",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/readerutil/readersize.go#L29-L58
|
14,828 |
go4org/go4
|
strutil/strutil.go
|
equalFoldRune
|
func equalFoldRune(sr, tr rune) bool {
if sr == tr {
return true
}
// Make sr < tr to simplify what follows.
if tr < sr {
sr, tr = tr, sr
}
// Fast check for ASCII.
if tr < utf8.RuneSelf && 'A' <= sr && sr <= 'Z' {
// ASCII, and sr is upper case. tr must be lower case.
if tr == sr+'a'-'A' {
return true
}
return false
}
// General case. SimpleFold(x) returns the next equivalent rune > x
// or wraps around to smaller values.
r := unicode.SimpleFold(sr)
for r != sr && r < tr {
r = unicode.SimpleFold(r)
}
if r == tr {
return true
}
return false
}
|
go
|
func equalFoldRune(sr, tr rune) bool {
if sr == tr {
return true
}
// Make sr < tr to simplify what follows.
if tr < sr {
sr, tr = tr, sr
}
// Fast check for ASCII.
if tr < utf8.RuneSelf && 'A' <= sr && sr <= 'Z' {
// ASCII, and sr is upper case. tr must be lower case.
if tr == sr+'a'-'A' {
return true
}
return false
}
// General case. SimpleFold(x) returns the next equivalent rune > x
// or wraps around to smaller values.
r := unicode.SimpleFold(sr)
for r != sr && r < tr {
r = unicode.SimpleFold(r)
}
if r == tr {
return true
}
return false
}
|
[
"func",
"equalFoldRune",
"(",
"sr",
",",
"tr",
"rune",
")",
"bool",
"{",
"if",
"sr",
"==",
"tr",
"{",
"return",
"true",
"\n",
"}",
"\n",
"// Make sr < tr to simplify what follows.",
"if",
"tr",
"<",
"sr",
"{",
"sr",
",",
"tr",
"=",
"tr",
",",
"sr",
"\n",
"}",
"\n",
"// Fast check for ASCII.",
"if",
"tr",
"<",
"utf8",
".",
"RuneSelf",
"&&",
"'A'",
"<=",
"sr",
"&&",
"sr",
"<=",
"'Z'",
"{",
"// ASCII, and sr is upper case. tr must be lower case.",
"if",
"tr",
"==",
"sr",
"+",
"'a'",
"-",
"'A'",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
"\n\n",
"// General case. SimpleFold(x) returns the next equivalent rune > x",
"// or wraps around to smaller values.",
"r",
":=",
"unicode",
".",
"SimpleFold",
"(",
"sr",
")",
"\n",
"for",
"r",
"!=",
"sr",
"&&",
"r",
"<",
"tr",
"{",
"r",
"=",
"unicode",
".",
"SimpleFold",
"(",
"r",
")",
"\n",
"}",
"\n",
"if",
"r",
"==",
"tr",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// equalFoldRune compares a and b runes whether they fold equally.
//
// The code comes from strings.EqualFold, but shortened to only one rune.
|
[
"equalFoldRune",
"compares",
"a",
"and",
"b",
"runes",
"whether",
"they",
"fold",
"equally",
".",
"The",
"code",
"comes",
"from",
"strings",
".",
"EqualFold",
"but",
"shortened",
"to",
"only",
"one",
"rune",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/strutil/strutil.go#L67-L94
|
14,829 |
go4org/go4
|
strutil/strutil.go
|
HasPrefixFold
|
func HasPrefixFold(s, prefix string) bool {
if prefix == "" {
return true
}
for _, pr := range prefix {
if s == "" {
return false
}
// step with s, too
sr, size := utf8.DecodeRuneInString(s)
if sr == utf8.RuneError {
return false
}
s = s[size:]
if !equalFoldRune(sr, pr) {
return false
}
}
return true
}
|
go
|
func HasPrefixFold(s, prefix string) bool {
if prefix == "" {
return true
}
for _, pr := range prefix {
if s == "" {
return false
}
// step with s, too
sr, size := utf8.DecodeRuneInString(s)
if sr == utf8.RuneError {
return false
}
s = s[size:]
if !equalFoldRune(sr, pr) {
return false
}
}
return true
}
|
[
"func",
"HasPrefixFold",
"(",
"s",
",",
"prefix",
"string",
")",
"bool",
"{",
"if",
"prefix",
"==",
"\"",
"\"",
"{",
"return",
"true",
"\n",
"}",
"\n",
"for",
"_",
",",
"pr",
":=",
"range",
"prefix",
"{",
"if",
"s",
"==",
"\"",
"\"",
"{",
"return",
"false",
"\n",
"}",
"\n",
"// step with s, too",
"sr",
",",
"size",
":=",
"utf8",
".",
"DecodeRuneInString",
"(",
"s",
")",
"\n",
"if",
"sr",
"==",
"utf8",
".",
"RuneError",
"{",
"return",
"false",
"\n",
"}",
"\n",
"s",
"=",
"s",
"[",
"size",
":",
"]",
"\n",
"if",
"!",
"equalFoldRune",
"(",
"sr",
",",
"pr",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// HasPrefixFold is like strings.HasPrefix but uses Unicode case-folding.
|
[
"HasPrefixFold",
"is",
"like",
"strings",
".",
"HasPrefix",
"but",
"uses",
"Unicode",
"case",
"-",
"folding",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/strutil/strutil.go#L97-L116
|
14,830 |
go4org/go4
|
strutil/strutil.go
|
HasSuffixFold
|
func HasSuffixFold(s, suffix string) bool {
if suffix == "" {
return true
}
// count the runes and bytes in s, but only till rune count of suffix
bo, so := len(s), len(suffix)
for bo > 0 && so > 0 {
r, size := utf8.DecodeLastRuneInString(s[:bo])
if r == utf8.RuneError {
return false
}
bo -= size
sr, size := utf8.DecodeLastRuneInString(suffix[:so])
if sr == utf8.RuneError {
return false
}
so -= size
if !equalFoldRune(r, sr) {
return false
}
}
return so == 0
}
|
go
|
func HasSuffixFold(s, suffix string) bool {
if suffix == "" {
return true
}
// count the runes and bytes in s, but only till rune count of suffix
bo, so := len(s), len(suffix)
for bo > 0 && so > 0 {
r, size := utf8.DecodeLastRuneInString(s[:bo])
if r == utf8.RuneError {
return false
}
bo -= size
sr, size := utf8.DecodeLastRuneInString(suffix[:so])
if sr == utf8.RuneError {
return false
}
so -= size
if !equalFoldRune(r, sr) {
return false
}
}
return so == 0
}
|
[
"func",
"HasSuffixFold",
"(",
"s",
",",
"suffix",
"string",
")",
"bool",
"{",
"if",
"suffix",
"==",
"\"",
"\"",
"{",
"return",
"true",
"\n",
"}",
"\n",
"// count the runes and bytes in s, but only till rune count of suffix",
"bo",
",",
"so",
":=",
"len",
"(",
"s",
")",
",",
"len",
"(",
"suffix",
")",
"\n",
"for",
"bo",
">",
"0",
"&&",
"so",
">",
"0",
"{",
"r",
",",
"size",
":=",
"utf8",
".",
"DecodeLastRuneInString",
"(",
"s",
"[",
":",
"bo",
"]",
")",
"\n",
"if",
"r",
"==",
"utf8",
".",
"RuneError",
"{",
"return",
"false",
"\n",
"}",
"\n",
"bo",
"-=",
"size",
"\n\n",
"sr",
",",
"size",
":=",
"utf8",
".",
"DecodeLastRuneInString",
"(",
"suffix",
"[",
":",
"so",
"]",
")",
"\n",
"if",
"sr",
"==",
"utf8",
".",
"RuneError",
"{",
"return",
"false",
"\n",
"}",
"\n",
"so",
"-=",
"size",
"\n\n",
"if",
"!",
"equalFoldRune",
"(",
"r",
",",
"sr",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"so",
"==",
"0",
"\n",
"}"
] |
// HasSuffixFold is like strings.HasPrefix but uses Unicode case-folding.
|
[
"HasSuffixFold",
"is",
"like",
"strings",
".",
"HasPrefix",
"but",
"uses",
"Unicode",
"case",
"-",
"folding",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/strutil/strutil.go#L119-L143
|
14,831 |
go4org/go4
|
strutil/strutil.go
|
ContainsFold
|
func ContainsFold(s, substr string) bool {
if substr == "" {
return true
}
if s == "" {
return false
}
firstRune := rune(substr[0])
if firstRune >= utf8.RuneSelf {
firstRune, _ = utf8.DecodeRuneInString(substr)
}
for i, rune := range s {
if equalFoldRune(rune, firstRune) && HasPrefixFold(s[i:], substr) {
return true
}
}
return false
}
|
go
|
func ContainsFold(s, substr string) bool {
if substr == "" {
return true
}
if s == "" {
return false
}
firstRune := rune(substr[0])
if firstRune >= utf8.RuneSelf {
firstRune, _ = utf8.DecodeRuneInString(substr)
}
for i, rune := range s {
if equalFoldRune(rune, firstRune) && HasPrefixFold(s[i:], substr) {
return true
}
}
return false
}
|
[
"func",
"ContainsFold",
"(",
"s",
",",
"substr",
"string",
")",
"bool",
"{",
"if",
"substr",
"==",
"\"",
"\"",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"s",
"==",
"\"",
"\"",
"{",
"return",
"false",
"\n",
"}",
"\n",
"firstRune",
":=",
"rune",
"(",
"substr",
"[",
"0",
"]",
")",
"\n",
"if",
"firstRune",
">=",
"utf8",
".",
"RuneSelf",
"{",
"firstRune",
",",
"_",
"=",
"utf8",
".",
"DecodeRuneInString",
"(",
"substr",
")",
"\n",
"}",
"\n",
"for",
"i",
",",
"rune",
":=",
"range",
"s",
"{",
"if",
"equalFoldRune",
"(",
"rune",
",",
"firstRune",
")",
"&&",
"HasPrefixFold",
"(",
"s",
"[",
"i",
":",
"]",
",",
"substr",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// ContainsFold is like strings.Contains but uses Unicode case-folding.
|
[
"ContainsFold",
"is",
"like",
"strings",
".",
"Contains",
"but",
"uses",
"Unicode",
"case",
"-",
"folding",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/strutil/strutil.go#L146-L163
|
14,832 |
go4org/go4
|
readerutil/singlereader/opener.go
|
Open
|
func Open(path string) (readerutil.ReaderAtCloser, error) {
openFileMu.Lock()
of := openFiles[path]
if of != nil {
of.refCount++
openFileMu.Unlock()
return &openFileHandle{false, of}, nil
}
openFileMu.Unlock() // release the lock while we call os.Open
winner := false // this goroutine made it into Do's func
// Returns an *openFile
resi, err := openerGroup.Do(path, func() (interface{}, error) {
winner = true
f, err := wkfs.Open(path)
if err != nil {
return nil, err
}
of := &openFile{
File: f,
path: path,
refCount: 1,
}
openFileMu.Lock()
openFiles[path] = of
openFileMu.Unlock()
return of, nil
})
if err != nil {
return nil, err
}
of = resi.(*openFile)
// If our os.Open was dup-suppressed, we have to increment our
// reference count.
if !winner {
openFileMu.Lock()
if of.refCount == 0 {
// Winner already closed it. Try again (rare).
openFileMu.Unlock()
return Open(path)
}
of.refCount++
openFileMu.Unlock()
}
return &openFileHandle{false, of}, nil
}
|
go
|
func Open(path string) (readerutil.ReaderAtCloser, error) {
openFileMu.Lock()
of := openFiles[path]
if of != nil {
of.refCount++
openFileMu.Unlock()
return &openFileHandle{false, of}, nil
}
openFileMu.Unlock() // release the lock while we call os.Open
winner := false // this goroutine made it into Do's func
// Returns an *openFile
resi, err := openerGroup.Do(path, func() (interface{}, error) {
winner = true
f, err := wkfs.Open(path)
if err != nil {
return nil, err
}
of := &openFile{
File: f,
path: path,
refCount: 1,
}
openFileMu.Lock()
openFiles[path] = of
openFileMu.Unlock()
return of, nil
})
if err != nil {
return nil, err
}
of = resi.(*openFile)
// If our os.Open was dup-suppressed, we have to increment our
// reference count.
if !winner {
openFileMu.Lock()
if of.refCount == 0 {
// Winner already closed it. Try again (rare).
openFileMu.Unlock()
return Open(path)
}
of.refCount++
openFileMu.Unlock()
}
return &openFileHandle{false, of}, nil
}
|
[
"func",
"Open",
"(",
"path",
"string",
")",
"(",
"readerutil",
".",
"ReaderAtCloser",
",",
"error",
")",
"{",
"openFileMu",
".",
"Lock",
"(",
")",
"\n",
"of",
":=",
"openFiles",
"[",
"path",
"]",
"\n",
"if",
"of",
"!=",
"nil",
"{",
"of",
".",
"refCount",
"++",
"\n",
"openFileMu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"&",
"openFileHandle",
"{",
"false",
",",
"of",
"}",
",",
"nil",
"\n",
"}",
"\n",
"openFileMu",
".",
"Unlock",
"(",
")",
"// release the lock while we call os.Open",
"\n\n",
"winner",
":=",
"false",
"// this goroutine made it into Do's func",
"\n\n",
"// Returns an *openFile",
"resi",
",",
"err",
":=",
"openerGroup",
".",
"Do",
"(",
"path",
",",
"func",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"winner",
"=",
"true",
"\n",
"f",
",",
"err",
":=",
"wkfs",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"of",
":=",
"&",
"openFile",
"{",
"File",
":",
"f",
",",
"path",
":",
"path",
",",
"refCount",
":",
"1",
",",
"}",
"\n",
"openFileMu",
".",
"Lock",
"(",
")",
"\n",
"openFiles",
"[",
"path",
"]",
"=",
"of",
"\n",
"openFileMu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"of",
",",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"of",
"=",
"resi",
".",
"(",
"*",
"openFile",
")",
"\n\n",
"// If our os.Open was dup-suppressed, we have to increment our",
"// reference count.",
"if",
"!",
"winner",
"{",
"openFileMu",
".",
"Lock",
"(",
")",
"\n",
"if",
"of",
".",
"refCount",
"==",
"0",
"{",
"// Winner already closed it. Try again (rare).",
"openFileMu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"Open",
"(",
"path",
")",
"\n",
"}",
"\n",
"of",
".",
"refCount",
"++",
"\n",
"openFileMu",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"return",
"&",
"openFileHandle",
"{",
"false",
",",
"of",
"}",
",",
"nil",
"\n",
"}"
] |
// Open opens the given file path for reading, reusing existing file descriptors
// when possible.
|
[
"Open",
"opens",
"the",
"given",
"file",
"path",
"for",
"reading",
"reusing",
"existing",
"file",
"descriptors",
"when",
"possible",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/readerutil/singlereader/opener.go#L71-L118
|
14,833 |
go4org/go4
|
cloud/google/gceutil/gceutil.go
|
CoreOSImageURL
|
func CoreOSImageURL(cl *http.Client) (string, error) {
resp, err := cl.Get("https://www.googleapis.com/compute/v1/projects/coreos-cloud/global/images")
if err != nil {
return "", err
}
defer resp.Body.Close()
type coreOSImage struct {
SelfLink string
CreationTimestamp time.Time
Name string
}
type coreOSImageList struct {
Items []coreOSImage
}
imageList := &coreOSImageList{}
if err := json.NewDecoder(resp.Body).Decode(imageList); err != nil {
return "", err
}
if imageList == nil || len(imageList.Items) == 0 {
return "", errors.New("no images list in response")
}
imageURL := ""
var max time.Time // latest stable image creation time
for _, v := range imageList.Items {
if !strings.HasPrefix(v.Name, "coreos-stable") {
continue
}
if v.CreationTimestamp.After(max) {
max = v.CreationTimestamp
imageURL = v.SelfLink
}
}
if imageURL == "" {
return "", errors.New("no stable coreOS image found")
}
return imageURL, nil
}
|
go
|
func CoreOSImageURL(cl *http.Client) (string, error) {
resp, err := cl.Get("https://www.googleapis.com/compute/v1/projects/coreos-cloud/global/images")
if err != nil {
return "", err
}
defer resp.Body.Close()
type coreOSImage struct {
SelfLink string
CreationTimestamp time.Time
Name string
}
type coreOSImageList struct {
Items []coreOSImage
}
imageList := &coreOSImageList{}
if err := json.NewDecoder(resp.Body).Decode(imageList); err != nil {
return "", err
}
if imageList == nil || len(imageList.Items) == 0 {
return "", errors.New("no images list in response")
}
imageURL := ""
var max time.Time // latest stable image creation time
for _, v := range imageList.Items {
if !strings.HasPrefix(v.Name, "coreos-stable") {
continue
}
if v.CreationTimestamp.After(max) {
max = v.CreationTimestamp
imageURL = v.SelfLink
}
}
if imageURL == "" {
return "", errors.New("no stable coreOS image found")
}
return imageURL, nil
}
|
[
"func",
"CoreOSImageURL",
"(",
"cl",
"*",
"http",
".",
"Client",
")",
"(",
"string",
",",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"cl",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"type",
"coreOSImage",
"struct",
"{",
"SelfLink",
"string",
"\n",
"CreationTimestamp",
"time",
".",
"Time",
"\n",
"Name",
"string",
"\n",
"}",
"\n\n",
"type",
"coreOSImageList",
"struct",
"{",
"Items",
"[",
"]",
"coreOSImage",
"\n",
"}",
"\n\n",
"imageList",
":=",
"&",
"coreOSImageList",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"NewDecoder",
"(",
"resp",
".",
"Body",
")",
".",
"Decode",
"(",
"imageList",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"imageList",
"==",
"nil",
"||",
"len",
"(",
"imageList",
".",
"Items",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"imageURL",
":=",
"\"",
"\"",
"\n",
"var",
"max",
"time",
".",
"Time",
"// latest stable image creation time",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"imageList",
".",
"Items",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"v",
".",
"Name",
",",
"\"",
"\"",
")",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"v",
".",
"CreationTimestamp",
".",
"After",
"(",
"max",
")",
"{",
"max",
"=",
"v",
".",
"CreationTimestamp",
"\n",
"imageURL",
"=",
"v",
".",
"SelfLink",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"imageURL",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"imageURL",
",",
"nil",
"\n",
"}"
] |
// CoreOSImageURL returns the URL of the latest stable CoreOS image for running on Google Compute Engine.
|
[
"CoreOSImageURL",
"returns",
"the",
"URL",
"of",
"the",
"latest",
"stable",
"CoreOS",
"image",
"for",
"running",
"on",
"Google",
"Compute",
"Engine",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/cloud/google/gceutil/gceutil.go#L32-L72
|
14,834 |
go4org/go4
|
cloud/google/gceutil/gceutil.go
|
InstanceGroups
|
func InstanceGroups(svc *compute.Service, proj, zone string) (map[string]InstanceGroupAndManager, error) {
managerList, err := svc.InstanceGroupManagers.List(proj, zone).Do()
if err != nil {
return nil, err
}
if managerList.NextPageToken != "" {
return nil, errors.New("too many managers; pagination not supported")
}
managedBy := make(map[string]*compute.InstanceGroupManager) // instance group URL -> its manager
for _, it := range managerList.Items {
managedBy[it.InstanceGroup] = it
}
groupList, err := svc.InstanceGroups.List(proj, zone).Do()
if err != nil {
return nil, err
}
if groupList.NextPageToken != "" {
return nil, errors.New("too many instance groups; pagination not supported")
}
ret := make(map[string]InstanceGroupAndManager)
for _, it := range groupList.Items {
ret[it.SelfLink] = InstanceGroupAndManager{it, managedBy[it.SelfLink]}
}
return ret, nil
}
|
go
|
func InstanceGroups(svc *compute.Service, proj, zone string) (map[string]InstanceGroupAndManager, error) {
managerList, err := svc.InstanceGroupManagers.List(proj, zone).Do()
if err != nil {
return nil, err
}
if managerList.NextPageToken != "" {
return nil, errors.New("too many managers; pagination not supported")
}
managedBy := make(map[string]*compute.InstanceGroupManager) // instance group URL -> its manager
for _, it := range managerList.Items {
managedBy[it.InstanceGroup] = it
}
groupList, err := svc.InstanceGroups.List(proj, zone).Do()
if err != nil {
return nil, err
}
if groupList.NextPageToken != "" {
return nil, errors.New("too many instance groups; pagination not supported")
}
ret := make(map[string]InstanceGroupAndManager)
for _, it := range groupList.Items {
ret[it.SelfLink] = InstanceGroupAndManager{it, managedBy[it.SelfLink]}
}
return ret, nil
}
|
[
"func",
"InstanceGroups",
"(",
"svc",
"*",
"compute",
".",
"Service",
",",
"proj",
",",
"zone",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"InstanceGroupAndManager",
",",
"error",
")",
"{",
"managerList",
",",
"err",
":=",
"svc",
".",
"InstanceGroupManagers",
".",
"List",
"(",
"proj",
",",
"zone",
")",
".",
"Do",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"managerList",
".",
"NextPageToken",
"!=",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"managedBy",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"compute",
".",
"InstanceGroupManager",
")",
"// instance group URL -> its manager",
"\n",
"for",
"_",
",",
"it",
":=",
"range",
"managerList",
".",
"Items",
"{",
"managedBy",
"[",
"it",
".",
"InstanceGroup",
"]",
"=",
"it",
"\n",
"}",
"\n",
"groupList",
",",
"err",
":=",
"svc",
".",
"InstanceGroups",
".",
"List",
"(",
"proj",
",",
"zone",
")",
".",
"Do",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"groupList",
".",
"NextPageToken",
"!=",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"ret",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"InstanceGroupAndManager",
")",
"\n",
"for",
"_",
",",
"it",
":=",
"range",
"groupList",
".",
"Items",
"{",
"ret",
"[",
"it",
".",
"SelfLink",
"]",
"=",
"InstanceGroupAndManager",
"{",
"it",
",",
"managedBy",
"[",
"it",
".",
"SelfLink",
"]",
"}",
"\n",
"}",
"\n",
"return",
"ret",
",",
"nil",
"\n",
"}"
] |
// InstanceGroups returns all the instance groups in a project's zone, along
// with their associated InstanceGroupManagers.
// The returned map is keyed by the instance group identifier URL.
|
[
"InstanceGroups",
"returns",
"all",
"the",
"instance",
"groups",
"in",
"a",
"project",
"s",
"zone",
"along",
"with",
"their",
"associated",
"InstanceGroupManagers",
".",
"The",
"returned",
"map",
"is",
"keyed",
"by",
"the",
"instance",
"group",
"identifier",
"URL",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/cloud/google/gceutil/gceutil.go#L86-L110
|
14,835 |
go4org/go4
|
wkfs/gcs/gcs.go
|
Open
|
func (fs *gcsFS) Open(name string) (wkfs.File, error) {
bucket, fileName, err := fs.parseName(name)
if err != nil {
return nil, err
}
obj := fs.sc.Bucket(bucket).Object(fileName)
attrs, err := obj.Attrs(fs.ctx)
if err != nil {
return nil, err
}
size := attrs.Size
if size > maxSize {
return nil, fmt.Errorf("file %s too large (%d bytes) for /gcs/ filesystem", name, size)
}
rc, err := obj.NewReader(fs.ctx)
if err != nil {
return nil, err
}
defer rc.Close()
slurp, err := ioutil.ReadAll(io.LimitReader(rc, size))
if err != nil {
return nil, err
}
return &file{
name: name,
Reader: bytes.NewReader(slurp),
}, nil
}
|
go
|
func (fs *gcsFS) Open(name string) (wkfs.File, error) {
bucket, fileName, err := fs.parseName(name)
if err != nil {
return nil, err
}
obj := fs.sc.Bucket(bucket).Object(fileName)
attrs, err := obj.Attrs(fs.ctx)
if err != nil {
return nil, err
}
size := attrs.Size
if size > maxSize {
return nil, fmt.Errorf("file %s too large (%d bytes) for /gcs/ filesystem", name, size)
}
rc, err := obj.NewReader(fs.ctx)
if err != nil {
return nil, err
}
defer rc.Close()
slurp, err := ioutil.ReadAll(io.LimitReader(rc, size))
if err != nil {
return nil, err
}
return &file{
name: name,
Reader: bytes.NewReader(slurp),
}, nil
}
|
[
"func",
"(",
"fs",
"*",
"gcsFS",
")",
"Open",
"(",
"name",
"string",
")",
"(",
"wkfs",
".",
"File",
",",
"error",
")",
"{",
"bucket",
",",
"fileName",
",",
"err",
":=",
"fs",
".",
"parseName",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"obj",
":=",
"fs",
".",
"sc",
".",
"Bucket",
"(",
"bucket",
")",
".",
"Object",
"(",
"fileName",
")",
"\n",
"attrs",
",",
"err",
":=",
"obj",
".",
"Attrs",
"(",
"fs",
".",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"size",
":=",
"attrs",
".",
"Size",
"\n",
"if",
"size",
">",
"maxSize",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"size",
")",
"\n",
"}",
"\n",
"rc",
",",
"err",
":=",
"obj",
".",
"NewReader",
"(",
"fs",
".",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"rc",
".",
"Close",
"(",
")",
"\n\n",
"slurp",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"io",
".",
"LimitReader",
"(",
"rc",
",",
"size",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"file",
"{",
"name",
":",
"name",
",",
"Reader",
":",
"bytes",
".",
"NewReader",
"(",
"slurp",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// Open opens the named file for reading. It returns an error if the file size
// is larger than 1 << 20.
|
[
"Open",
"opens",
"the",
"named",
"file",
"for",
"reading",
".",
"It",
"returns",
"an",
"error",
"if",
"the",
"file",
"size",
"is",
"larger",
"than",
"1",
"<<",
"20",
"."
] |
94abd6928b1da39b1d757b60c93fb2419c409fa1
|
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/wkfs/gcs/gcs.go#L97-L125
|
14,836 |
mjibson/go-dsp
|
fft/fft.go
|
IFFT
|
func IFFT(x []complex128) []complex128 {
lx := len(x)
r := make([]complex128, lx)
// Reverse inputs, which is calculated with modulo N, hence x[0] as an outlier
r[0] = x[0]
for i := 1; i < lx; i++ {
r[i] = x[lx-i]
}
r = FFT(r)
N := complex(float64(lx), 0)
for n := range r {
r[n] /= N
}
return r
}
|
go
|
func IFFT(x []complex128) []complex128 {
lx := len(x)
r := make([]complex128, lx)
// Reverse inputs, which is calculated with modulo N, hence x[0] as an outlier
r[0] = x[0]
for i := 1; i < lx; i++ {
r[i] = x[lx-i]
}
r = FFT(r)
N := complex(float64(lx), 0)
for n := range r {
r[n] /= N
}
return r
}
|
[
"func",
"IFFT",
"(",
"x",
"[",
"]",
"complex128",
")",
"[",
"]",
"complex128",
"{",
"lx",
":=",
"len",
"(",
"x",
")",
"\n",
"r",
":=",
"make",
"(",
"[",
"]",
"complex128",
",",
"lx",
")",
"\n\n",
"// Reverse inputs, which is calculated with modulo N, hence x[0] as an outlier",
"r",
"[",
"0",
"]",
"=",
"x",
"[",
"0",
"]",
"\n",
"for",
"i",
":=",
"1",
";",
"i",
"<",
"lx",
";",
"i",
"++",
"{",
"r",
"[",
"i",
"]",
"=",
"x",
"[",
"lx",
"-",
"i",
"]",
"\n",
"}",
"\n\n",
"r",
"=",
"FFT",
"(",
"r",
")",
"\n\n",
"N",
":=",
"complex",
"(",
"float64",
"(",
"lx",
")",
",",
"0",
")",
"\n",
"for",
"n",
":=",
"range",
"r",
"{",
"r",
"[",
"n",
"]",
"/=",
"N",
"\n",
"}",
"\n",
"return",
"r",
"\n",
"}"
] |
// IFFT returns the inverse FFT of the complex-valued slice.
|
[
"IFFT",
"returns",
"the",
"inverse",
"FFT",
"of",
"the",
"complex",
"-",
"valued",
"slice",
"."
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/fft/fft.go#L35-L52
|
14,837 |
mjibson/go-dsp
|
fft/fft.go
|
FFT
|
func FFT(x []complex128) []complex128 {
lx := len(x)
// todo: non-hack handling length <= 1 cases
if lx <= 1 {
r := make([]complex128, lx)
copy(r, x)
return r
}
if dsputils.IsPowerOf2(lx) {
return radix2FFT(x)
}
return bluesteinFFT(x)
}
|
go
|
func FFT(x []complex128) []complex128 {
lx := len(x)
// todo: non-hack handling length <= 1 cases
if lx <= 1 {
r := make([]complex128, lx)
copy(r, x)
return r
}
if dsputils.IsPowerOf2(lx) {
return radix2FFT(x)
}
return bluesteinFFT(x)
}
|
[
"func",
"FFT",
"(",
"x",
"[",
"]",
"complex128",
")",
"[",
"]",
"complex128",
"{",
"lx",
":=",
"len",
"(",
"x",
")",
"\n\n",
"// todo: non-hack handling length <= 1 cases",
"if",
"lx",
"<=",
"1",
"{",
"r",
":=",
"make",
"(",
"[",
"]",
"complex128",
",",
"lx",
")",
"\n",
"copy",
"(",
"r",
",",
"x",
")",
"\n",
"return",
"r",
"\n",
"}",
"\n\n",
"if",
"dsputils",
".",
"IsPowerOf2",
"(",
"lx",
")",
"{",
"return",
"radix2FFT",
"(",
"x",
")",
"\n",
"}",
"\n\n",
"return",
"bluesteinFFT",
"(",
"x",
")",
"\n",
"}"
] |
// FFT returns the forward FFT of the complex-valued slice.
|
[
"FFT",
"returns",
"the",
"forward",
"FFT",
"of",
"the",
"complex",
"-",
"valued",
"slice",
"."
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/fft/fft.go#L72-L87
|
14,838 |
mjibson/go-dsp
|
fft/fft.go
|
decrDim
|
func decrDim(x, d []int) bool {
for n, v := range x {
if v == -1 {
continue
} else if v == 0 {
i := n
// find the next element to decrement
for ; i < len(x); i++ {
if x[i] == -1 {
continue
} else if x[i] == 0 {
x[i] = d[i]
} else {
x[i] -= 1
return true
}
}
// no decrement
return false
} else {
x[n] -= 1
return true
}
}
return false
}
|
go
|
func decrDim(x, d []int) bool {
for n, v := range x {
if v == -1 {
continue
} else if v == 0 {
i := n
// find the next element to decrement
for ; i < len(x); i++ {
if x[i] == -1 {
continue
} else if x[i] == 0 {
x[i] = d[i]
} else {
x[i] -= 1
return true
}
}
// no decrement
return false
} else {
x[n] -= 1
return true
}
}
return false
}
|
[
"func",
"decrDim",
"(",
"x",
",",
"d",
"[",
"]",
"int",
")",
"bool",
"{",
"for",
"n",
",",
"v",
":=",
"range",
"x",
"{",
"if",
"v",
"==",
"-",
"1",
"{",
"continue",
"\n",
"}",
"else",
"if",
"v",
"==",
"0",
"{",
"i",
":=",
"n",
"\n",
"// find the next element to decrement",
"for",
";",
"i",
"<",
"len",
"(",
"x",
")",
";",
"i",
"++",
"{",
"if",
"x",
"[",
"i",
"]",
"==",
"-",
"1",
"{",
"continue",
"\n",
"}",
"else",
"if",
"x",
"[",
"i",
"]",
"==",
"0",
"{",
"x",
"[",
"i",
"]",
"=",
"d",
"[",
"i",
"]",
"\n",
"}",
"else",
"{",
"x",
"[",
"i",
"]",
"-=",
"1",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"// no decrement",
"return",
"false",
"\n",
"}",
"else",
"{",
"x",
"[",
"n",
"]",
"-=",
"1",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
] |
// decrDim decrements an element of x by 1, skipping all -1s, and wrapping up to d.
// If a value is 0, it will be reset to its correspending value in d, and will carry one from the next non -1 value to the right.
// Returns true if decremented, else false.
|
[
"decrDim",
"decrements",
"an",
"element",
"of",
"x",
"by",
"1",
"skipping",
"all",
"-",
"1s",
"and",
"wrapping",
"up",
"to",
"d",
".",
"If",
"a",
"value",
"is",
"0",
"it",
"will",
"be",
"reset",
"to",
"its",
"correspending",
"value",
"in",
"d",
"and",
"will",
"carry",
"one",
"from",
"the",
"next",
"non",
"-",
"1",
"value",
"to",
"the",
"right",
".",
"Returns",
"true",
"if",
"decremented",
"else",
"false",
"."
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/fft/fft.go#L197-L224
|
14,839 |
mjibson/go-dsp
|
fft/bluestein.go
|
bluesteinFFT
|
func bluesteinFFT(x []complex128) []complex128 {
lx := len(x)
a := dsputils.ZeroPad(x, dsputils.NextPowerOf2(lx*2-1))
la := len(a)
factors, invFactors := getBluesteinFactors(lx)
for n, v := range x {
a[n] = v * invFactors[n]
}
b := make([]complex128, la)
for i := 0; i < lx; i++ {
b[i] = factors[i]
if i != 0 {
b[la-i] = factors[i]
}
}
r := Convolve(a, b)
for i := 0; i < lx; i++ {
r[i] *= invFactors[i]
}
return r[:lx]
}
|
go
|
func bluesteinFFT(x []complex128) []complex128 {
lx := len(x)
a := dsputils.ZeroPad(x, dsputils.NextPowerOf2(lx*2-1))
la := len(a)
factors, invFactors := getBluesteinFactors(lx)
for n, v := range x {
a[n] = v * invFactors[n]
}
b := make([]complex128, la)
for i := 0; i < lx; i++ {
b[i] = factors[i]
if i != 0 {
b[la-i] = factors[i]
}
}
r := Convolve(a, b)
for i := 0; i < lx; i++ {
r[i] *= invFactors[i]
}
return r[:lx]
}
|
[
"func",
"bluesteinFFT",
"(",
"x",
"[",
"]",
"complex128",
")",
"[",
"]",
"complex128",
"{",
"lx",
":=",
"len",
"(",
"x",
")",
"\n",
"a",
":=",
"dsputils",
".",
"ZeroPad",
"(",
"x",
",",
"dsputils",
".",
"NextPowerOf2",
"(",
"lx",
"*",
"2",
"-",
"1",
")",
")",
"\n",
"la",
":=",
"len",
"(",
"a",
")",
"\n",
"factors",
",",
"invFactors",
":=",
"getBluesteinFactors",
"(",
"lx",
")",
"\n\n",
"for",
"n",
",",
"v",
":=",
"range",
"x",
"{",
"a",
"[",
"n",
"]",
"=",
"v",
"*",
"invFactors",
"[",
"n",
"]",
"\n",
"}",
"\n\n",
"b",
":=",
"make",
"(",
"[",
"]",
"complex128",
",",
"la",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"lx",
";",
"i",
"++",
"{",
"b",
"[",
"i",
"]",
"=",
"factors",
"[",
"i",
"]",
"\n\n",
"if",
"i",
"!=",
"0",
"{",
"b",
"[",
"la",
"-",
"i",
"]",
"=",
"factors",
"[",
"i",
"]",
"\n",
"}",
"\n",
"}",
"\n\n",
"r",
":=",
"Convolve",
"(",
"a",
",",
"b",
")",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"lx",
";",
"i",
"++",
"{",
"r",
"[",
"i",
"]",
"*=",
"invFactors",
"[",
"i",
"]",
"\n",
"}",
"\n\n",
"return",
"r",
"[",
":",
"lx",
"]",
"\n",
"}"
] |
// bluesteinFFT returns the FFT calculated using the Bluestein algorithm.
|
[
"bluesteinFFT",
"returns",
"the",
"FFT",
"calculated",
"using",
"the",
"Bluestein",
"algorithm",
"."
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/fft/bluestein.go#L68-L94
|
14,840 |
mjibson/go-dsp
|
wav/wav.go
|
New
|
func New(r io.Reader) (*Wav, error) {
var w Wav
header := make([]byte, 16)
if _, err := io.ReadFull(r, header[:12]); err != nil {
return nil, err
}
if string(header[0:4]) != "RIFF" {
return nil, fmt.Errorf("wav: missing RIFF")
}
if string(header[8:12]) != "WAVE" {
return nil, fmt.Errorf("wav: missing WAVE")
}
hasFmt := false
for {
if _, err := io.ReadFull(r, header[:8]); err != nil {
return nil, err
}
sz := binary.LittleEndian.Uint32(header[4:])
switch typ := string(header[:4]); typ {
case "fmt ":
if sz < 16 {
return nil, fmt.Errorf("wav: bad fmt size")
}
f := make([]byte, sz)
if _, err := io.ReadFull(r, f); err != nil {
return nil, err
}
if err := binary.Read(bytes.NewBuffer(f), binary.LittleEndian, &w.Header); err != nil {
return nil, err
}
switch w.AudioFormat {
case wavFormatPCM:
case wavFormatIEEEFloat:
default:
return nil, fmt.Errorf("wav: unknown audio format: %02x", w.AudioFormat)
}
hasFmt = true
case "data":
if !hasFmt {
return nil, fmt.Errorf("wav: unexpected fmt chunk")
}
w.Samples = int(sz) / int(w.BitsPerSample) * 8
w.Duration = time.Duration(w.Samples) * time.Second / time.Duration(w.SampleRate) / time.Duration(w.NumChannels)
w.r = io.LimitReader(r, int64(sz))
return &w, nil
default:
io.CopyN(ioutil.Discard, r, int64(sz))
}
}
}
|
go
|
func New(r io.Reader) (*Wav, error) {
var w Wav
header := make([]byte, 16)
if _, err := io.ReadFull(r, header[:12]); err != nil {
return nil, err
}
if string(header[0:4]) != "RIFF" {
return nil, fmt.Errorf("wav: missing RIFF")
}
if string(header[8:12]) != "WAVE" {
return nil, fmt.Errorf("wav: missing WAVE")
}
hasFmt := false
for {
if _, err := io.ReadFull(r, header[:8]); err != nil {
return nil, err
}
sz := binary.LittleEndian.Uint32(header[4:])
switch typ := string(header[:4]); typ {
case "fmt ":
if sz < 16 {
return nil, fmt.Errorf("wav: bad fmt size")
}
f := make([]byte, sz)
if _, err := io.ReadFull(r, f); err != nil {
return nil, err
}
if err := binary.Read(bytes.NewBuffer(f), binary.LittleEndian, &w.Header); err != nil {
return nil, err
}
switch w.AudioFormat {
case wavFormatPCM:
case wavFormatIEEEFloat:
default:
return nil, fmt.Errorf("wav: unknown audio format: %02x", w.AudioFormat)
}
hasFmt = true
case "data":
if !hasFmt {
return nil, fmt.Errorf("wav: unexpected fmt chunk")
}
w.Samples = int(sz) / int(w.BitsPerSample) * 8
w.Duration = time.Duration(w.Samples) * time.Second / time.Duration(w.SampleRate) / time.Duration(w.NumChannels)
w.r = io.LimitReader(r, int64(sz))
return &w, nil
default:
io.CopyN(ioutil.Discard, r, int64(sz))
}
}
}
|
[
"func",
"New",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"*",
"Wav",
",",
"error",
")",
"{",
"var",
"w",
"Wav",
"\n",
"header",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"16",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"header",
"[",
":",
"12",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"string",
"(",
"header",
"[",
"0",
":",
"4",
"]",
")",
"!=",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"string",
"(",
"header",
"[",
"8",
":",
"12",
"]",
")",
"!=",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"hasFmt",
":=",
"false",
"\n",
"for",
"{",
"if",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"header",
"[",
":",
"8",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"sz",
":=",
"binary",
".",
"LittleEndian",
".",
"Uint32",
"(",
"header",
"[",
"4",
":",
"]",
")",
"\n",
"switch",
"typ",
":=",
"string",
"(",
"header",
"[",
":",
"4",
"]",
")",
";",
"typ",
"{",
"case",
"\"",
"\"",
":",
"if",
"sz",
"<",
"16",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"f",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"sz",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"f",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"binary",
".",
"Read",
"(",
"bytes",
".",
"NewBuffer",
"(",
"f",
")",
",",
"binary",
".",
"LittleEndian",
",",
"&",
"w",
".",
"Header",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"switch",
"w",
".",
"AudioFormat",
"{",
"case",
"wavFormatPCM",
":",
"case",
"wavFormatIEEEFloat",
":",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"w",
".",
"AudioFormat",
")",
"\n",
"}",
"\n",
"hasFmt",
"=",
"true",
"\n",
"case",
"\"",
"\"",
":",
"if",
"!",
"hasFmt",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"w",
".",
"Samples",
"=",
"int",
"(",
"sz",
")",
"/",
"int",
"(",
"w",
".",
"BitsPerSample",
")",
"*",
"8",
"\n",
"w",
".",
"Duration",
"=",
"time",
".",
"Duration",
"(",
"w",
".",
"Samples",
")",
"*",
"time",
".",
"Second",
"/",
"time",
".",
"Duration",
"(",
"w",
".",
"SampleRate",
")",
"/",
"time",
".",
"Duration",
"(",
"w",
".",
"NumChannels",
")",
"\n",
"w",
".",
"r",
"=",
"io",
".",
"LimitReader",
"(",
"r",
",",
"int64",
"(",
"sz",
")",
")",
"\n",
"return",
"&",
"w",
",",
"nil",
"\n",
"default",
":",
"io",
".",
"CopyN",
"(",
"ioutil",
".",
"Discard",
",",
"r",
",",
"int64",
"(",
"sz",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// New reads the WAV header from r.
|
[
"New",
"reads",
"the",
"WAV",
"header",
"from",
"r",
"."
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/wav/wav.go#L60-L109
|
14,841 |
mjibson/go-dsp
|
wav/wav.go
|
ReadFloats
|
func (w *Wav) ReadFloats(n int) ([]float32, error) {
d, err := w.ReadSamples(n)
if err != nil {
return nil, err
}
var f []float32
switch d := d.(type) {
case []uint8:
f = make([]float32, len(d))
for i, v := range d {
f[i] = float32(v) / math.MaxUint8
}
case []int16:
f = make([]float32, len(d))
for i, v := range d {
f[i] = (float32(v) - math.MinInt16) / (math.MaxInt16 - math.MinInt16)
}
case []float32:
f = d
default:
return nil, fmt.Errorf("wav: unknown type: %T", d)
}
return f, nil
}
|
go
|
func (w *Wav) ReadFloats(n int) ([]float32, error) {
d, err := w.ReadSamples(n)
if err != nil {
return nil, err
}
var f []float32
switch d := d.(type) {
case []uint8:
f = make([]float32, len(d))
for i, v := range d {
f[i] = float32(v) / math.MaxUint8
}
case []int16:
f = make([]float32, len(d))
for i, v := range d {
f[i] = (float32(v) - math.MinInt16) / (math.MaxInt16 - math.MinInt16)
}
case []float32:
f = d
default:
return nil, fmt.Errorf("wav: unknown type: %T", d)
}
return f, nil
}
|
[
"func",
"(",
"w",
"*",
"Wav",
")",
"ReadFloats",
"(",
"n",
"int",
")",
"(",
"[",
"]",
"float32",
",",
"error",
")",
"{",
"d",
",",
"err",
":=",
"w",
".",
"ReadSamples",
"(",
"n",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"f",
"[",
"]",
"float32",
"\n",
"switch",
"d",
":=",
"d",
".",
"(",
"type",
")",
"{",
"case",
"[",
"]",
"uint8",
":",
"f",
"=",
"make",
"(",
"[",
"]",
"float32",
",",
"len",
"(",
"d",
")",
")",
"\n",
"for",
"i",
",",
"v",
":=",
"range",
"d",
"{",
"f",
"[",
"i",
"]",
"=",
"float32",
"(",
"v",
")",
"/",
"math",
".",
"MaxUint8",
"\n",
"}",
"\n",
"case",
"[",
"]",
"int16",
":",
"f",
"=",
"make",
"(",
"[",
"]",
"float32",
",",
"len",
"(",
"d",
")",
")",
"\n",
"for",
"i",
",",
"v",
":=",
"range",
"d",
"{",
"f",
"[",
"i",
"]",
"=",
"(",
"float32",
"(",
"v",
")",
"-",
"math",
".",
"MinInt16",
")",
"/",
"(",
"math",
".",
"MaxInt16",
"-",
"math",
".",
"MinInt16",
")",
"\n",
"}",
"\n",
"case",
"[",
"]",
"float32",
":",
"f",
"=",
"d",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"d",
")",
"\n",
"}",
"\n",
"return",
"f",
",",
"nil",
"\n",
"}"
] |
// ReadFloats is like ReadSamples, but it converts any underlying data to a
// float32.
|
[
"ReadFloats",
"is",
"like",
"ReadSamples",
"but",
"it",
"converts",
"any",
"underlying",
"data",
"to",
"a",
"float32",
"."
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/wav/wav.go#L138-L161
|
14,842 |
mjibson/go-dsp
|
dsputils/dsputils.go
|
NextPowerOf2
|
func NextPowerOf2(x int) int {
if IsPowerOf2(x) {
return x
}
return int(math.Pow(2, math.Ceil(math.Log2(float64(x)))))
}
|
go
|
func NextPowerOf2(x int) int {
if IsPowerOf2(x) {
return x
}
return int(math.Pow(2, math.Ceil(math.Log2(float64(x)))))
}
|
[
"func",
"NextPowerOf2",
"(",
"x",
"int",
")",
"int",
"{",
"if",
"IsPowerOf2",
"(",
"x",
")",
"{",
"return",
"x",
"\n",
"}",
"\n\n",
"return",
"int",
"(",
"math",
".",
"Pow",
"(",
"2",
",",
"math",
".",
"Ceil",
"(",
"math",
".",
"Log2",
"(",
"float64",
"(",
"x",
")",
")",
")",
")",
")",
"\n",
"}"
] |
// NextPowerOf2 returns the next power of 2 >= x.
|
[
"NextPowerOf2",
"returns",
"the",
"next",
"power",
"of",
"2",
">",
"=",
"x",
"."
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/dsputils/dsputils.go#L39-L45
|
14,843 |
mjibson/go-dsp
|
dsputils/dsputils.go
|
ToComplex2
|
func ToComplex2(x [][]float64) [][]complex128 {
y := make([][]complex128, len(x))
for n, v := range x {
y[n] = ToComplex(v)
}
return y
}
|
go
|
func ToComplex2(x [][]float64) [][]complex128 {
y := make([][]complex128, len(x))
for n, v := range x {
y[n] = ToComplex(v)
}
return y
}
|
[
"func",
"ToComplex2",
"(",
"x",
"[",
"]",
"[",
"]",
"float64",
")",
"[",
"]",
"[",
"]",
"complex128",
"{",
"y",
":=",
"make",
"(",
"[",
"]",
"[",
"]",
"complex128",
",",
"len",
"(",
"x",
")",
")",
"\n",
"for",
"n",
",",
"v",
":=",
"range",
"x",
"{",
"y",
"[",
"n",
"]",
"=",
"ToComplex",
"(",
"v",
")",
"\n",
"}",
"\n",
"return",
"y",
"\n",
"}"
] |
// ToComplex2 returns the complex equivalent of the real-valued matrix.
|
[
"ToComplex2",
"returns",
"the",
"complex",
"equivalent",
"of",
"the",
"real",
"-",
"valued",
"matrix",
"."
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/dsputils/dsputils.go#L77-L83
|
14,844 |
mjibson/go-dsp
|
dsputils/dsputils.go
|
Segment
|
func Segment(x []complex128, segs int, noverlap float64) [][]complex128 {
lx := len(x)
// determine step, length, and overlap
var overlap, length, step, tot int
for length = lx; length > 0; length-- {
overlap = int(float64(length) * noverlap)
tot = segs*(length-overlap) + overlap
if tot <= lx {
step = length - overlap
break
}
}
if length == 0 {
panic("too many segments")
}
r := make([][]complex128, segs)
s := 0
for n := range r {
r[n] = x[s : s+length]
s += step
}
return r
}
|
go
|
func Segment(x []complex128, segs int, noverlap float64) [][]complex128 {
lx := len(x)
// determine step, length, and overlap
var overlap, length, step, tot int
for length = lx; length > 0; length-- {
overlap = int(float64(length) * noverlap)
tot = segs*(length-overlap) + overlap
if tot <= lx {
step = length - overlap
break
}
}
if length == 0 {
panic("too many segments")
}
r := make([][]complex128, segs)
s := 0
for n := range r {
r[n] = x[s : s+length]
s += step
}
return r
}
|
[
"func",
"Segment",
"(",
"x",
"[",
"]",
"complex128",
",",
"segs",
"int",
",",
"noverlap",
"float64",
")",
"[",
"]",
"[",
"]",
"complex128",
"{",
"lx",
":=",
"len",
"(",
"x",
")",
"\n\n",
"// determine step, length, and overlap",
"var",
"overlap",
",",
"length",
",",
"step",
",",
"tot",
"int",
"\n",
"for",
"length",
"=",
"lx",
";",
"length",
">",
"0",
";",
"length",
"--",
"{",
"overlap",
"=",
"int",
"(",
"float64",
"(",
"length",
")",
"*",
"noverlap",
")",
"\n",
"tot",
"=",
"segs",
"*",
"(",
"length",
"-",
"overlap",
")",
"+",
"overlap",
"\n",
"if",
"tot",
"<=",
"lx",
"{",
"step",
"=",
"length",
"-",
"overlap",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"length",
"==",
"0",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"r",
":=",
"make",
"(",
"[",
"]",
"[",
"]",
"complex128",
",",
"segs",
")",
"\n",
"s",
":=",
"0",
"\n",
"for",
"n",
":=",
"range",
"r",
"{",
"r",
"[",
"n",
"]",
"=",
"x",
"[",
"s",
":",
"s",
"+",
"length",
"]",
"\n",
"s",
"+=",
"step",
"\n",
"}",
"\n\n",
"return",
"r",
"\n",
"}"
] |
// Segment returns segs equal-length slices that are segments of x with noverlap% of overlap.
// The returned slices are not copies of x, but slices into it.
// Trailing entries in x that connot be included in the equal-length segments are discarded.
// noverlap is a percentage, thus 0 <= noverlap <= 1, and noverlap = 0.5 is 50% overlap.
|
[
"Segment",
"returns",
"segs",
"equal",
"-",
"length",
"slices",
"that",
"are",
"segments",
"of",
"x",
"with",
"noverlap%",
"of",
"overlap",
".",
"The",
"returned",
"slices",
"are",
"not",
"copies",
"of",
"x",
"but",
"slices",
"into",
"it",
".",
"Trailing",
"entries",
"in",
"x",
"that",
"connot",
"be",
"included",
"in",
"the",
"equal",
"-",
"length",
"segments",
"are",
"discarded",
".",
"noverlap",
"is",
"a",
"percentage",
"thus",
"0",
"<",
"=",
"noverlap",
"<",
"=",
"1",
"and",
"noverlap",
"=",
"0",
".",
"5",
"is",
"50%",
"overlap",
"."
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/dsputils/dsputils.go#L89-L115
|
14,845 |
mjibson/go-dsp
|
fft/radix2.go
|
radix2FFT
|
func radix2FFT(x []complex128) []complex128 {
lx := len(x)
factors := getRadix2Factors(lx)
t := make([]complex128, lx) // temp
r := reorderData(x)
var blocks, stage, s_2 int
jobs := make(chan *fft_work, lx)
wg := sync.WaitGroup{}
num_workers := worker_pool_size
if (num_workers) == 0 {
num_workers = runtime.GOMAXPROCS(0)
}
idx_diff := lx / num_workers
if idx_diff < 2 {
idx_diff = 2
}
worker := func() {
for work := range jobs {
for nb := work.start; nb < work.end; nb += stage {
if stage != 2 {
for j := 0; j < s_2; j++ {
idx := j + nb
idx2 := idx + s_2
ridx := r[idx]
w_n := r[idx2] * factors[blocks*j]
t[idx] = ridx + w_n
t[idx2] = ridx - w_n
}
} else {
n1 := nb + 1
rn := r[nb]
rn1 := r[n1]
t[nb] = rn + rn1
t[n1] = rn - rn1
}
}
wg.Done()
}
}
for i := 0; i < num_workers; i++ {
go worker()
}
defer close(jobs)
for stage = 2; stage <= lx; stage <<= 1 {
blocks = lx / stage
s_2 = stage / 2
for start, end := 0, stage; ; {
if end-start >= idx_diff || end == lx {
wg.Add(1)
jobs <- &fft_work{start, end}
if end == lx {
break
}
start = end
}
end += stage
}
wg.Wait()
r, t = t, r
}
return r
}
|
go
|
func radix2FFT(x []complex128) []complex128 {
lx := len(x)
factors := getRadix2Factors(lx)
t := make([]complex128, lx) // temp
r := reorderData(x)
var blocks, stage, s_2 int
jobs := make(chan *fft_work, lx)
wg := sync.WaitGroup{}
num_workers := worker_pool_size
if (num_workers) == 0 {
num_workers = runtime.GOMAXPROCS(0)
}
idx_diff := lx / num_workers
if idx_diff < 2 {
idx_diff = 2
}
worker := func() {
for work := range jobs {
for nb := work.start; nb < work.end; nb += stage {
if stage != 2 {
for j := 0; j < s_2; j++ {
idx := j + nb
idx2 := idx + s_2
ridx := r[idx]
w_n := r[idx2] * factors[blocks*j]
t[idx] = ridx + w_n
t[idx2] = ridx - w_n
}
} else {
n1 := nb + 1
rn := r[nb]
rn1 := r[n1]
t[nb] = rn + rn1
t[n1] = rn - rn1
}
}
wg.Done()
}
}
for i := 0; i < num_workers; i++ {
go worker()
}
defer close(jobs)
for stage = 2; stage <= lx; stage <<= 1 {
blocks = lx / stage
s_2 = stage / 2
for start, end := 0, stage; ; {
if end-start >= idx_diff || end == lx {
wg.Add(1)
jobs <- &fft_work{start, end}
if end == lx {
break
}
start = end
}
end += stage
}
wg.Wait()
r, t = t, r
}
return r
}
|
[
"func",
"radix2FFT",
"(",
"x",
"[",
"]",
"complex128",
")",
"[",
"]",
"complex128",
"{",
"lx",
":=",
"len",
"(",
"x",
")",
"\n",
"factors",
":=",
"getRadix2Factors",
"(",
"lx",
")",
"\n\n",
"t",
":=",
"make",
"(",
"[",
"]",
"complex128",
",",
"lx",
")",
"// temp",
"\n",
"r",
":=",
"reorderData",
"(",
"x",
")",
"\n\n",
"var",
"blocks",
",",
"stage",
",",
"s_2",
"int",
"\n\n",
"jobs",
":=",
"make",
"(",
"chan",
"*",
"fft_work",
",",
"lx",
")",
"\n",
"wg",
":=",
"sync",
".",
"WaitGroup",
"{",
"}",
"\n\n",
"num_workers",
":=",
"worker_pool_size",
"\n",
"if",
"(",
"num_workers",
")",
"==",
"0",
"{",
"num_workers",
"=",
"runtime",
".",
"GOMAXPROCS",
"(",
"0",
")",
"\n",
"}",
"\n\n",
"idx_diff",
":=",
"lx",
"/",
"num_workers",
"\n",
"if",
"idx_diff",
"<",
"2",
"{",
"idx_diff",
"=",
"2",
"\n",
"}",
"\n\n",
"worker",
":=",
"func",
"(",
")",
"{",
"for",
"work",
":=",
"range",
"jobs",
"{",
"for",
"nb",
":=",
"work",
".",
"start",
";",
"nb",
"<",
"work",
".",
"end",
";",
"nb",
"+=",
"stage",
"{",
"if",
"stage",
"!=",
"2",
"{",
"for",
"j",
":=",
"0",
";",
"j",
"<",
"s_2",
";",
"j",
"++",
"{",
"idx",
":=",
"j",
"+",
"nb",
"\n",
"idx2",
":=",
"idx",
"+",
"s_2",
"\n",
"ridx",
":=",
"r",
"[",
"idx",
"]",
"\n",
"w_n",
":=",
"r",
"[",
"idx2",
"]",
"*",
"factors",
"[",
"blocks",
"*",
"j",
"]",
"\n",
"t",
"[",
"idx",
"]",
"=",
"ridx",
"+",
"w_n",
"\n",
"t",
"[",
"idx2",
"]",
"=",
"ridx",
"-",
"w_n",
"\n",
"}",
"\n",
"}",
"else",
"{",
"n1",
":=",
"nb",
"+",
"1",
"\n",
"rn",
":=",
"r",
"[",
"nb",
"]",
"\n",
"rn1",
":=",
"r",
"[",
"n1",
"]",
"\n",
"t",
"[",
"nb",
"]",
"=",
"rn",
"+",
"rn1",
"\n",
"t",
"[",
"n1",
"]",
"=",
"rn",
"-",
"rn1",
"\n",
"}",
"\n",
"}",
"\n",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"num_workers",
";",
"i",
"++",
"{",
"go",
"worker",
"(",
")",
"\n",
"}",
"\n",
"defer",
"close",
"(",
"jobs",
")",
"\n\n",
"for",
"stage",
"=",
"2",
";",
"stage",
"<=",
"lx",
";",
"stage",
"<<=",
"1",
"{",
"blocks",
"=",
"lx",
"/",
"stage",
"\n",
"s_2",
"=",
"stage",
"/",
"2",
"\n\n",
"for",
"start",
",",
"end",
":=",
"0",
",",
"stage",
";",
";",
"{",
"if",
"end",
"-",
"start",
">=",
"idx_diff",
"||",
"end",
"==",
"lx",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"jobs",
"<-",
"&",
"fft_work",
"{",
"start",
",",
"end",
"}",
"\n\n",
"if",
"end",
"==",
"lx",
"{",
"break",
"\n",
"}",
"\n\n",
"start",
"=",
"end",
"\n",
"}",
"\n\n",
"end",
"+=",
"stage",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"r",
",",
"t",
"=",
"t",
",",
"r",
"\n",
"}",
"\n\n",
"return",
"r",
"\n",
"}"
] |
// radix2FFT returns the FFT calculated using the radix-2 DIT Cooley-Tukey algorithm.
|
[
"radix2FFT",
"returns",
"the",
"FFT",
"calculated",
"using",
"the",
"radix",
"-",
"2",
"DIT",
"Cooley",
"-",
"Tukey",
"algorithm",
"."
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/fft/radix2.go#L80-L154
|
14,846 |
mjibson/go-dsp
|
fft/radix2.go
|
reorderData
|
func reorderData(x []complex128) []complex128 {
lx := uint(len(x))
r := make([]complex128, lx)
s := log2(lx)
var n uint
for ; n < lx; n++ {
r[reverseBits(n, s)] = x[n]
}
return r
}
|
go
|
func reorderData(x []complex128) []complex128 {
lx := uint(len(x))
r := make([]complex128, lx)
s := log2(lx)
var n uint
for ; n < lx; n++ {
r[reverseBits(n, s)] = x[n]
}
return r
}
|
[
"func",
"reorderData",
"(",
"x",
"[",
"]",
"complex128",
")",
"[",
"]",
"complex128",
"{",
"lx",
":=",
"uint",
"(",
"len",
"(",
"x",
")",
")",
"\n",
"r",
":=",
"make",
"(",
"[",
"]",
"complex128",
",",
"lx",
")",
"\n",
"s",
":=",
"log2",
"(",
"lx",
")",
"\n\n",
"var",
"n",
"uint",
"\n",
"for",
";",
"n",
"<",
"lx",
";",
"n",
"++",
"{",
"r",
"[",
"reverseBits",
"(",
"n",
",",
"s",
")",
"]",
"=",
"x",
"[",
"n",
"]",
"\n",
"}",
"\n\n",
"return",
"r",
"\n",
"}"
] |
// reorderData returns a copy of x reordered for the DFT.
|
[
"reorderData",
"returns",
"a",
"copy",
"of",
"x",
"reordered",
"for",
"the",
"DFT",
"."
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/fft/radix2.go#L157-L168
|
14,847 |
mjibson/go-dsp
|
window/window.go
|
Apply
|
func Apply(x []float64, windowFunction func(int) []float64) {
for i, w := range windowFunction(len(x)) {
x[i] *= w
}
}
|
go
|
func Apply(x []float64, windowFunction func(int) []float64) {
for i, w := range windowFunction(len(x)) {
x[i] *= w
}
}
|
[
"func",
"Apply",
"(",
"x",
"[",
"]",
"float64",
",",
"windowFunction",
"func",
"(",
"int",
")",
"[",
"]",
"float64",
")",
"{",
"for",
"i",
",",
"w",
":=",
"range",
"windowFunction",
"(",
"len",
"(",
"x",
")",
")",
"{",
"x",
"[",
"i",
"]",
"*=",
"w",
"\n",
"}",
"\n",
"}"
] |
// Apply applies the window windowFunction to x.
|
[
"Apply",
"applies",
"the",
"window",
"windowFunction",
"to",
"x",
"."
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/window/window.go#L25-L29
|
14,848 |
mjibson/go-dsp
|
dsputils/compare.go
|
PrettyClose
|
func PrettyClose(a, b []float64) bool {
if len(a) != len(b) {
return false
}
for i, c := range a {
if !Float64Equal(c, b[i]) {
return false
}
}
return true
}
|
go
|
func PrettyClose(a, b []float64) bool {
if len(a) != len(b) {
return false
}
for i, c := range a {
if !Float64Equal(c, b[i]) {
return false
}
}
return true
}
|
[
"func",
"PrettyClose",
"(",
"a",
",",
"b",
"[",
"]",
"float64",
")",
"bool",
"{",
"if",
"len",
"(",
"a",
")",
"!=",
"len",
"(",
"b",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"for",
"i",
",",
"c",
":=",
"range",
"a",
"{",
"if",
"!",
"Float64Equal",
"(",
"c",
",",
"b",
"[",
"i",
"]",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// PrettyClose returns true if the slices a and b are very close, else false.
|
[
"PrettyClose",
"returns",
"true",
"if",
"the",
"slices",
"a",
"and",
"b",
"are",
"very",
"close",
"else",
"false",
"."
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/dsputils/compare.go#L28-L39
|
14,849 |
mjibson/go-dsp
|
dsputils/compare.go
|
PrettyCloseC
|
func PrettyCloseC(a, b []complex128) bool {
if len(a) != len(b) {
return false
}
for i, c := range a {
if !ComplexEqual(c, b[i]) {
return false
}
}
return true
}
|
go
|
func PrettyCloseC(a, b []complex128) bool {
if len(a) != len(b) {
return false
}
for i, c := range a {
if !ComplexEqual(c, b[i]) {
return false
}
}
return true
}
|
[
"func",
"PrettyCloseC",
"(",
"a",
",",
"b",
"[",
"]",
"complex128",
")",
"bool",
"{",
"if",
"len",
"(",
"a",
")",
"!=",
"len",
"(",
"b",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"for",
"i",
",",
"c",
":=",
"range",
"a",
"{",
"if",
"!",
"ComplexEqual",
"(",
"c",
",",
"b",
"[",
"i",
"]",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// PrettyCloseC returns true if the slices a and b are very close, else false.
|
[
"PrettyCloseC",
"returns",
"true",
"if",
"the",
"slices",
"a",
"and",
"b",
"are",
"very",
"close",
"else",
"false",
"."
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/dsputils/compare.go#L42-L53
|
14,850 |
mjibson/go-dsp
|
dsputils/compare.go
|
ComplexEqual
|
func ComplexEqual(a, b complex128) bool {
r_a := real(a)
r_b := real(b)
i_a := imag(a)
i_b := imag(b)
return Float64Equal(r_a, r_b) && Float64Equal(i_a, i_b)
}
|
go
|
func ComplexEqual(a, b complex128) bool {
r_a := real(a)
r_b := real(b)
i_a := imag(a)
i_b := imag(b)
return Float64Equal(r_a, r_b) && Float64Equal(i_a, i_b)
}
|
[
"func",
"ComplexEqual",
"(",
"a",
",",
"b",
"complex128",
")",
"bool",
"{",
"r_a",
":=",
"real",
"(",
"a",
")",
"\n",
"r_b",
":=",
"real",
"(",
"b",
")",
"\n",
"i_a",
":=",
"imag",
"(",
"a",
")",
"\n",
"i_b",
":=",
"imag",
"(",
"b",
")",
"\n\n",
"return",
"Float64Equal",
"(",
"r_a",
",",
"r_b",
")",
"&&",
"Float64Equal",
"(",
"i_a",
",",
"i_b",
")",
"\n",
"}"
] |
// ComplexEqual returns true if a and b are very close, else false.
|
[
"ComplexEqual",
"returns",
"true",
"if",
"a",
"and",
"b",
"are",
"very",
"close",
"else",
"false",
"."
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/dsputils/compare.go#L84-L91
|
14,851 |
mjibson/go-dsp
|
dsputils/compare.go
|
Float64Equal
|
func Float64Equal(a, b float64) bool {
return math.Abs(a-b) <= closeFactor || math.Abs(1-a/b) <= closeFactor
}
|
go
|
func Float64Equal(a, b float64) bool {
return math.Abs(a-b) <= closeFactor || math.Abs(1-a/b) <= closeFactor
}
|
[
"func",
"Float64Equal",
"(",
"a",
",",
"b",
"float64",
")",
"bool",
"{",
"return",
"math",
".",
"Abs",
"(",
"a",
"-",
"b",
")",
"<=",
"closeFactor",
"||",
"math",
".",
"Abs",
"(",
"1",
"-",
"a",
"/",
"b",
")",
"<=",
"closeFactor",
"\n",
"}"
] |
// Float64Equal returns true if a and b are very close, else false.
|
[
"Float64Equal",
"returns",
"true",
"if",
"a",
"and",
"b",
"are",
"very",
"close",
"else",
"false",
"."
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/dsputils/compare.go#L94-L96
|
14,852 |
mjibson/go-dsp
|
dsputils/matrix.go
|
MakeMatrix2
|
func MakeMatrix2(x [][]complex128) *Matrix {
dims := []int{len(x), len(x[0])}
r := make([]complex128, dims[0]*dims[1])
for n, v := range x {
if len(v) != dims[1] {
panic("ragged array")
}
copy(r[n*dims[1]:(n+1)*dims[1]], v)
}
return MakeMatrix(r, dims)
}
|
go
|
func MakeMatrix2(x [][]complex128) *Matrix {
dims := []int{len(x), len(x[0])}
r := make([]complex128, dims[0]*dims[1])
for n, v := range x {
if len(v) != dims[1] {
panic("ragged array")
}
copy(r[n*dims[1]:(n+1)*dims[1]], v)
}
return MakeMatrix(r, dims)
}
|
[
"func",
"MakeMatrix2",
"(",
"x",
"[",
"]",
"[",
"]",
"complex128",
")",
"*",
"Matrix",
"{",
"dims",
":=",
"[",
"]",
"int",
"{",
"len",
"(",
"x",
")",
",",
"len",
"(",
"x",
"[",
"0",
"]",
")",
"}",
"\n",
"r",
":=",
"make",
"(",
"[",
"]",
"complex128",
",",
"dims",
"[",
"0",
"]",
"*",
"dims",
"[",
"1",
"]",
")",
"\n",
"for",
"n",
",",
"v",
":=",
"range",
"x",
"{",
"if",
"len",
"(",
"v",
")",
"!=",
"dims",
"[",
"1",
"]",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"copy",
"(",
"r",
"[",
"n",
"*",
"dims",
"[",
"1",
"]",
":",
"(",
"n",
"+",
"1",
")",
"*",
"dims",
"[",
"1",
"]",
"]",
",",
"v",
")",
"\n",
"}",
"\n\n",
"return",
"MakeMatrix",
"(",
"r",
",",
"dims",
")",
"\n",
"}"
] |
// MakeMatrix2 is a helper function to convert a 2-d array to a matrix.
|
[
"MakeMatrix2",
"is",
"a",
"helper",
"function",
"to",
"convert",
"a",
"2",
"-",
"d",
"array",
"to",
"a",
"matrix",
"."
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/dsputils/matrix.go#L60-L72
|
14,853 |
mjibson/go-dsp
|
dsputils/matrix.go
|
Copy
|
func (m *Matrix) Copy() *Matrix {
r := &Matrix{m.list, m.dims, m.offsets}
r.list = make([]complex128, len(m.list))
copy(r.list, m.list)
return r
}
|
go
|
func (m *Matrix) Copy() *Matrix {
r := &Matrix{m.list, m.dims, m.offsets}
r.list = make([]complex128, len(m.list))
copy(r.list, m.list)
return r
}
|
[
"func",
"(",
"m",
"*",
"Matrix",
")",
"Copy",
"(",
")",
"*",
"Matrix",
"{",
"r",
":=",
"&",
"Matrix",
"{",
"m",
".",
"list",
",",
"m",
".",
"dims",
",",
"m",
".",
"offsets",
"}",
"\n",
"r",
".",
"list",
"=",
"make",
"(",
"[",
"]",
"complex128",
",",
"len",
"(",
"m",
".",
"list",
")",
")",
"\n",
"copy",
"(",
"r",
".",
"list",
",",
"m",
".",
"list",
")",
"\n",
"return",
"r",
"\n",
"}"
] |
// Copy returns a new copy of m.
|
[
"Copy",
"returns",
"a",
"new",
"copy",
"of",
"m",
"."
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/dsputils/matrix.go#L75-L80
|
14,854 |
mjibson/go-dsp
|
dsputils/matrix.go
|
MakeEmptyMatrix
|
func MakeEmptyMatrix(dims []int) *Matrix {
x := 1
for _, v := range dims {
x *= v
}
return MakeMatrix(make([]complex128, x), dims)
}
|
go
|
func MakeEmptyMatrix(dims []int) *Matrix {
x := 1
for _, v := range dims {
x *= v
}
return MakeMatrix(make([]complex128, x), dims)
}
|
[
"func",
"MakeEmptyMatrix",
"(",
"dims",
"[",
"]",
"int",
")",
"*",
"Matrix",
"{",
"x",
":=",
"1",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"dims",
"{",
"x",
"*=",
"v",
"\n",
"}",
"\n\n",
"return",
"MakeMatrix",
"(",
"make",
"(",
"[",
"]",
"complex128",
",",
"x",
")",
",",
"dims",
")",
"\n",
"}"
] |
// MakeEmptyMatrix creates an empty Matrix with given dimensions.
|
[
"MakeEmptyMatrix",
"creates",
"an",
"empty",
"Matrix",
"with",
"given",
"dimensions",
"."
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/dsputils/matrix.go#L83-L90
|
14,855 |
mjibson/go-dsp
|
dsputils/matrix.go
|
offset
|
func (s *Matrix) offset(dims []int) int {
if len(dims) != len(s.dims) {
panic("incorrect dimensions")
}
i := 0
for n, v := range dims {
if v > s.dims[n] {
panic("incorrect dimensions")
}
i += v * s.offsets[n]
}
return i
}
|
go
|
func (s *Matrix) offset(dims []int) int {
if len(dims) != len(s.dims) {
panic("incorrect dimensions")
}
i := 0
for n, v := range dims {
if v > s.dims[n] {
panic("incorrect dimensions")
}
i += v * s.offsets[n]
}
return i
}
|
[
"func",
"(",
"s",
"*",
"Matrix",
")",
"offset",
"(",
"dims",
"[",
"]",
"int",
")",
"int",
"{",
"if",
"len",
"(",
"dims",
")",
"!=",
"len",
"(",
"s",
".",
"dims",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"i",
":=",
"0",
"\n",
"for",
"n",
",",
"v",
":=",
"range",
"dims",
"{",
"if",
"v",
">",
"s",
".",
"dims",
"[",
"n",
"]",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"i",
"+=",
"v",
"*",
"s",
".",
"offsets",
"[",
"n",
"]",
"\n",
"}",
"\n\n",
"return",
"i",
"\n",
"}"
] |
// offset returns the index in the one-dimensional array
|
[
"offset",
"returns",
"the",
"index",
"in",
"the",
"one",
"-",
"dimensional",
"array"
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/dsputils/matrix.go#L93-L108
|
14,856 |
mjibson/go-dsp
|
dsputils/matrix.go
|
Dimensions
|
func (m *Matrix) Dimensions() []int {
r := make([]int, len(m.dims))
copy(r, m.dims)
return r
}
|
go
|
func (m *Matrix) Dimensions() []int {
r := make([]int, len(m.dims))
copy(r, m.dims)
return r
}
|
[
"func",
"(",
"m",
"*",
"Matrix",
")",
"Dimensions",
"(",
")",
"[",
"]",
"int",
"{",
"r",
":=",
"make",
"(",
"[",
"]",
"int",
",",
"len",
"(",
"m",
".",
"dims",
")",
")",
"\n",
"copy",
"(",
"r",
",",
"m",
".",
"dims",
")",
"\n",
"return",
"r",
"\n",
"}"
] |
// Dimensions returns the dimension array of the Matrix.
|
[
"Dimensions",
"returns",
"the",
"dimension",
"array",
"of",
"the",
"Matrix",
"."
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/dsputils/matrix.go#L144-L148
|
14,857 |
mjibson/go-dsp
|
dsputils/matrix.go
|
To2D
|
func (m *Matrix) To2D() [][]complex128 {
if len(m.dims) != 2 {
panic("can only convert 2-D Matrixes")
}
r := make([][]complex128, m.dims[0])
for i := 0; i < m.dims[0]; i++ {
r[i] = make([]complex128, m.dims[1])
copy(r[i], m.list[i*m.dims[1]:(i+1)*m.dims[1]])
}
return r
}
|
go
|
func (m *Matrix) To2D() [][]complex128 {
if len(m.dims) != 2 {
panic("can only convert 2-D Matrixes")
}
r := make([][]complex128, m.dims[0])
for i := 0; i < m.dims[0]; i++ {
r[i] = make([]complex128, m.dims[1])
copy(r[i], m.list[i*m.dims[1]:(i+1)*m.dims[1]])
}
return r
}
|
[
"func",
"(",
"m",
"*",
"Matrix",
")",
"To2D",
"(",
")",
"[",
"]",
"[",
"]",
"complex128",
"{",
"if",
"len",
"(",
"m",
".",
"dims",
")",
"!=",
"2",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"r",
":=",
"make",
"(",
"[",
"]",
"[",
"]",
"complex128",
",",
"m",
".",
"dims",
"[",
"0",
"]",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"m",
".",
"dims",
"[",
"0",
"]",
";",
"i",
"++",
"{",
"r",
"[",
"i",
"]",
"=",
"make",
"(",
"[",
"]",
"complex128",
",",
"m",
".",
"dims",
"[",
"1",
"]",
")",
"\n",
"copy",
"(",
"r",
"[",
"i",
"]",
",",
"m",
".",
"list",
"[",
"i",
"*",
"m",
".",
"dims",
"[",
"1",
"]",
":",
"(",
"i",
"+",
"1",
")",
"*",
"m",
".",
"dims",
"[",
"1",
"]",
"]",
")",
"\n",
"}",
"\n\n",
"return",
"r",
"\n",
"}"
] |
// To2D returns the 2-D array equivalent of the Matrix.
// Only works on Matrixes of 2 dimensions.
|
[
"To2D",
"returns",
"the",
"2",
"-",
"D",
"array",
"equivalent",
"of",
"the",
"Matrix",
".",
"Only",
"works",
"on",
"Matrixes",
"of",
"2",
"dimensions",
"."
] |
11479a337f1259210b7c8f93f7bf2b0cc87b066e
|
https://github.com/mjibson/go-dsp/blob/11479a337f1259210b7c8f93f7bf2b0cc87b066e/dsputils/matrix.go#L191-L203
|
14,858 |
go-chi/jwtauth
|
jwtauth.go
|
Authenticator
|
func Authenticator(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, _, err := FromContext(r.Context())
if err != nil {
http.Error(w, http.StatusText(401), 401)
return
}
if token == nil || !token.Valid {
http.Error(w, http.StatusText(401), 401)
return
}
// Token is authenticated, pass it through
next.ServeHTTP(w, r)
})
}
|
go
|
func Authenticator(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, _, err := FromContext(r.Context())
if err != nil {
http.Error(w, http.StatusText(401), 401)
return
}
if token == nil || !token.Valid {
http.Error(w, http.StatusText(401), 401)
return
}
// Token is authenticated, pass it through
next.ServeHTTP(w, r)
})
}
|
[
"func",
"Authenticator",
"(",
"next",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"token",
",",
"_",
",",
"err",
":=",
"FromContext",
"(",
"r",
".",
"Context",
"(",
")",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"http",
".",
"StatusText",
"(",
"401",
")",
",",
"401",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"token",
"==",
"nil",
"||",
"!",
"token",
".",
"Valid",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"http",
".",
"StatusText",
"(",
"401",
")",
",",
"401",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Token is authenticated, pass it through",
"next",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// Authenticator is a default authentication middleware to enforce access from the
// Verifier middleware request context values. The Authenticator sends a 401 Unauthorized
// response for any unverified tokens and passes the good ones through. It's just fine
// until you decide to write something similar and customize your client response.
|
[
"Authenticator",
"is",
"a",
"default",
"authentication",
"middleware",
"to",
"enforce",
"access",
"from",
"the",
"Verifier",
"middleware",
"request",
"context",
"values",
".",
"The",
"Authenticator",
"sends",
"a",
"401",
"Unauthorized",
"response",
"for",
"any",
"unverified",
"tokens",
"and",
"passes",
"the",
"good",
"ones",
"through",
".",
"It",
"s",
"just",
"fine",
"until",
"you",
"decide",
"to",
"write",
"something",
"similar",
"and",
"customize",
"your",
"client",
"response",
"."
] |
aa727a6feb92b4f5820097b56bf2acc4514f77e9
|
https://github.com/go-chi/jwtauth/blob/aa727a6feb92b4f5820097b56bf2acc4514f77e9/jwtauth.go#L162-L179
|
14,859 |
go-chi/jwtauth
|
jwtauth.go
|
TokenFromCookie
|
func TokenFromCookie(r *http.Request) string {
cookie, err := r.Cookie("jwt")
if err != nil {
return ""
}
return cookie.Value
}
|
go
|
func TokenFromCookie(r *http.Request) string {
cookie, err := r.Cookie("jwt")
if err != nil {
return ""
}
return cookie.Value
}
|
[
"func",
"TokenFromCookie",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"cookie",
",",
"err",
":=",
"r",
".",
"Cookie",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"cookie",
".",
"Value",
"\n",
"}"
] |
// TokenFromCookie tries to retreive the token string from a cookie named
// "jwt".
|
[
"TokenFromCookie",
"tries",
"to",
"retreive",
"the",
"token",
"string",
"from",
"a",
"cookie",
"named",
"jwt",
"."
] |
aa727a6feb92b4f5820097b56bf2acc4514f77e9
|
https://github.com/go-chi/jwtauth/blob/aa727a6feb92b4f5820097b56bf2acc4514f77e9/jwtauth.go#L243-L249
|
14,860 |
digota/digota
|
locker/handlers/zookeeper/zookeeper.go
|
NewLocker
|
func NewLocker(lockerConfig config.Locker) (*lock, error) {
c, _, err := zk.Connect(lockerConfig.Address, time.Millisecond*100)
if err != nil {
return nil, err
}
return &lock{c}, nil
}
|
go
|
func NewLocker(lockerConfig config.Locker) (*lock, error) {
c, _, err := zk.Connect(lockerConfig.Address, time.Millisecond*100)
if err != nil {
return nil, err
}
return &lock{c}, nil
}
|
[
"func",
"NewLocker",
"(",
"lockerConfig",
"config",
".",
"Locker",
")",
"(",
"*",
"lock",
",",
"error",
")",
"{",
"c",
",",
"_",
",",
"err",
":=",
"zk",
".",
"Connect",
"(",
"lockerConfig",
".",
"Address",
",",
"time",
".",
"Millisecond",
"*",
"100",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"lock",
"{",
"c",
"}",
",",
"nil",
"\n",
"}"
] |
// NewLocker return new lock
|
[
"NewLocker",
"return",
"new",
"lock"
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/locker/handlers/zookeeper/zookeeper.go#L43-L49
|
14,861 |
digota/digota
|
locker/handlers/redis/redis.go
|
NewLocker
|
func NewLocker(lockerConfig config.Locker) (*locker, error) {
if len(lockerConfig.Address) < 1 {
return nil, errors.New("No redis address provided")
}
p := newPool(lockerConfig.Address[0], "")
return &locker{p}, nil
}
|
go
|
func NewLocker(lockerConfig config.Locker) (*locker, error) {
if len(lockerConfig.Address) < 1 {
return nil, errors.New("No redis address provided")
}
p := newPool(lockerConfig.Address[0], "")
return &locker{p}, nil
}
|
[
"func",
"NewLocker",
"(",
"lockerConfig",
"config",
".",
"Locker",
")",
"(",
"*",
"locker",
",",
"error",
")",
"{",
"if",
"len",
"(",
"lockerConfig",
".",
"Address",
")",
"<",
"1",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"p",
":=",
"newPool",
"(",
"lockerConfig",
".",
"Address",
"[",
"0",
"]",
",",
"\"",
"\"",
")",
"\n",
"return",
"&",
"locker",
"{",
"p",
"}",
",",
"nil",
"\n",
"}"
] |
// NewLocker return new redis based lock
|
[
"NewLocker",
"return",
"new",
"redis",
"based",
"lock"
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/locker/handlers/redis/redis.go#L57-L63
|
14,862 |
digota/digota
|
product/product.go
|
ReadMethods
|
func ReadMethods() []*regexp.Regexp {
return []*regexp.Regexp{
regexp.MustCompile(baseMethod + "Get"),
regexp.MustCompile(baseMethod + "List"),
}
}
|
go
|
func ReadMethods() []*regexp.Regexp {
return []*regexp.Regexp{
regexp.MustCompile(baseMethod + "Get"),
regexp.MustCompile(baseMethod + "List"),
}
}
|
[
"func",
"ReadMethods",
"(",
")",
"[",
"]",
"*",
"regexp",
".",
"Regexp",
"{",
"return",
"[",
"]",
"*",
"regexp",
".",
"Regexp",
"{",
"regexp",
".",
"MustCompile",
"(",
"baseMethod",
"+",
"\"",
"\"",
")",
",",
"regexp",
".",
"MustCompile",
"(",
"baseMethod",
"+",
"\"",
"\"",
")",
",",
"}",
"\n",
"}"
] |
// ReadMethods returns regexp slice of readable methods, mostly used by the acl
|
[
"ReadMethods",
"returns",
"regexp",
"slice",
"of",
"readable",
"methods",
"mostly",
"used",
"by",
"the",
"acl"
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/product/product.go#L62-L67
|
14,863 |
digota/digota
|
payment/service/providers/stripe/stripe.go
|
NewProvider
|
func NewProvider(paymentConfig *config.PaymentProvider) (*provider, error) {
stripe.Key = paymentConfig.Secret
stripe.Logger = logrus.New()
return &provider{}, nil
}
|
go
|
func NewProvider(paymentConfig *config.PaymentProvider) (*provider, error) {
stripe.Key = paymentConfig.Secret
stripe.Logger = logrus.New()
return &provider{}, nil
}
|
[
"func",
"NewProvider",
"(",
"paymentConfig",
"*",
"config",
".",
"PaymentProvider",
")",
"(",
"*",
"provider",
",",
"error",
")",
"{",
"stripe",
".",
"Key",
"=",
"paymentConfig",
".",
"Secret",
"\n",
"stripe",
".",
"Logger",
"=",
"logrus",
".",
"New",
"(",
")",
"\n",
"return",
"&",
"provider",
"{",
"}",
",",
"nil",
"\n",
"}"
] |
// NewProvider creates and prepare the stripe provider
|
[
"NewProvider",
"creates",
"and",
"prepare",
"the",
"stripe",
"provider"
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/payment/service/providers/stripe/stripe.go#L41-L45
|
14,864 |
digota/digota
|
acl/acl.go
|
getAccessMap
|
func getAccessMap(c *client.Client) [][]*regexp.Regexp {
var m [][]*regexp.Regexp
// append public scope
m = append(m, accessMap[client.PublicScope]...)
if c == nil {
return m
}
for _, v := range c.Scopes {
if methods, ok := accessMap[v]; ok {
m = append(m, methods...)
}
}
return m
}
|
go
|
func getAccessMap(c *client.Client) [][]*regexp.Regexp {
var m [][]*regexp.Regexp
// append public scope
m = append(m, accessMap[client.PublicScope]...)
if c == nil {
return m
}
for _, v := range c.Scopes {
if methods, ok := accessMap[v]; ok {
m = append(m, methods...)
}
}
return m
}
|
[
"func",
"getAccessMap",
"(",
"c",
"*",
"client",
".",
"Client",
")",
"[",
"]",
"[",
"]",
"*",
"regexp",
".",
"Regexp",
"{",
"var",
"m",
"[",
"]",
"[",
"]",
"*",
"regexp",
".",
"Regexp",
"\n",
"// append public scope",
"m",
"=",
"append",
"(",
"m",
",",
"accessMap",
"[",
"client",
".",
"PublicScope",
"]",
"...",
")",
"\n",
"if",
"c",
"==",
"nil",
"{",
"return",
"m",
"\n",
"}",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"c",
".",
"Scopes",
"{",
"if",
"methods",
",",
"ok",
":=",
"accessMap",
"[",
"v",
"]",
";",
"ok",
"{",
"m",
"=",
"append",
"(",
"m",
",",
"methods",
"...",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"m",
"\n",
"}"
] |
// getAccessMap return access map for specific client
|
[
"getAccessMap",
"return",
"access",
"map",
"for",
"specific",
"client"
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/acl/acl.go#L76-L89
|
14,865 |
digota/digota
|
acl/acl.go
|
CanAccessMethod
|
func CanAccessMethod(ctx context.Context, fullMethod string) bool {
u, _ := client.FromContext(ctx)
for _, v := range getAccessMap(u) {
for _, r := range v {
if r.MatchString(fullMethod) {
return true
}
}
}
return false
}
|
go
|
func CanAccessMethod(ctx context.Context, fullMethod string) bool {
u, _ := client.FromContext(ctx)
for _, v := range getAccessMap(u) {
for _, r := range v {
if r.MatchString(fullMethod) {
return true
}
}
}
return false
}
|
[
"func",
"CanAccessMethod",
"(",
"ctx",
"context",
".",
"Context",
",",
"fullMethod",
"string",
")",
"bool",
"{",
"u",
",",
"_",
":=",
"client",
".",
"FromContext",
"(",
"ctx",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"getAccessMap",
"(",
"u",
")",
"{",
"for",
"_",
",",
"r",
":=",
"range",
"v",
"{",
"if",
"r",
".",
"MatchString",
"(",
"fullMethod",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// CanAccessMethod check if user can access fullMethod by getting its accessMap
|
[
"CanAccessMethod",
"check",
"if",
"user",
"can",
"access",
"fullMethod",
"by",
"getting",
"its",
"accessMap"
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/acl/acl.go#L92-L102
|
14,866 |
digota/digota
|
middleware/recovery/recovery.go
|
RecoveryHandlerFunc
|
func RecoveryHandlerFunc(p interface{}) (err error) {
// print stack to stderr
debug.PrintStack()
// return grpc error
switch x := p.(type) {
case *logrus.Entry:
return status.Errorf(codes.Internal, "%s", x.Message)
}
return status.Errorf(codes.Internal, "%s", p)
}
|
go
|
func RecoveryHandlerFunc(p interface{}) (err error) {
// print stack to stderr
debug.PrintStack()
// return grpc error
switch x := p.(type) {
case *logrus.Entry:
return status.Errorf(codes.Internal, "%s", x.Message)
}
return status.Errorf(codes.Internal, "%s", p)
}
|
[
"func",
"RecoveryHandlerFunc",
"(",
"p",
"interface",
"{",
"}",
")",
"(",
"err",
"error",
")",
"{",
"// print stack to stderr",
"debug",
".",
"PrintStack",
"(",
")",
"\n",
"// return grpc error",
"switch",
"x",
":=",
"p",
".",
"(",
"type",
")",
"{",
"case",
"*",
"logrus",
".",
"Entry",
":",
"return",
"status",
".",
"Errorf",
"(",
"codes",
".",
"Internal",
",",
"\"",
"\"",
",",
"x",
".",
"Message",
")",
"\n",
"}",
"\n\n",
"return",
"status",
".",
"Errorf",
"(",
"codes",
".",
"Internal",
",",
"\"",
"\"",
",",
"p",
")",
"\n",
"}"
] |
// RecoveryHandlerFunc outputs the stack and the error
// returns valid grpc error
|
[
"RecoveryHandlerFunc",
"outputs",
"the",
"stack",
"and",
"the",
"error",
"returns",
"valid",
"grpc",
"error"
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/middleware/recovery/recovery.go#L34-L45
|
14,867 |
digota/digota
|
util/util.go
|
Retry
|
func Retry(callback func() error) (err error) {
for i := 0; ; i++ {
if err = callback(); err == nil {
return
}
if i >= (defaultRetryAttempts - 1) {
break
}
time.Sleep(defaultRetrySleep)
log.Error("retrying after error:", err)
}
return fmt.Errorf("after %d attempts, last error: %s", defaultRetryAttempts, err)
}
|
go
|
func Retry(callback func() error) (err error) {
for i := 0; ; i++ {
if err = callback(); err == nil {
return
}
if i >= (defaultRetryAttempts - 1) {
break
}
time.Sleep(defaultRetrySleep)
log.Error("retrying after error:", err)
}
return fmt.Errorf("after %d attempts, last error: %s", defaultRetryAttempts, err)
}
|
[
"func",
"Retry",
"(",
"callback",
"func",
"(",
")",
"error",
")",
"(",
"err",
"error",
")",
"{",
"for",
"i",
":=",
"0",
";",
";",
"i",
"++",
"{",
"if",
"err",
"=",
"callback",
"(",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"i",
">=",
"(",
"defaultRetryAttempts",
"-",
"1",
")",
"{",
"break",
"\n",
"}",
"\n",
"time",
".",
"Sleep",
"(",
"defaultRetrySleep",
")",
"\n",
"log",
".",
"Error",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"defaultRetryAttempts",
",",
"err",
")",
"\n",
"}"
] |
// Retry function for default retry attempts
|
[
"Retry",
"function",
"for",
"default",
"retry",
"attempts"
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/util/util.go#L41-L53
|
14,868 |
digota/digota
|
storage/handlers/mongo/mongo.go
|
NewHandler
|
func NewHandler(s config.Storage) *handler {
if s.Database == "" {
s.Database = object.DefaultDatabase
}
h := &handler{
dailInfo: &mgo.DialInfo{
PoolLimit: 4096,
Timeout: time.Second,
FailFast: true,
Username: s.Username,
Password: s.Password,
Addrs: s.Address,
Database: s.Database,
},
database: s.Database,
}
return h
}
|
go
|
func NewHandler(s config.Storage) *handler {
if s.Database == "" {
s.Database = object.DefaultDatabase
}
h := &handler{
dailInfo: &mgo.DialInfo{
PoolLimit: 4096,
Timeout: time.Second,
FailFast: true,
Username: s.Username,
Password: s.Password,
Addrs: s.Address,
Database: s.Database,
},
database: s.Database,
}
return h
}
|
[
"func",
"NewHandler",
"(",
"s",
"config",
".",
"Storage",
")",
"*",
"handler",
"{",
"if",
"s",
".",
"Database",
"==",
"\"",
"\"",
"{",
"s",
".",
"Database",
"=",
"object",
".",
"DefaultDatabase",
"\n",
"}",
"\n",
"h",
":=",
"&",
"handler",
"{",
"dailInfo",
":",
"&",
"mgo",
".",
"DialInfo",
"{",
"PoolLimit",
":",
"4096",
",",
"Timeout",
":",
"time",
".",
"Second",
",",
"FailFast",
":",
"true",
",",
"Username",
":",
"s",
".",
"Username",
",",
"Password",
":",
"s",
".",
"Password",
",",
"Addrs",
":",
"s",
".",
"Address",
",",
"Database",
":",
"s",
".",
"Database",
",",
"}",
",",
"database",
":",
"s",
".",
"Database",
",",
"}",
"\n",
"return",
"h",
"\n",
"}"
] |
// NewHandler create new mongo handler
|
[
"NewHandler",
"create",
"new",
"mongo",
"handler"
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/storage/handlers/mongo/mongo.go#L46-L63
|
14,869 |
digota/digota
|
sdk/sdk.go
|
NewClient
|
func NewClient(addr string, opt *ClientOpt) (*grpc.ClientConn, error) {
if opt == nil {
return nil, fmt.Errorf("Empty ClientOpt")
}
// Load key pair
certificate, err := tls.LoadX509KeyPair(opt.Crt, opt.Key)
if err != nil {
return nil, err
}
tlsConf := &tls.Config{
ServerName: opt.ServerName,
Certificates: []tls.Certificate{certificate},
InsecureSkipVerify: opt.InsecureSkipVerify,
}
// Mutual handshake with private ca
if opt.CaCrt != "" {
certPool := x509.NewCertPool()
bs, err := ioutil.ReadFile(opt.CaCrt)
if err != nil {
return nil, err
}
ok := certPool.AppendCertsFromPEM(bs)
if !ok {
return nil, fmt.Errorf("failed to append certs")
}
tlsConf.InsecureSkipVerify = false
tlsConf.RootCAs = certPool
}
dailOpts := []grpc.DialOption{
grpc.WithTransportCredentials(credentials.NewTLS(tlsConf)),
}
if opt.WithBlock {
dailOpts = append(dailOpts, grpc.WithBlock(), grpc.WithTimeout(5*time.Second))
}
// Dail and return connection
conn, err := grpc.Dial(addr, dailOpts...)
if err != nil {
return nil, err
}
return conn, nil
}
|
go
|
func NewClient(addr string, opt *ClientOpt) (*grpc.ClientConn, error) {
if opt == nil {
return nil, fmt.Errorf("Empty ClientOpt")
}
// Load key pair
certificate, err := tls.LoadX509KeyPair(opt.Crt, opt.Key)
if err != nil {
return nil, err
}
tlsConf := &tls.Config{
ServerName: opt.ServerName,
Certificates: []tls.Certificate{certificate},
InsecureSkipVerify: opt.InsecureSkipVerify,
}
// Mutual handshake with private ca
if opt.CaCrt != "" {
certPool := x509.NewCertPool()
bs, err := ioutil.ReadFile(opt.CaCrt)
if err != nil {
return nil, err
}
ok := certPool.AppendCertsFromPEM(bs)
if !ok {
return nil, fmt.Errorf("failed to append certs")
}
tlsConf.InsecureSkipVerify = false
tlsConf.RootCAs = certPool
}
dailOpts := []grpc.DialOption{
grpc.WithTransportCredentials(credentials.NewTLS(tlsConf)),
}
if opt.WithBlock {
dailOpts = append(dailOpts, grpc.WithBlock(), grpc.WithTimeout(5*time.Second))
}
// Dail and return connection
conn, err := grpc.Dial(addr, dailOpts...)
if err != nil {
return nil, err
}
return conn, nil
}
|
[
"func",
"NewClient",
"(",
"addr",
"string",
",",
"opt",
"*",
"ClientOpt",
")",
"(",
"*",
"grpc",
".",
"ClientConn",
",",
"error",
")",
"{",
"if",
"opt",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Load key pair",
"certificate",
",",
"err",
":=",
"tls",
".",
"LoadX509KeyPair",
"(",
"opt",
".",
"Crt",
",",
"opt",
".",
"Key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"tlsConf",
":=",
"&",
"tls",
".",
"Config",
"{",
"ServerName",
":",
"opt",
".",
"ServerName",
",",
"Certificates",
":",
"[",
"]",
"tls",
".",
"Certificate",
"{",
"certificate",
"}",
",",
"InsecureSkipVerify",
":",
"opt",
".",
"InsecureSkipVerify",
",",
"}",
"\n\n",
"// Mutual handshake with private ca",
"if",
"opt",
".",
"CaCrt",
"!=",
"\"",
"\"",
"{",
"certPool",
":=",
"x509",
".",
"NewCertPool",
"(",
")",
"\n",
"bs",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"opt",
".",
"CaCrt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"ok",
":=",
"certPool",
".",
"AppendCertsFromPEM",
"(",
"bs",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"tlsConf",
".",
"InsecureSkipVerify",
"=",
"false",
"\n",
"tlsConf",
".",
"RootCAs",
"=",
"certPool",
"\n",
"}",
"\n\n",
"dailOpts",
":=",
"[",
"]",
"grpc",
".",
"DialOption",
"{",
"grpc",
".",
"WithTransportCredentials",
"(",
"credentials",
".",
"NewTLS",
"(",
"tlsConf",
")",
")",
",",
"}",
"\n\n",
"if",
"opt",
".",
"WithBlock",
"{",
"dailOpts",
"=",
"append",
"(",
"dailOpts",
",",
"grpc",
".",
"WithBlock",
"(",
")",
",",
"grpc",
".",
"WithTimeout",
"(",
"5",
"*",
"time",
".",
"Second",
")",
")",
"\n",
"}",
"\n\n",
"// Dail and return connection",
"conn",
",",
"err",
":=",
"grpc",
".",
"Dial",
"(",
"addr",
",",
"dailOpts",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"conn",
",",
"nil",
"\n\n",
"}"
] |
// NewClient creates new grpc connection to the addr using the ClientOpt
|
[
"NewClient",
"creates",
"new",
"grpc",
"connection",
"to",
"the",
"addr",
"using",
"the",
"ClientOpt"
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/sdk/sdk.go#L42-L91
|
14,870 |
digota/digota
|
server/server.go
|
New
|
func New(conf *config.AppConfig) *server {
if conf.Insecure {
acl.SetSkipAuth()
}
// create new storage handler
if err := storage.New(conf.Storage); err != nil {
log.Fatalf("Could not create storage handler => %s", err.Error())
}
// create new locker handler
if err := locker.New(conf.Locker); err != nil {
log.Fatalf("Could not create locker handler => %s", err.Error())
}
// load ca clients
client.New(conf.Clients)
providers.New(conf.Payment)
lis, err := net.Listen("tcp", conf.Address)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
log.Infof("Listening on %s", conf.Address)
return &server{
listener: lis,
grpcServer: newGRPCServer(conf),
}
}
|
go
|
func New(conf *config.AppConfig) *server {
if conf.Insecure {
acl.SetSkipAuth()
}
// create new storage handler
if err := storage.New(conf.Storage); err != nil {
log.Fatalf("Could not create storage handler => %s", err.Error())
}
// create new locker handler
if err := locker.New(conf.Locker); err != nil {
log.Fatalf("Could not create locker handler => %s", err.Error())
}
// load ca clients
client.New(conf.Clients)
providers.New(conf.Payment)
lis, err := net.Listen("tcp", conf.Address)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
log.Infof("Listening on %s", conf.Address)
return &server{
listener: lis,
grpcServer: newGRPCServer(conf),
}
}
|
[
"func",
"New",
"(",
"conf",
"*",
"config",
".",
"AppConfig",
")",
"*",
"server",
"{",
"if",
"conf",
".",
"Insecure",
"{",
"acl",
".",
"SetSkipAuth",
"(",
")",
"\n",
"}",
"\n\n",
"// create new storage handler",
"if",
"err",
":=",
"storage",
".",
"New",
"(",
"conf",
".",
"Storage",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"// create new locker handler",
"if",
"err",
":=",
"locker",
".",
"New",
"(",
"conf",
".",
"Locker",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"// load ca clients",
"client",
".",
"New",
"(",
"conf",
".",
"Clients",
")",
"\n",
"providers",
".",
"New",
"(",
"conf",
".",
"Payment",
")",
"\n\n",
"lis",
",",
"err",
":=",
"net",
".",
"Listen",
"(",
"\"",
"\"",
",",
"conf",
".",
"Address",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"conf",
".",
"Address",
")",
"\n",
"return",
"&",
"server",
"{",
"listener",
":",
"lis",
",",
"grpcServer",
":",
"newGRPCServer",
"(",
"conf",
")",
",",
"}",
"\n",
"}"
] |
// New create new digota server
|
[
"New",
"create",
"new",
"digota",
"server"
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/server/server.go#L77-L106
|
14,871 |
digota/digota
|
payment/service/providers/providers.go
|
Provider
|
func Provider(p paymentpb.PaymentProviderId) Interface {
mtx.Lock()
defer mtx.Unlock()
if v, ok := providers[p]; ok {
return v
}
log.Panicf("payment provider %s isn't registered", p.String())
return nil
}
|
go
|
func Provider(p paymentpb.PaymentProviderId) Interface {
mtx.Lock()
defer mtx.Unlock()
if v, ok := providers[p]; ok {
return v
}
log.Panicf("payment provider %s isn't registered", p.String())
return nil
}
|
[
"func",
"Provider",
"(",
"p",
"paymentpb",
".",
"PaymentProviderId",
")",
"Interface",
"{",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"if",
"v",
",",
"ok",
":=",
"providers",
"[",
"p",
"]",
";",
"ok",
"{",
"return",
"v",
"\n",
"}",
"\n",
"log",
".",
"Panicf",
"(",
"\"",
"\"",
",",
"p",
".",
"String",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Provider returns payment provider from the map using the provided id
// panics if the provider could not be found
|
[
"Provider",
"returns",
"payment",
"provider",
"from",
"the",
"map",
"using",
"the",
"provided",
"id",
"panics",
"if",
"the",
"provider",
"could",
"not",
"be",
"found"
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/payment/service/providers/providers.go#L79-L87
|
14,872 |
digota/digota
|
client/client.go
|
NewContext
|
func NewContext(ctx context.Context, serialId *big.Int) context.Context {
var c *Client
var err error
if c, err = GetClient(util.BigIntToHex(serialId)); err != nil {
return ctx
}
return context.WithValue(ctx, clientKey{}, c)
}
|
go
|
func NewContext(ctx context.Context, serialId *big.Int) context.Context {
var c *Client
var err error
if c, err = GetClient(util.BigIntToHex(serialId)); err != nil {
return ctx
}
return context.WithValue(ctx, clientKey{}, c)
}
|
[
"func",
"NewContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"serialId",
"*",
"big",
".",
"Int",
")",
"context",
".",
"Context",
"{",
"var",
"c",
"*",
"Client",
"\n",
"var",
"err",
"error",
"\n",
"if",
"c",
",",
"err",
"=",
"GetClient",
"(",
"util",
".",
"BigIntToHex",
"(",
"serialId",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"ctx",
"\n",
"}",
"\n",
"return",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"clientKey",
"{",
"}",
",",
"c",
")",
"\n",
"}"
] |
// NewContext store user in ctx and return new ctx.
|
[
"NewContext",
"store",
"user",
"in",
"ctx",
"and",
"return",
"new",
"ctx",
"."
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/client/client.go#L73-L80
|
14,873 |
digota/digota
|
client/client.go
|
FromContext
|
func FromContext(ctx context.Context) (*Client, bool) {
u, ok := ctx.Value(clientKey{}).(*Client)
return u, ok
}
|
go
|
func FromContext(ctx context.Context) (*Client, bool) {
u, ok := ctx.Value(clientKey{}).(*Client)
return u, ok
}
|
[
"func",
"FromContext",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"*",
"Client",
",",
"bool",
")",
"{",
"u",
",",
"ok",
":=",
"ctx",
".",
"Value",
"(",
"clientKey",
"{",
"}",
")",
".",
"(",
"*",
"Client",
")",
"\n",
"return",
"u",
",",
"ok",
"\n",
"}"
] |
// FromContext returns the User stored in ctx, if any.
|
[
"FromContext",
"returns",
"the",
"User",
"stored",
"in",
"ctx",
"if",
"any",
"."
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/client/client.go#L83-L86
|
14,874 |
digota/digota
|
client/client.go
|
GetClient
|
func GetClient(serialId string) (*Client, error) {
// search for user
for _, c := range clients {
if c.Serial == serialId {
return &c, nil
}
}
return nil, errors.New("Cant find client.")
}
|
go
|
func GetClient(serialId string) (*Client, error) {
// search for user
for _, c := range clients {
if c.Serial == serialId {
return &c, nil
}
}
return nil, errors.New("Cant find client.")
}
|
[
"func",
"GetClient",
"(",
"serialId",
"string",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"// search for user",
"for",
"_",
",",
"c",
":=",
"range",
"clients",
"{",
"if",
"c",
".",
"Serial",
"==",
"serialId",
"{",
"return",
"&",
"c",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] |
// GetClient return client based on provided serialId
|
[
"GetClient",
"return",
"client",
"based",
"on",
"provided",
"serialId"
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/client/client.go#L89-L97
|
14,875 |
digota/digota
|
validation/validation.go
|
Validate
|
func Validate(req interface{}) error {
// validate req message
if err := v.Struct(req); err != nil {
if v, ok := err.(validator.ValidationErrors); ok {
err = v
}
return status.Errorf(codes.InvalidArgument, "Request validation failed: %s", err)
}
return nil
}
|
go
|
func Validate(req interface{}) error {
// validate req message
if err := v.Struct(req); err != nil {
if v, ok := err.(validator.ValidationErrors); ok {
err = v
}
return status.Errorf(codes.InvalidArgument, "Request validation failed: %s", err)
}
return nil
}
|
[
"func",
"Validate",
"(",
"req",
"interface",
"{",
"}",
")",
"error",
"{",
"// validate req message",
"if",
"err",
":=",
"v",
".",
"Struct",
"(",
"req",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"v",
",",
"ok",
":=",
"err",
".",
"(",
"validator",
".",
"ValidationErrors",
")",
";",
"ok",
"{",
"err",
"=",
"v",
"\n",
"}",
"\n",
"return",
"status",
".",
"Errorf",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Validate is doing struct level validation using validator.v9
|
[
"Validate",
"is",
"doing",
"struct",
"level",
"validation",
"using",
"validator",
".",
"v9"
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/validation/validation.go#L34-L43
|
14,876 |
digota/digota
|
storage/storage.go
|
New
|
func New(storageConfig config.Storage) error {
// create handler based on the storage config
switch handlerName(storageConfig.Handler) {
case mongodbHandler:
handler = mongo.NewHandler(storageConfig)
default:
return errors.New("Invalid storage handler `" + storageConfig.Handler + "`")
}
// prepare handler
return handler.Prepare()
}
|
go
|
func New(storageConfig config.Storage) error {
// create handler based on the storage config
switch handlerName(storageConfig.Handler) {
case mongodbHandler:
handler = mongo.NewHandler(storageConfig)
default:
return errors.New("Invalid storage handler `" + storageConfig.Handler + "`")
}
// prepare handler
return handler.Prepare()
}
|
[
"func",
"New",
"(",
"storageConfig",
"config",
".",
"Storage",
")",
"error",
"{",
"// create handler based on the storage config",
"switch",
"handlerName",
"(",
"storageConfig",
".",
"Handler",
")",
"{",
"case",
"mongodbHandler",
":",
"handler",
"=",
"mongo",
".",
"NewHandler",
"(",
"storageConfig",
")",
"\n",
"default",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"storageConfig",
".",
"Handler",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// prepare handler",
"return",
"handler",
".",
"Prepare",
"(",
")",
"\n",
"}"
] |
// New creates storage handler from config.Storage and prepare it for use
// returns error if something went wrong during the preparations
|
[
"New",
"creates",
"storage",
"handler",
"from",
"config",
".",
"Storage",
"and",
"prepare",
"it",
"for",
"use",
"returns",
"error",
"if",
"something",
"went",
"wrong",
"during",
"the",
"preparations"
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/storage/storage.go#L58-L68
|
14,877 |
digota/digota
|
locker/locker.go
|
New
|
func New(lockerConfig config.Locker) error {
var err error
switch handlerName(lockerConfig.Handler) {
case zookeeperHandler:
handler, err = zookeeper.NewLocker(lockerConfig)
return err
case redisHandler:
handler, err = redis.NewLocker(lockerConfig)
return err
default:
handler = memlock.NewLocker()
}
return nil
}
|
go
|
func New(lockerConfig config.Locker) error {
var err error
switch handlerName(lockerConfig.Handler) {
case zookeeperHandler:
handler, err = zookeeper.NewLocker(lockerConfig)
return err
case redisHandler:
handler, err = redis.NewLocker(lockerConfig)
return err
default:
handler = memlock.NewLocker()
}
return nil
}
|
[
"func",
"New",
"(",
"lockerConfig",
"config",
".",
"Locker",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"switch",
"handlerName",
"(",
"lockerConfig",
".",
"Handler",
")",
"{",
"case",
"zookeeperHandler",
":",
"handler",
",",
"err",
"=",
"zookeeper",
".",
"NewLocker",
"(",
"lockerConfig",
")",
"\n",
"return",
"err",
"\n",
"case",
"redisHandler",
":",
"handler",
",",
"err",
"=",
"redis",
".",
"NewLocker",
"(",
"lockerConfig",
")",
"\n",
"return",
"err",
"\n",
"default",
":",
"handler",
"=",
"memlock",
".",
"NewLocker",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// New creates a locker handler from the provided
// config.Locker and save it in handler for further use
|
[
"New",
"creates",
"a",
"locker",
"handler",
"from",
"the",
"provided",
"config",
".",
"Locker",
"and",
"save",
"it",
"in",
"handler",
"for",
"further",
"use"
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/locker/locker.go#L58-L71
|
14,878 |
digota/digota
|
order/service/service.go
|
IsReturnable
|
func (o *order) IsReturnable(amount int64) error {
if o.Status != orderpb.Order_Paid && o.Status != orderpb.Order_Fulfilled && o.Status != orderpb.Order_Canceled {
return status.Error(codes.Internal, "Order is not paid or fulfilled.")
}
// if refund amount is bigger than the order amount return err
if amount > o.GetAmount() {
return status.Error(codes.Internal, "Refund amount is greater then order amount.")
}
return nil
}
|
go
|
func (o *order) IsReturnable(amount int64) error {
if o.Status != orderpb.Order_Paid && o.Status != orderpb.Order_Fulfilled && o.Status != orderpb.Order_Canceled {
return status.Error(codes.Internal, "Order is not paid or fulfilled.")
}
// if refund amount is bigger than the order amount return err
if amount > o.GetAmount() {
return status.Error(codes.Internal, "Refund amount is greater then order amount.")
}
return nil
}
|
[
"func",
"(",
"o",
"*",
"order",
")",
"IsReturnable",
"(",
"amount",
"int64",
")",
"error",
"{",
"if",
"o",
".",
"Status",
"!=",
"orderpb",
".",
"Order_Paid",
"&&",
"o",
".",
"Status",
"!=",
"orderpb",
".",
"Order_Fulfilled",
"&&",
"o",
".",
"Status",
"!=",
"orderpb",
".",
"Order_Canceled",
"{",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"Internal",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// if refund amount is bigger than the order amount return err",
"if",
"amount",
">",
"o",
".",
"GetAmount",
"(",
")",
"{",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"Internal",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// IsReturnable checks che
|
[
"IsReturnable",
"checks",
"che"
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/order/service/service.go#L89-L98
|
14,879 |
digota/digota
|
order/service/service.go
|
New
|
func (s *orderService) New(ctx context.Context, req *orderpb.NewRequest) (*orderpb.Order, error) {
// validate input
if err := validation.Validate(req); err != nil {
return nil, err
}
// order wrapper
o := &order{
Order: orderpb.Order{
Email: req.GetEmail(),
Status: orderpb.Order_Created,
Amount: 0,
Currency: req.GetCurrency(),
Shipping: req.GetShipping(),
},
}
// get relevant order items
orderItems, err := getUpdatedOrderItems(req.GetItems())
if err != nil {
return nil, err
}
// update order items
o.Items = orderItems
// calculate final amount
amount, err := calculateTotal(o.GetCurrency(), orderItems)
if err != nil {
return nil, err
}
// update order amount
o.Amount = amount
// Insert and return order
return &o.Order, storage.Handler().Insert(o)
}
|
go
|
func (s *orderService) New(ctx context.Context, req *orderpb.NewRequest) (*orderpb.Order, error) {
// validate input
if err := validation.Validate(req); err != nil {
return nil, err
}
// order wrapper
o := &order{
Order: orderpb.Order{
Email: req.GetEmail(),
Status: orderpb.Order_Created,
Amount: 0,
Currency: req.GetCurrency(),
Shipping: req.GetShipping(),
},
}
// get relevant order items
orderItems, err := getUpdatedOrderItems(req.GetItems())
if err != nil {
return nil, err
}
// update order items
o.Items = orderItems
// calculate final amount
amount, err := calculateTotal(o.GetCurrency(), orderItems)
if err != nil {
return nil, err
}
// update order amount
o.Amount = amount
// Insert and return order
return &o.Order, storage.Handler().Insert(o)
}
|
[
"func",
"(",
"s",
"*",
"orderService",
")",
"New",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"orderpb",
".",
"NewRequest",
")",
"(",
"*",
"orderpb",
".",
"Order",
",",
"error",
")",
"{",
"// validate input",
"if",
"err",
":=",
"validation",
".",
"Validate",
"(",
"req",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// order wrapper",
"o",
":=",
"&",
"order",
"{",
"Order",
":",
"orderpb",
".",
"Order",
"{",
"Email",
":",
"req",
".",
"GetEmail",
"(",
")",
",",
"Status",
":",
"orderpb",
".",
"Order_Created",
",",
"Amount",
":",
"0",
",",
"Currency",
":",
"req",
".",
"GetCurrency",
"(",
")",
",",
"Shipping",
":",
"req",
".",
"GetShipping",
"(",
")",
",",
"}",
",",
"}",
"\n",
"// get relevant order items",
"orderItems",
",",
"err",
":=",
"getUpdatedOrderItems",
"(",
"req",
".",
"GetItems",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// update order items",
"o",
".",
"Items",
"=",
"orderItems",
"\n",
"// calculate final amount",
"amount",
",",
"err",
":=",
"calculateTotal",
"(",
"o",
".",
"GetCurrency",
"(",
")",
",",
"orderItems",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// update order amount",
"o",
".",
"Amount",
"=",
"amount",
"\n",
"// Insert and return order",
"return",
"&",
"o",
".",
"Order",
",",
"storage",
".",
"Handler",
"(",
")",
".",
"Insert",
"(",
"o",
")",
"\n",
"}"
] |
// New implements the orderpb.New interface.
// Creates new order from order Items and return Order or error, error will
// returned if something went wrong .. let say something such as inactive Items.
|
[
"New",
"implements",
"the",
"orderpb",
".",
"New",
"interface",
".",
"Creates",
"new",
"order",
"from",
"order",
"Items",
"and",
"return",
"Order",
"or",
"error",
"error",
"will",
"returned",
"if",
"something",
"went",
"wrong",
"..",
"let",
"say",
"something",
"such",
"as",
"inactive",
"Items",
"."
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/order/service/service.go#L118-L149
|
14,880 |
digota/digota
|
order/service/service.go
|
Get
|
func (s *orderService) Get(ctx context.Context, req *orderpb.GetRequest) (*orderpb.Order, error) {
// validate input
if err := validation.Validate(req); err != nil {
return nil, err
}
// order wrapper
o := &order{
Order: orderpb.Order{
Id: req.GetId(),
},
}
// acquire order lock
unlock, err := locker.Handler().TryLock(o, locker.DefaultTimeout)
if err != nil {
return nil, err
}
defer unlock()
// get and return order
return &o.Order, storage.Handler().One(o)
}
|
go
|
func (s *orderService) Get(ctx context.Context, req *orderpb.GetRequest) (*orderpb.Order, error) {
// validate input
if err := validation.Validate(req); err != nil {
return nil, err
}
// order wrapper
o := &order{
Order: orderpb.Order{
Id: req.GetId(),
},
}
// acquire order lock
unlock, err := locker.Handler().TryLock(o, locker.DefaultTimeout)
if err != nil {
return nil, err
}
defer unlock()
// get and return order
return &o.Order, storage.Handler().One(o)
}
|
[
"func",
"(",
"s",
"*",
"orderService",
")",
"Get",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"orderpb",
".",
"GetRequest",
")",
"(",
"*",
"orderpb",
".",
"Order",
",",
"error",
")",
"{",
"// validate input",
"if",
"err",
":=",
"validation",
".",
"Validate",
"(",
"req",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// order wrapper",
"o",
":=",
"&",
"order",
"{",
"Order",
":",
"orderpb",
".",
"Order",
"{",
"Id",
":",
"req",
".",
"GetId",
"(",
")",
",",
"}",
",",
"}",
"\n\n",
"// acquire order lock",
"unlock",
",",
"err",
":=",
"locker",
".",
"Handler",
"(",
")",
".",
"TryLock",
"(",
"o",
",",
"locker",
".",
"DefaultTimeout",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"unlock",
"(",
")",
"\n\n",
"// get and return order",
"return",
"&",
"o",
".",
"Order",
",",
"storage",
".",
"Handler",
"(",
")",
".",
"One",
"(",
"o",
")",
"\n",
"}"
] |
// Get implements the orderpb.Get interface.
// Retrieve order or returns error.
|
[
"Get",
"implements",
"the",
"orderpb",
".",
"Get",
"interface",
".",
"Retrieve",
"order",
"or",
"returns",
"error",
"."
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/order/service/service.go#L153-L174
|
14,881 |
digota/digota
|
order/service/service.go
|
Return
|
func (s *orderService) Return(ctx context.Context, req *orderpb.ReturnRequest) (*orderpb.Order, error) {
// validate input
if err := validation.Validate(req); err != nil {
return nil, err
}
// order wrapper
o := &order{
Order: orderpb.Order{
Id: req.GetId(),
},
}
// lock order
unlock, err := locker.Handler().TryLock(o, locker.DefaultTimeout)
if err != nil {
return nil, err
}
defer unlock()
// get order
if err := storage.Handler().One(o); err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
// calculate returns amount
amount, err := calculateTotal(o.GetCurrency(), o.GetItems())
if err != nil {
return nil, err
}
// check if order can be refunded
if err := o.IsReturnable(amount); err != nil {
return nil, err
}
// lock all inventory order items (inventory objects)
lockedItems := getLockedOrderItems(ctx, &o.Order)
// Free all locks at func return
defer func() {
for _, item := range lockedItems {
item.Unlock()
}
}()
// refund the order
if _, err := payment.Service().RefundCharge(ctx, &paymentpb.RefundRequest{Id: o.GetChargeId(), Amount: uint64(amount)}); err != nil {
return nil, err
}
// update order status
switch o.Status {
// if the order has been paid but never fulfilled
// order status turns from paid into canceled
// inventory item will get updated since the sku is in
// stock again
case orderpb.Order_Paid:
o.Status = orderpb.Order_Canceled
// notify listeners we want to return the items back in inventory
// update inventories
for _, item := range lockedItems {
if item.Sku.Inventory.Type == skupb.Inventory_Finite {
// update inventory Quantity
item.Sku.Inventory.Quantity += item.OrderItem.Quantity
item.Update()
}
}
// if the order has been fulfilled
// order status turns from fulfilled into returned
// inventory will not get updated since we still got no
// item to sell again
case orderpb.Order_Fulfilled:
o.Status = orderpb.Order_Returned
}
// update order with retries
updateErr := util.Retry(func() error {
return storage.Handler().Update(o)
})
// return err
if updateErr != nil {
return nil, status.Error(codes.DataLoss, fmt.Sprintf("could not update order {%s} object, order has been refunded {%s}!", o.Id, o.ChargeId))
}
// return order
return &o.Order, nil
}
|
go
|
func (s *orderService) Return(ctx context.Context, req *orderpb.ReturnRequest) (*orderpb.Order, error) {
// validate input
if err := validation.Validate(req); err != nil {
return nil, err
}
// order wrapper
o := &order{
Order: orderpb.Order{
Id: req.GetId(),
},
}
// lock order
unlock, err := locker.Handler().TryLock(o, locker.DefaultTimeout)
if err != nil {
return nil, err
}
defer unlock()
// get order
if err := storage.Handler().One(o); err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
// calculate returns amount
amount, err := calculateTotal(o.GetCurrency(), o.GetItems())
if err != nil {
return nil, err
}
// check if order can be refunded
if err := o.IsReturnable(amount); err != nil {
return nil, err
}
// lock all inventory order items (inventory objects)
lockedItems := getLockedOrderItems(ctx, &o.Order)
// Free all locks at func return
defer func() {
for _, item := range lockedItems {
item.Unlock()
}
}()
// refund the order
if _, err := payment.Service().RefundCharge(ctx, &paymentpb.RefundRequest{Id: o.GetChargeId(), Amount: uint64(amount)}); err != nil {
return nil, err
}
// update order status
switch o.Status {
// if the order has been paid but never fulfilled
// order status turns from paid into canceled
// inventory item will get updated since the sku is in
// stock again
case orderpb.Order_Paid:
o.Status = orderpb.Order_Canceled
// notify listeners we want to return the items back in inventory
// update inventories
for _, item := range lockedItems {
if item.Sku.Inventory.Type == skupb.Inventory_Finite {
// update inventory Quantity
item.Sku.Inventory.Quantity += item.OrderItem.Quantity
item.Update()
}
}
// if the order has been fulfilled
// order status turns from fulfilled into returned
// inventory will not get updated since we still got no
// item to sell again
case orderpb.Order_Fulfilled:
o.Status = orderpb.Order_Returned
}
// update order with retries
updateErr := util.Retry(func() error {
return storage.Handler().Update(o)
})
// return err
if updateErr != nil {
return nil, status.Error(codes.DataLoss, fmt.Sprintf("could not update order {%s} object, order has been refunded {%s}!", o.Id, o.ChargeId))
}
// return order
return &o.Order, nil
}
|
[
"func",
"(",
"s",
"*",
"orderService",
")",
"Return",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"orderpb",
".",
"ReturnRequest",
")",
"(",
"*",
"orderpb",
".",
"Order",
",",
"error",
")",
"{",
"// validate input",
"if",
"err",
":=",
"validation",
".",
"Validate",
"(",
"req",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// order wrapper",
"o",
":=",
"&",
"order",
"{",
"Order",
":",
"orderpb",
".",
"Order",
"{",
"Id",
":",
"req",
".",
"GetId",
"(",
")",
",",
"}",
",",
"}",
"\n",
"// lock order",
"unlock",
",",
"err",
":=",
"locker",
".",
"Handler",
"(",
")",
".",
"TryLock",
"(",
"o",
",",
"locker",
".",
"DefaultTimeout",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"unlock",
"(",
")",
"\n\n",
"// get order",
"if",
"err",
":=",
"storage",
".",
"Handler",
"(",
")",
".",
"One",
"(",
"o",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"status",
".",
"Error",
"(",
"codes",
".",
"Internal",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"// calculate returns amount",
"amount",
",",
"err",
":=",
"calculateTotal",
"(",
"o",
".",
"GetCurrency",
"(",
")",
",",
"o",
".",
"GetItems",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// check if order can be refunded",
"if",
"err",
":=",
"o",
".",
"IsReturnable",
"(",
"amount",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// lock all inventory order items (inventory objects)",
"lockedItems",
":=",
"getLockedOrderItems",
"(",
"ctx",
",",
"&",
"o",
".",
"Order",
")",
"\n",
"// Free all locks at func return",
"defer",
"func",
"(",
")",
"{",
"for",
"_",
",",
"item",
":=",
"range",
"lockedItems",
"{",
"item",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"// refund the order",
"if",
"_",
",",
"err",
":=",
"payment",
".",
"Service",
"(",
")",
".",
"RefundCharge",
"(",
"ctx",
",",
"&",
"paymentpb",
".",
"RefundRequest",
"{",
"Id",
":",
"o",
".",
"GetChargeId",
"(",
")",
",",
"Amount",
":",
"uint64",
"(",
"amount",
")",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// update order status",
"switch",
"o",
".",
"Status",
"{",
"// if the order has been paid but never fulfilled",
"// order status turns from paid into canceled",
"// inventory item will get updated since the sku is in",
"// stock again",
"case",
"orderpb",
".",
"Order_Paid",
":",
"o",
".",
"Status",
"=",
"orderpb",
".",
"Order_Canceled",
"\n",
"// notify listeners we want to return the items back in inventory",
"// update inventories",
"for",
"_",
",",
"item",
":=",
"range",
"lockedItems",
"{",
"if",
"item",
".",
"Sku",
".",
"Inventory",
".",
"Type",
"==",
"skupb",
".",
"Inventory_Finite",
"{",
"// update inventory Quantity",
"item",
".",
"Sku",
".",
"Inventory",
".",
"Quantity",
"+=",
"item",
".",
"OrderItem",
".",
"Quantity",
"\n",
"item",
".",
"Update",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"// if the order has been fulfilled",
"// order status turns from fulfilled into returned",
"// inventory will not get updated since we still got no",
"// item to sell again",
"case",
"orderpb",
".",
"Order_Fulfilled",
":",
"o",
".",
"Status",
"=",
"orderpb",
".",
"Order_Returned",
"\n",
"}",
"\n",
"// update order with retries",
"updateErr",
":=",
"util",
".",
"Retry",
"(",
"func",
"(",
")",
"error",
"{",
"return",
"storage",
".",
"Handler",
"(",
")",
".",
"Update",
"(",
"o",
")",
"\n",
"}",
")",
"\n",
"// return err",
"if",
"updateErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"status",
".",
"Error",
"(",
"codes",
".",
"DataLoss",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"o",
".",
"Id",
",",
"o",
".",
"ChargeId",
")",
")",
"\n",
"}",
"\n",
"// return order",
"return",
"&",
"o",
".",
"Order",
",",
"nil",
"\n",
"}"
] |
// Pay implements the orderpb.Pay interface. Pay on specific orderId with CC based on payment provider supplied.
|
[
"Pay",
"implements",
"the",
"orderpb",
".",
"Pay",
"interface",
".",
"Pay",
"on",
"specific",
"orderId",
"with",
"CC",
"based",
"on",
"payment",
"provider",
"supplied",
"."
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/order/service/service.go#L294-L371
|
14,882 |
digota/digota
|
order/service/service.go
|
calculateTotal
|
func calculateTotal(currency paymentpb.Currency, orderItems []*orderpb.OrderItem) (int64, error) {
var err error
m := money.New(0, currency.String())
for _, v := range orderItems {
if v.Quantity <= 0 {
v.Quantity = 1
}
m, err = m.Add(money.New(v.Quantity*v.Amount, v.Currency.String()))
if err != nil {
return 0, status.Error(codes.Internal, err.Error())
}
}
return m.Amount(), nil
}
|
go
|
func calculateTotal(currency paymentpb.Currency, orderItems []*orderpb.OrderItem) (int64, error) {
var err error
m := money.New(0, currency.String())
for _, v := range orderItems {
if v.Quantity <= 0 {
v.Quantity = 1
}
m, err = m.Add(money.New(v.Quantity*v.Amount, v.Currency.String()))
if err != nil {
return 0, status.Error(codes.Internal, err.Error())
}
}
return m.Amount(), nil
}
|
[
"func",
"calculateTotal",
"(",
"currency",
"paymentpb",
".",
"Currency",
",",
"orderItems",
"[",
"]",
"*",
"orderpb",
".",
"OrderItem",
")",
"(",
"int64",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"m",
":=",
"money",
".",
"New",
"(",
"0",
",",
"currency",
".",
"String",
"(",
")",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"orderItems",
"{",
"if",
"v",
".",
"Quantity",
"<=",
"0",
"{",
"v",
".",
"Quantity",
"=",
"1",
"\n",
"}",
"\n",
"m",
",",
"err",
"=",
"m",
".",
"Add",
"(",
"money",
".",
"New",
"(",
"v",
".",
"Quantity",
"*",
"v",
".",
"Amount",
",",
"v",
".",
"Currency",
".",
"String",
"(",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"status",
".",
"Error",
"(",
"codes",
".",
"Internal",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"m",
".",
"Amount",
"(",
")",
",",
"nil",
"\n",
"}"
] |
// calculateTotal will calculate the new amount of the cart. using
// go-money library, which helps us to do money calculations of
// the `Fowler's Money pattern`. will return error if something went
// wrong, like wrong currencies.
|
[
"calculateTotal",
"will",
"calculate",
"the",
"new",
"amount",
"of",
"the",
"cart",
".",
"using",
"go",
"-",
"money",
"library",
"which",
"helps",
"us",
"to",
"do",
"money",
"calculations",
"of",
"the",
"Fowler",
"s",
"Money",
"pattern",
".",
"will",
"return",
"error",
"if",
"something",
"went",
"wrong",
"like",
"wrong",
"currencies",
"."
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/order/service/service.go#L377-L390
|
14,883 |
digota/digota
|
payment/payment.go
|
WriteMethods
|
func WriteMethods() []*regexp.Regexp {
return []*regexp.Regexp{
regexp.MustCompile(baseMethod + "NewCharge"),
regexp.MustCompile(baseMethod + "RefundCharge"),
}
}
|
go
|
func WriteMethods() []*regexp.Regexp {
return []*regexp.Regexp{
regexp.MustCompile(baseMethod + "NewCharge"),
regexp.MustCompile(baseMethod + "RefundCharge"),
}
}
|
[
"func",
"WriteMethods",
"(",
")",
"[",
"]",
"*",
"regexp",
".",
"Regexp",
"{",
"return",
"[",
"]",
"*",
"regexp",
".",
"Regexp",
"{",
"regexp",
".",
"MustCompile",
"(",
"baseMethod",
"+",
"\"",
"\"",
")",
",",
"regexp",
".",
"MustCompile",
"(",
"baseMethod",
"+",
"\"",
"\"",
")",
",",
"}",
"\n",
"}"
] |
// WriteMethods returns regexp slice of writable methods, mostly used by the acl
|
[
"WriteMethods",
"returns",
"regexp",
"slice",
"of",
"writable",
"methods",
"mostly",
"used",
"by",
"the",
"acl"
] |
c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c
|
https://github.com/digota/digota/blob/c2a16d57bfe0fd0d6f3a7b9a71122668a24c1e6c/payment/payment.go#L67-L72
|
14,884 |
lestrrat-go/file-rotatelogs
|
options.go
|
WithLocation
|
func WithLocation(loc *time.Location) Option {
return option.New(optkeyClock, clockFn(func() time.Time {
return time.Now().In(loc)
}))
}
|
go
|
func WithLocation(loc *time.Location) Option {
return option.New(optkeyClock, clockFn(func() time.Time {
return time.Now().In(loc)
}))
}
|
[
"func",
"WithLocation",
"(",
"loc",
"*",
"time",
".",
"Location",
")",
"Option",
"{",
"return",
"option",
".",
"New",
"(",
"optkeyClock",
",",
"clockFn",
"(",
"func",
"(",
")",
"time",
".",
"Time",
"{",
"return",
"time",
".",
"Now",
"(",
")",
".",
"In",
"(",
"loc",
")",
"\n",
"}",
")",
")",
"\n",
"}"
] |
// WithLocation creates a new Option that sets up a
// "Clock" interface that the RotateLogs object will use
// to determine the current time.
//
// This optin works by always returning the in the given
// location.
|
[
"WithLocation",
"creates",
"a",
"new",
"Option",
"that",
"sets",
"up",
"a",
"Clock",
"interface",
"that",
"the",
"RotateLogs",
"object",
"will",
"use",
"to",
"determine",
"the",
"current",
"time",
".",
"This",
"optin",
"works",
"by",
"always",
"returning",
"the",
"in",
"the",
"given",
"location",
"."
] |
4ce522c92b91beadfd4c77f75dcc06ffe97cf9c6
|
https://github.com/lestrrat-go/file-rotatelogs/blob/4ce522c92b91beadfd4c77f75dcc06ffe97cf9c6/options.go#L36-L40
|
14,885 |
lestrrat-go/file-rotatelogs
|
rotatelogs.go
|
New
|
func New(p string, options ...Option) (*RotateLogs, error) {
globPattern := p
for _, re := range patternConversionRegexps {
globPattern = re.ReplaceAllString(globPattern, "*")
}
pattern, err := strftime.New(p)
if err != nil {
return nil, errors.Wrap(err, `invalid strftime pattern`)
}
var clock Clock = Local
rotationTime := 24 * time.Hour
var rotationCount uint
var linkName string
var maxAge time.Duration
var handler Handler
for _, o := range options {
switch o.Name() {
case optkeyClock:
clock = o.Value().(Clock)
case optkeyLinkName:
linkName = o.Value().(string)
case optkeyMaxAge:
maxAge = o.Value().(time.Duration)
if maxAge < 0 {
maxAge = 0
}
case optkeyRotationTime:
rotationTime = o.Value().(time.Duration)
if rotationTime < 0 {
rotationTime = 0
}
case optkeyRotationCount:
rotationCount = o.Value().(uint)
case optkeyHandler:
handler = o.Value().(Handler)
}
}
if maxAge > 0 && rotationCount > 0 {
return nil, errors.New("options MaxAge and RotationCount cannot be both set")
}
if maxAge == 0 && rotationCount == 0 {
// if both are 0, give maxAge a sane default
maxAge = 7 * 24 * time.Hour
}
return &RotateLogs{
clock: clock,
eventHandler: handler,
globPattern: globPattern,
linkName: linkName,
maxAge: maxAge,
pattern: pattern,
rotationTime: rotationTime,
rotationCount: rotationCount,
}, nil
}
|
go
|
func New(p string, options ...Option) (*RotateLogs, error) {
globPattern := p
for _, re := range patternConversionRegexps {
globPattern = re.ReplaceAllString(globPattern, "*")
}
pattern, err := strftime.New(p)
if err != nil {
return nil, errors.Wrap(err, `invalid strftime pattern`)
}
var clock Clock = Local
rotationTime := 24 * time.Hour
var rotationCount uint
var linkName string
var maxAge time.Duration
var handler Handler
for _, o := range options {
switch o.Name() {
case optkeyClock:
clock = o.Value().(Clock)
case optkeyLinkName:
linkName = o.Value().(string)
case optkeyMaxAge:
maxAge = o.Value().(time.Duration)
if maxAge < 0 {
maxAge = 0
}
case optkeyRotationTime:
rotationTime = o.Value().(time.Duration)
if rotationTime < 0 {
rotationTime = 0
}
case optkeyRotationCount:
rotationCount = o.Value().(uint)
case optkeyHandler:
handler = o.Value().(Handler)
}
}
if maxAge > 0 && rotationCount > 0 {
return nil, errors.New("options MaxAge and RotationCount cannot be both set")
}
if maxAge == 0 && rotationCount == 0 {
// if both are 0, give maxAge a sane default
maxAge = 7 * 24 * time.Hour
}
return &RotateLogs{
clock: clock,
eventHandler: handler,
globPattern: globPattern,
linkName: linkName,
maxAge: maxAge,
pattern: pattern,
rotationTime: rotationTime,
rotationCount: rotationCount,
}, nil
}
|
[
"func",
"New",
"(",
"p",
"string",
",",
"options",
"...",
"Option",
")",
"(",
"*",
"RotateLogs",
",",
"error",
")",
"{",
"globPattern",
":=",
"p",
"\n",
"for",
"_",
",",
"re",
":=",
"range",
"patternConversionRegexps",
"{",
"globPattern",
"=",
"re",
".",
"ReplaceAllString",
"(",
"globPattern",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"pattern",
",",
"err",
":=",
"strftime",
".",
"New",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"`invalid strftime pattern`",
")",
"\n",
"}",
"\n\n",
"var",
"clock",
"Clock",
"=",
"Local",
"\n",
"rotationTime",
":=",
"24",
"*",
"time",
".",
"Hour",
"\n",
"var",
"rotationCount",
"uint",
"\n",
"var",
"linkName",
"string",
"\n",
"var",
"maxAge",
"time",
".",
"Duration",
"\n",
"var",
"handler",
"Handler",
"\n\n",
"for",
"_",
",",
"o",
":=",
"range",
"options",
"{",
"switch",
"o",
".",
"Name",
"(",
")",
"{",
"case",
"optkeyClock",
":",
"clock",
"=",
"o",
".",
"Value",
"(",
")",
".",
"(",
"Clock",
")",
"\n",
"case",
"optkeyLinkName",
":",
"linkName",
"=",
"o",
".",
"Value",
"(",
")",
".",
"(",
"string",
")",
"\n",
"case",
"optkeyMaxAge",
":",
"maxAge",
"=",
"o",
".",
"Value",
"(",
")",
".",
"(",
"time",
".",
"Duration",
")",
"\n",
"if",
"maxAge",
"<",
"0",
"{",
"maxAge",
"=",
"0",
"\n",
"}",
"\n",
"case",
"optkeyRotationTime",
":",
"rotationTime",
"=",
"o",
".",
"Value",
"(",
")",
".",
"(",
"time",
".",
"Duration",
")",
"\n",
"if",
"rotationTime",
"<",
"0",
"{",
"rotationTime",
"=",
"0",
"\n",
"}",
"\n",
"case",
"optkeyRotationCount",
":",
"rotationCount",
"=",
"o",
".",
"Value",
"(",
")",
".",
"(",
"uint",
")",
"\n",
"case",
"optkeyHandler",
":",
"handler",
"=",
"o",
".",
"Value",
"(",
")",
".",
"(",
"Handler",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"maxAge",
">",
"0",
"&&",
"rotationCount",
">",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"maxAge",
"==",
"0",
"&&",
"rotationCount",
"==",
"0",
"{",
"// if both are 0, give maxAge a sane default",
"maxAge",
"=",
"7",
"*",
"24",
"*",
"time",
".",
"Hour",
"\n",
"}",
"\n\n",
"return",
"&",
"RotateLogs",
"{",
"clock",
":",
"clock",
",",
"eventHandler",
":",
"handler",
",",
"globPattern",
":",
"globPattern",
",",
"linkName",
":",
"linkName",
",",
"maxAge",
":",
"maxAge",
",",
"pattern",
":",
"pattern",
",",
"rotationTime",
":",
"rotationTime",
",",
"rotationCount",
":",
"rotationCount",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// New creates a new RotateLogs object. A log filename pattern
// must be passed. Optional `Option` parameters may be passed
|
[
"New",
"creates",
"a",
"new",
"RotateLogs",
"object",
".",
"A",
"log",
"filename",
"pattern",
"must",
"be",
"passed",
".",
"Optional",
"Option",
"parameters",
"may",
"be",
"passed"
] |
4ce522c92b91beadfd4c77f75dcc06ffe97cf9c6
|
https://github.com/lestrrat-go/file-rotatelogs/blob/4ce522c92b91beadfd4c77f75dcc06ffe97cf9c6/rotatelogs.go#L27-L87
|
14,886 |
lestrrat-go/file-rotatelogs
|
rotatelogs.go
|
Write
|
func (rl *RotateLogs) Write(p []byte) (n int, err error) {
// Guard against concurrent writes
rl.mutex.Lock()
defer rl.mutex.Unlock()
out, err := rl.getWriter_nolock(false, false)
if err != nil {
return 0, errors.Wrap(err, `failed to acquite target io.Writer`)
}
return out.Write(p)
}
|
go
|
func (rl *RotateLogs) Write(p []byte) (n int, err error) {
// Guard against concurrent writes
rl.mutex.Lock()
defer rl.mutex.Unlock()
out, err := rl.getWriter_nolock(false, false)
if err != nil {
return 0, errors.Wrap(err, `failed to acquite target io.Writer`)
}
return out.Write(p)
}
|
[
"func",
"(",
"rl",
"*",
"RotateLogs",
")",
"Write",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"// Guard against concurrent writes",
"rl",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"rl",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"out",
",",
"err",
":=",
"rl",
".",
"getWriter_nolock",
"(",
"false",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"`failed to acquite target io.Writer`",
")",
"\n",
"}",
"\n\n",
"return",
"out",
".",
"Write",
"(",
"p",
")",
"\n",
"}"
] |
// Write satisfies the io.Writer interface. It writes to the
// appropriate file handle that is currently being used.
// If we have reached rotation time, the target file gets
// automatically rotated, and also purged if necessary.
|
[
"Write",
"satisfies",
"the",
"io",
".",
"Writer",
"interface",
".",
"It",
"writes",
"to",
"the",
"appropriate",
"file",
"handle",
"that",
"is",
"currently",
"being",
"used",
".",
"If",
"we",
"have",
"reached",
"rotation",
"time",
"the",
"target",
"file",
"gets",
"automatically",
"rotated",
"and",
"also",
"purged",
"if",
"necessary",
"."
] |
4ce522c92b91beadfd4c77f75dcc06ffe97cf9c6
|
https://github.com/lestrrat-go/file-rotatelogs/blob/4ce522c92b91beadfd4c77f75dcc06ffe97cf9c6/rotatelogs.go#L117-L128
|
14,887 |
lestrrat-go/file-rotatelogs
|
rotatelogs.go
|
getWriter_nolock
|
func (rl *RotateLogs) getWriter_nolock(bailOnRotateFail, useGenerationalNames bool) (io.Writer, error) {
generation := rl.generation
previousFn := rl.curFn
// This filename contains the name of the "NEW" filename
// to log to, which may be newer than rl.currentFilename
filename := rl.genFilename()
if previousFn != filename {
generation = 0
} else {
if !useGenerationalNames {
// nothing to do
return rl.outFh, nil
}
// This is used when we *REALLY* want to rotate a log.
// instead of just using the regular strftime pattern, we
// create a new file name using generational names such as
// "foo.1", "foo.2", "foo.3", etc
for {
generation++
name := fmt.Sprintf("%s.%d", filename, generation)
if _, err := os.Stat(name); err != nil {
filename = name
break
}
}
}
// make sure the dir is existed, eg:
// ./foo/bar/baz/hello.log must make sure ./foo/bar/baz is existed
dirname := filepath.Dir(filename)
if err := os.MkdirAll(dirname, 0755); err != nil {
return nil, errors.Wrapf(err, "failed to create directory %s", dirname)
}
// if we got here, then we need to create a file
fh, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return nil, errors.Errorf("failed to open file %s: %s", rl.pattern, err)
}
if err := rl.rotate_nolock(filename); err != nil {
err = errors.Wrap(err, "failed to rotate")
if bailOnRotateFail {
// Failure to rotate is a problem, but it's really not a great
// idea to stop your application just because you couldn't rename
// your log.
//
// We only return this error when explicitly needed (as specified by bailOnRotateFail)
//
// However, we *NEED* to close `fh` here
if fh != nil { // probably can't happen, but being paranoid
fh.Close()
}
return nil, err
}
fmt.Fprintf(os.Stderr, "%s\n", err.Error())
}
rl.outFh.Close()
rl.outFh = fh
rl.curFn = filename
rl.generation = generation
if h := rl.eventHandler; h != nil {
go h.Handle(&FileRotatedEvent{
prev: previousFn,
current: filename,
})
}
return fh, nil
}
|
go
|
func (rl *RotateLogs) getWriter_nolock(bailOnRotateFail, useGenerationalNames bool) (io.Writer, error) {
generation := rl.generation
previousFn := rl.curFn
// This filename contains the name of the "NEW" filename
// to log to, which may be newer than rl.currentFilename
filename := rl.genFilename()
if previousFn != filename {
generation = 0
} else {
if !useGenerationalNames {
// nothing to do
return rl.outFh, nil
}
// This is used when we *REALLY* want to rotate a log.
// instead of just using the regular strftime pattern, we
// create a new file name using generational names such as
// "foo.1", "foo.2", "foo.3", etc
for {
generation++
name := fmt.Sprintf("%s.%d", filename, generation)
if _, err := os.Stat(name); err != nil {
filename = name
break
}
}
}
// make sure the dir is existed, eg:
// ./foo/bar/baz/hello.log must make sure ./foo/bar/baz is existed
dirname := filepath.Dir(filename)
if err := os.MkdirAll(dirname, 0755); err != nil {
return nil, errors.Wrapf(err, "failed to create directory %s", dirname)
}
// if we got here, then we need to create a file
fh, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return nil, errors.Errorf("failed to open file %s: %s", rl.pattern, err)
}
if err := rl.rotate_nolock(filename); err != nil {
err = errors.Wrap(err, "failed to rotate")
if bailOnRotateFail {
// Failure to rotate is a problem, but it's really not a great
// idea to stop your application just because you couldn't rename
// your log.
//
// We only return this error when explicitly needed (as specified by bailOnRotateFail)
//
// However, we *NEED* to close `fh` here
if fh != nil { // probably can't happen, but being paranoid
fh.Close()
}
return nil, err
}
fmt.Fprintf(os.Stderr, "%s\n", err.Error())
}
rl.outFh.Close()
rl.outFh = fh
rl.curFn = filename
rl.generation = generation
if h := rl.eventHandler; h != nil {
go h.Handle(&FileRotatedEvent{
prev: previousFn,
current: filename,
})
}
return fh, nil
}
|
[
"func",
"(",
"rl",
"*",
"RotateLogs",
")",
"getWriter_nolock",
"(",
"bailOnRotateFail",
",",
"useGenerationalNames",
"bool",
")",
"(",
"io",
".",
"Writer",
",",
"error",
")",
"{",
"generation",
":=",
"rl",
".",
"generation",
"\n",
"previousFn",
":=",
"rl",
".",
"curFn",
"\n",
"// This filename contains the name of the \"NEW\" filename",
"// to log to, which may be newer than rl.currentFilename",
"filename",
":=",
"rl",
".",
"genFilename",
"(",
")",
"\n",
"if",
"previousFn",
"!=",
"filename",
"{",
"generation",
"=",
"0",
"\n",
"}",
"else",
"{",
"if",
"!",
"useGenerationalNames",
"{",
"// nothing to do",
"return",
"rl",
".",
"outFh",
",",
"nil",
"\n",
"}",
"\n",
"// This is used when we *REALLY* want to rotate a log.",
"// instead of just using the regular strftime pattern, we",
"// create a new file name using generational names such as",
"// \"foo.1\", \"foo.2\", \"foo.3\", etc",
"for",
"{",
"generation",
"++",
"\n",
"name",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"filename",
",",
"generation",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"name",
")",
";",
"err",
"!=",
"nil",
"{",
"filename",
"=",
"name",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"// make sure the dir is existed, eg:",
"// ./foo/bar/baz/hello.log must make sure ./foo/bar/baz is existed",
"dirname",
":=",
"filepath",
".",
"Dir",
"(",
"filename",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"dirname",
",",
"0755",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"dirname",
")",
"\n",
"}",
"\n",
"// if we got here, then we need to create a file",
"fh",
",",
"err",
":=",
"os",
".",
"OpenFile",
"(",
"filename",
",",
"os",
".",
"O_CREATE",
"|",
"os",
".",
"O_APPEND",
"|",
"os",
".",
"O_WRONLY",
",",
"0644",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"rl",
".",
"pattern",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"rl",
".",
"rotate_nolock",
"(",
"filename",
")",
";",
"err",
"!=",
"nil",
"{",
"err",
"=",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"if",
"bailOnRotateFail",
"{",
"// Failure to rotate is a problem, but it's really not a great",
"// idea to stop your application just because you couldn't rename",
"// your log.",
"//",
"// We only return this error when explicitly needed (as specified by bailOnRotateFail)",
"//",
"// However, we *NEED* to close `fh` here",
"if",
"fh",
"!=",
"nil",
"{",
"// probably can't happen, but being paranoid",
"fh",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\n",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"rl",
".",
"outFh",
".",
"Close",
"(",
")",
"\n",
"rl",
".",
"outFh",
"=",
"fh",
"\n",
"rl",
".",
"curFn",
"=",
"filename",
"\n",
"rl",
".",
"generation",
"=",
"generation",
"\n\n",
"if",
"h",
":=",
"rl",
".",
"eventHandler",
";",
"h",
"!=",
"nil",
"{",
"go",
"h",
".",
"Handle",
"(",
"&",
"FileRotatedEvent",
"{",
"prev",
":",
"previousFn",
",",
"current",
":",
"filename",
",",
"}",
")",
"\n",
"}",
"\n",
"return",
"fh",
",",
"nil",
"\n",
"}"
] |
// must be locked during this operation
|
[
"must",
"be",
"locked",
"during",
"this",
"operation"
] |
4ce522c92b91beadfd4c77f75dcc06ffe97cf9c6
|
https://github.com/lestrrat-go/file-rotatelogs/blob/4ce522c92b91beadfd4c77f75dcc06ffe97cf9c6/rotatelogs.go#L131-L199
|
14,888 |
lestrrat-go/file-rotatelogs
|
rotatelogs.go
|
CurrentFileName
|
func (rl *RotateLogs) CurrentFileName() string {
rl.mutex.RLock()
defer rl.mutex.RUnlock()
return rl.curFn
}
|
go
|
func (rl *RotateLogs) CurrentFileName() string {
rl.mutex.RLock()
defer rl.mutex.RUnlock()
return rl.curFn
}
|
[
"func",
"(",
"rl",
"*",
"RotateLogs",
")",
"CurrentFileName",
"(",
")",
"string",
"{",
"rl",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"rl",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"rl",
".",
"curFn",
"\n",
"}"
] |
// CurrentFileName returns the current file name that
// the RotateLogs object is writing to
|
[
"CurrentFileName",
"returns",
"the",
"current",
"file",
"name",
"that",
"the",
"RotateLogs",
"object",
"is",
"writing",
"to"
] |
4ce522c92b91beadfd4c77f75dcc06ffe97cf9c6
|
https://github.com/lestrrat-go/file-rotatelogs/blob/4ce522c92b91beadfd4c77f75dcc06ffe97cf9c6/rotatelogs.go#L203-L207
|
14,889 |
lestrrat-go/file-rotatelogs
|
rotatelogs.go
|
Rotate
|
func (rl *RotateLogs) Rotate() error {
rl.mutex.Lock()
defer rl.mutex.Unlock()
if _, err := rl.getWriter_nolock(true, true); err != nil {
return err
}
return nil
}
|
go
|
func (rl *RotateLogs) Rotate() error {
rl.mutex.Lock()
defer rl.mutex.Unlock()
if _, err := rl.getWriter_nolock(true, true); err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"rl",
"*",
"RotateLogs",
")",
"Rotate",
"(",
")",
"error",
"{",
"rl",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"rl",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"rl",
".",
"getWriter_nolock",
"(",
"true",
",",
"true",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Rotate forcefully rotates the log files. If the generated file name
// clash because file already exists, a numeric suffix of the form
// ".1", ".2", ".3" and so forth are appended to the end of the log file
//
// Thie method can be used in conjunction with a signal handler so to
// emulate servers that generate new log files when they receive a
// SIGHUP
|
[
"Rotate",
"forcefully",
"rotates",
"the",
"log",
"files",
".",
"If",
"the",
"generated",
"file",
"name",
"clash",
"because",
"file",
"already",
"exists",
"a",
"numeric",
"suffix",
"of",
"the",
"form",
".",
"1",
".",
"2",
".",
"3",
"and",
"so",
"forth",
"are",
"appended",
"to",
"the",
"end",
"of",
"the",
"log",
"file",
"Thie",
"method",
"can",
"be",
"used",
"in",
"conjunction",
"with",
"a",
"signal",
"handler",
"so",
"to",
"emulate",
"servers",
"that",
"generate",
"new",
"log",
"files",
"when",
"they",
"receive",
"a",
"SIGHUP"
] |
4ce522c92b91beadfd4c77f75dcc06ffe97cf9c6
|
https://github.com/lestrrat-go/file-rotatelogs/blob/4ce522c92b91beadfd4c77f75dcc06ffe97cf9c6/rotatelogs.go#L236-L243
|
14,890 |
lestrrat-go/file-rotatelogs
|
rotatelogs.go
|
Close
|
func (rl *RotateLogs) Close() error {
rl.mutex.Lock()
defer rl.mutex.Unlock()
if rl.outFh == nil {
return nil
}
rl.outFh.Close()
rl.outFh = nil
return nil
}
|
go
|
func (rl *RotateLogs) Close() error {
rl.mutex.Lock()
defer rl.mutex.Unlock()
if rl.outFh == nil {
return nil
}
rl.outFh.Close()
rl.outFh = nil
return nil
}
|
[
"func",
"(",
"rl",
"*",
"RotateLogs",
")",
"Close",
"(",
")",
"error",
"{",
"rl",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"rl",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"rl",
".",
"outFh",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"rl",
".",
"outFh",
".",
"Close",
"(",
")",
"\n",
"rl",
".",
"outFh",
"=",
"nil",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Close satisfies the io.Closer interface. You must
// call this method if you performed any writes to
// the object.
|
[
"Close",
"satisfies",
"the",
"io",
".",
"Closer",
"interface",
".",
"You",
"must",
"call",
"this",
"method",
"if",
"you",
"performed",
"any",
"writes",
"to",
"the",
"object",
"."
] |
4ce522c92b91beadfd4c77f75dcc06ffe97cf9c6
|
https://github.com/lestrrat-go/file-rotatelogs/blob/4ce522c92b91beadfd4c77f75dcc06ffe97cf9c6/rotatelogs.go#L335-L346
|
14,891 |
kataras/golog
|
level.go
|
Text
|
func (m *LevelMetadata) Text(enableColor bool) string {
if enableColor {
return m.ColorfulText
}
return m.RawText
}
|
go
|
func (m *LevelMetadata) Text(enableColor bool) string {
if enableColor {
return m.ColorfulText
}
return m.RawText
}
|
[
"func",
"(",
"m",
"*",
"LevelMetadata",
")",
"Text",
"(",
"enableColor",
"bool",
")",
"string",
"{",
"if",
"enableColor",
"{",
"return",
"m",
".",
"ColorfulText",
"\n",
"}",
"\n",
"return",
"m",
".",
"RawText",
"\n",
"}"
] |
// Text returns the text that should be
// prepended to the log message when a specific
// log level is being written.
|
[
"Text",
"returns",
"the",
"text",
"that",
"should",
"be",
"prepended",
"to",
"the",
"log",
"message",
"when",
"a",
"specific",
"log",
"level",
"is",
"being",
"written",
"."
] |
03be101463868edc5a81f094fc68a5f6c1b5503a
|
https://github.com/kataras/golog/blob/03be101463868edc5a81f094fc68a5f6c1b5503a/level.go#L116-L121
|
14,892 |
kataras/golog
|
logger.go
|
New
|
func New() *Logger {
return &Logger{
Level: InfoLevel,
TimeFormat: "2006/01/02 15:04",
NewLine: true,
Printer: pio.NewPrinter("", os.Stdout).EnableDirectOutput().Hijack(logHijacker),
children: newLoggerMap(),
}
}
|
go
|
func New() *Logger {
return &Logger{
Level: InfoLevel,
TimeFormat: "2006/01/02 15:04",
NewLine: true,
Printer: pio.NewPrinter("", os.Stdout).EnableDirectOutput().Hijack(logHijacker),
children: newLoggerMap(),
}
}
|
[
"func",
"New",
"(",
")",
"*",
"Logger",
"{",
"return",
"&",
"Logger",
"{",
"Level",
":",
"InfoLevel",
",",
"TimeFormat",
":",
"\"",
"\"",
",",
"NewLine",
":",
"true",
",",
"Printer",
":",
"pio",
".",
"NewPrinter",
"(",
"\"",
"\"",
",",
"os",
".",
"Stdout",
")",
".",
"EnableDirectOutput",
"(",
")",
".",
"Hijack",
"(",
"logHijacker",
")",
",",
"children",
":",
"newLoggerMap",
"(",
")",
",",
"}",
"\n",
"}"
] |
// New returns a new golog with a default output to `os.Stdout`
// and level to `InfoLevel`.
|
[
"New",
"returns",
"a",
"new",
"golog",
"with",
"a",
"default",
"output",
"to",
"os",
".",
"Stdout",
"and",
"level",
"to",
"InfoLevel",
"."
] |
03be101463868edc5a81f094fc68a5f6c1b5503a
|
https://github.com/kataras/golog/blob/03be101463868edc5a81f094fc68a5f6c1b5503a/logger.go#L51-L59
|
14,893 |
kataras/golog
|
logger.go
|
acquireLog
|
func (l *Logger) acquireLog(level Level, msg string, withPrintln bool) *Log {
log, ok := l.logs.Get().(*Log)
if !ok {
log = &Log{
Logger: l,
}
}
log.NewLine = withPrintln
log.Time = time.Now()
log.Level = level
log.Message = msg
return log
}
|
go
|
func (l *Logger) acquireLog(level Level, msg string, withPrintln bool) *Log {
log, ok := l.logs.Get().(*Log)
if !ok {
log = &Log{
Logger: l,
}
}
log.NewLine = withPrintln
log.Time = time.Now()
log.Level = level
log.Message = msg
return log
}
|
[
"func",
"(",
"l",
"*",
"Logger",
")",
"acquireLog",
"(",
"level",
"Level",
",",
"msg",
"string",
",",
"withPrintln",
"bool",
")",
"*",
"Log",
"{",
"log",
",",
"ok",
":=",
"l",
".",
"logs",
".",
"Get",
"(",
")",
".",
"(",
"*",
"Log",
")",
"\n",
"if",
"!",
"ok",
"{",
"log",
"=",
"&",
"Log",
"{",
"Logger",
":",
"l",
",",
"}",
"\n",
"}",
"\n",
"log",
".",
"NewLine",
"=",
"withPrintln",
"\n",
"log",
".",
"Time",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"log",
".",
"Level",
"=",
"level",
"\n",
"log",
".",
"Message",
"=",
"msg",
"\n",
"return",
"log",
"\n",
"}"
] |
// acquireLog returns a new log fom the pool.
|
[
"acquireLog",
"returns",
"a",
"new",
"log",
"fom",
"the",
"pool",
"."
] |
03be101463868edc5a81f094fc68a5f6c1b5503a
|
https://github.com/kataras/golog/blob/03be101463868edc5a81f094fc68a5f6c1b5503a/logger.go#L62-L74
|
14,894 |
kataras/golog
|
logger.go
|
SetOutput
|
func (l *Logger) SetOutput(w io.Writer) *Logger {
l.Printer.SetOutput(w)
return l
}
|
go
|
func (l *Logger) SetOutput(w io.Writer) *Logger {
l.Printer.SetOutput(w)
return l
}
|
[
"func",
"(",
"l",
"*",
"Logger",
")",
"SetOutput",
"(",
"w",
"io",
".",
"Writer",
")",
"*",
"Logger",
"{",
"l",
".",
"Printer",
".",
"SetOutput",
"(",
"w",
")",
"\n",
"return",
"l",
"\n",
"}"
] |
// SetOutput overrides the Logger's Printer's Output with another `io.Writer`.
//
// Returns itself.
|
[
"SetOutput",
"overrides",
"the",
"Logger",
"s",
"Printer",
"s",
"Output",
"with",
"another",
"io",
".",
"Writer",
".",
"Returns",
"itself",
"."
] |
03be101463868edc5a81f094fc68a5f6c1b5503a
|
https://github.com/kataras/golog/blob/03be101463868edc5a81f094fc68a5f6c1b5503a/logger.go#L118-L121
|
14,895 |
kataras/golog
|
logger.go
|
SetPrefix
|
func (l *Logger) SetPrefix(s string) *Logger {
l.mu.Lock()
l.Prefix = []byte(s)
l.mu.Unlock()
return l
}
|
go
|
func (l *Logger) SetPrefix(s string) *Logger {
l.mu.Lock()
l.Prefix = []byte(s)
l.mu.Unlock()
return l
}
|
[
"func",
"(",
"l",
"*",
"Logger",
")",
"SetPrefix",
"(",
"s",
"string",
")",
"*",
"Logger",
"{",
"l",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"Prefix",
"=",
"[",
"]",
"byte",
"(",
"s",
")",
"\n",
"l",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"l",
"\n",
"}"
] |
// SetPrefix sets a prefix for this "l" Logger.
//
// The prefix is the first space-separated
// word that is being presented to the output.
// It's written even before the log level text.
//
// Returns itself.
|
[
"SetPrefix",
"sets",
"a",
"prefix",
"for",
"this",
"l",
"Logger",
".",
"The",
"prefix",
"is",
"the",
"first",
"space",
"-",
"separated",
"word",
"that",
"is",
"being",
"presented",
"to",
"the",
"output",
".",
"It",
"s",
"written",
"even",
"before",
"the",
"log",
"level",
"text",
".",
"Returns",
"itself",
"."
] |
03be101463868edc5a81f094fc68a5f6c1b5503a
|
https://github.com/kataras/golog/blob/03be101463868edc5a81f094fc68a5f6c1b5503a/logger.go#L141-L146
|
14,896 |
kataras/golog
|
logger.go
|
SetTimeFormat
|
func (l *Logger) SetTimeFormat(s string) *Logger {
l.mu.Lock()
l.TimeFormat = s
l.mu.Unlock()
return l
}
|
go
|
func (l *Logger) SetTimeFormat(s string) *Logger {
l.mu.Lock()
l.TimeFormat = s
l.mu.Unlock()
return l
}
|
[
"func",
"(",
"l",
"*",
"Logger",
")",
"SetTimeFormat",
"(",
"s",
"string",
")",
"*",
"Logger",
"{",
"l",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"TimeFormat",
"=",
"s",
"\n",
"l",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"l",
"\n",
"}"
] |
// SetTimeFormat sets time format for logs,
// if "s" is empty then time representation will be off.
//
// Returns itself.
|
[
"SetTimeFormat",
"sets",
"time",
"format",
"for",
"logs",
"if",
"s",
"is",
"empty",
"then",
"time",
"representation",
"will",
"be",
"off",
".",
"Returns",
"itself",
"."
] |
03be101463868edc5a81f094fc68a5f6c1b5503a
|
https://github.com/kataras/golog/blob/03be101463868edc5a81f094fc68a5f6c1b5503a/logger.go#L152-L158
|
14,897 |
kataras/golog
|
logger.go
|
DisableNewLine
|
func (l *Logger) DisableNewLine() *Logger {
l.mu.Lock()
l.NewLine = false
l.mu.Unlock()
return l
}
|
go
|
func (l *Logger) DisableNewLine() *Logger {
l.mu.Lock()
l.NewLine = false
l.mu.Unlock()
return l
}
|
[
"func",
"(",
"l",
"*",
"Logger",
")",
"DisableNewLine",
"(",
")",
"*",
"Logger",
"{",
"l",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"NewLine",
"=",
"false",
"\n",
"l",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"l",
"\n",
"}"
] |
// DisableNewLine disables the new line suffix on every log function, even the `F`'s,
// the caller should add "\n" to the log message manually after this call.
//
// Returns itself.
|
[
"DisableNewLine",
"disables",
"the",
"new",
"line",
"suffix",
"on",
"every",
"log",
"function",
"even",
"the",
"F",
"s",
"the",
"caller",
"should",
"add",
"\\",
"n",
"to",
"the",
"log",
"message",
"manually",
"after",
"this",
"call",
".",
"Returns",
"itself",
"."
] |
03be101463868edc5a81f094fc68a5f6c1b5503a
|
https://github.com/kataras/golog/blob/03be101463868edc5a81f094fc68a5f6c1b5503a/logger.go#L164-L170
|
14,898 |
kataras/golog
|
logger.go
|
Print
|
func (l *Logger) Print(v ...interface{}) {
l.print(DisableLevel, fmt.Sprint(v...), l.NewLine)
}
|
go
|
func (l *Logger) Print(v ...interface{}) {
l.print(DisableLevel, fmt.Sprint(v...), l.NewLine)
}
|
[
"func",
"(",
"l",
"*",
"Logger",
")",
"Print",
"(",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"print",
"(",
"DisableLevel",
",",
"fmt",
".",
"Sprint",
"(",
"v",
"...",
")",
",",
"l",
".",
"NewLine",
")",
"\n",
"}"
] |
// Print prints a log message without levels and colors.
|
[
"Print",
"prints",
"a",
"log",
"message",
"without",
"levels",
"and",
"colors",
"."
] |
03be101463868edc5a81f094fc68a5f6c1b5503a
|
https://github.com/kataras/golog/blob/03be101463868edc5a81f094fc68a5f6c1b5503a/logger.go#L219-L221
|
14,899 |
kataras/golog
|
logger.go
|
Println
|
func (l *Logger) Println(v ...interface{}) {
l.print(DisableLevel, fmt.Sprint(v...), true)
}
|
go
|
func (l *Logger) Println(v ...interface{}) {
l.print(DisableLevel, fmt.Sprint(v...), true)
}
|
[
"func",
"(",
"l",
"*",
"Logger",
")",
"Println",
"(",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"print",
"(",
"DisableLevel",
",",
"fmt",
".",
"Sprint",
"(",
"v",
"...",
")",
",",
"true",
")",
"\n",
"}"
] |
// Println prints a log message without levels and colors.
// It adds a new line at the end, it overrides the `NewLine` option.
|
[
"Println",
"prints",
"a",
"log",
"message",
"without",
"levels",
"and",
"colors",
".",
"It",
"adds",
"a",
"new",
"line",
"at",
"the",
"end",
"it",
"overrides",
"the",
"NewLine",
"option",
"."
] |
03be101463868edc5a81f094fc68a5f6c1b5503a
|
https://github.com/kataras/golog/blob/03be101463868edc5a81f094fc68a5f6c1b5503a/logger.go#L230-L232
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.