repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
coreos/ignition
internal/exec/util/file.go
getFileOwnerAndMode
func getFileOwnerAndMode(path string) (int, int, os.FileMode) { finfo, err := os.Stat(path) if err != nil { return 0, 0, 0 } return int(finfo.Sys().(*syscall.Stat_t).Uid), int(finfo.Sys().(*syscall.Stat_t).Gid), finfo.Mode() }
go
func getFileOwnerAndMode(path string) (int, int, os.FileMode) { finfo, err := os.Stat(path) if err != nil { return 0, 0, 0 } return int(finfo.Sys().(*syscall.Stat_t).Uid), int(finfo.Sys().(*syscall.Stat_t).Gid), finfo.Mode() }
[ "func", "getFileOwnerAndMode", "(", "path", "string", ")", "(", "int", ",", "int", ",", "os", ".", "FileMode", ")", "{", "finfo", ",", "err", ":=", "os", ".", "Stat", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0", ",", "0", "\n", "}", "\n", "return", "int", "(", "finfo", ".", "Sys", "(", ")", ".", "(", "*", "syscall", ".", "Stat_t", ")", ".", "Uid", ")", ",", "int", "(", "finfo", ".", "Sys", "(", ")", ".", "(", "*", "syscall", ".", "Stat_t", ")", ".", "Gid", ")", ",", "finfo", ".", "Mode", "(", ")", "\n", "}" ]
// getFileOwner will return the uid and gid for the file at a given path. If the // file doesn't exist, or some other error is encountered when running stat on // the path, 0, 0, and 0 will be returned.
[ "getFileOwner", "will", "return", "the", "uid", "and", "gid", "for", "the", "file", "at", "a", "given", "path", ".", "If", "the", "file", "doesn", "t", "exist", "or", "some", "other", "error", "is", "encountered", "when", "running", "stat", "on", "the", "path", "0", "0", "and", "0", "will", "be", "returned", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/file.go#L247-L253
train
coreos/ignition
internal/exec/util/file.go
ResolveNodeUidAndGid
func (u Util) ResolveNodeUidAndGid(n types.Node, defaultUid, defaultGid int) (int, int, error) { var err error uid, gid := defaultUid, defaultGid if n.User.ID != nil { uid = *n.User.ID } else if n.User.Name != nil && *n.User.Name != "" { uid, err = u.getUserID(*n.User.Name) if err != nil { return 0, 0, err } } if n.Group.ID != nil { gid = *n.Group.ID } else if n.Group.Name != nil && *n.Group.Name != "" { gid, err = u.getGroupID(*n.Group.Name) if err != nil { return 0, 0, err } } return uid, gid, nil }
go
func (u Util) ResolveNodeUidAndGid(n types.Node, defaultUid, defaultGid int) (int, int, error) { var err error uid, gid := defaultUid, defaultGid if n.User.ID != nil { uid = *n.User.ID } else if n.User.Name != nil && *n.User.Name != "" { uid, err = u.getUserID(*n.User.Name) if err != nil { return 0, 0, err } } if n.Group.ID != nil { gid = *n.Group.ID } else if n.Group.Name != nil && *n.Group.Name != "" { gid, err = u.getGroupID(*n.Group.Name) if err != nil { return 0, 0, err } } return uid, gid, nil }
[ "func", "(", "u", "Util", ")", "ResolveNodeUidAndGid", "(", "n", "types", ".", "Node", ",", "defaultUid", ",", "defaultGid", "int", ")", "(", "int", ",", "int", ",", "error", ")", "{", "var", "err", "error", "\n", "uid", ",", "gid", ":=", "defaultUid", ",", "defaultGid", "\n\n", "if", "n", ".", "User", ".", "ID", "!=", "nil", "{", "uid", "=", "*", "n", ".", "User", ".", "ID", "\n", "}", "else", "if", "n", ".", "User", ".", "Name", "!=", "nil", "&&", "*", "n", ".", "User", ".", "Name", "!=", "\"", "\"", "{", "uid", ",", "err", "=", "u", ".", "getUserID", "(", "*", "n", ".", "User", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0", ",", "err", "\n", "}", "\n", "}", "\n\n", "if", "n", ".", "Group", ".", "ID", "!=", "nil", "{", "gid", "=", "*", "n", ".", "Group", ".", "ID", "\n", "}", "else", "if", "n", ".", "Group", ".", "Name", "!=", "nil", "&&", "*", "n", ".", "Group", ".", "Name", "!=", "\"", "\"", "{", "gid", ",", "err", "=", "u", ".", "getGroupID", "(", "*", "n", ".", "Group", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0", ",", "err", "\n", "}", "\n", "}", "\n", "return", "uid", ",", "gid", ",", "nil", "\n", "}" ]
// ResolveNodeUidAndGid attempts to convert a types.Node into a concrete uid and // gid. If the node has the User.ID field set, that's used for the uid. If the // node has the User.Name field set, a username -> uid lookup is performed. If // neither are set, it returns the passed in defaultUid. The logic is identical // for gids with equivalent fields.
[ "ResolveNodeUidAndGid", "attempts", "to", "convert", "a", "types", ".", "Node", "into", "a", "concrete", "uid", "and", "gid", ".", "If", "the", "node", "has", "the", "User", ".", "ID", "field", "set", "that", "s", "used", "for", "the", "uid", ".", "If", "the", "node", "has", "the", "User", ".", "Name", "field", "set", "a", "username", "-", ">", "uid", "lookup", "is", "performed", ".", "If", "neither", "are", "set", "it", "returns", "the", "passed", "in", "defaultUid", ".", "The", "logic", "is", "identical", "for", "gids", "with", "equivalent", "fields", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/file.go#L260-L282
train
coreos/ignition
internal/exec/stages/files/units.go
createUnits
func (s *stage) createUnits(config types.Config) error { enabledOneUnit := false for _, unit := range config.Systemd.Units { if err := s.writeSystemdUnit(unit, false); err != nil { return err } if unit.Enabled != nil { if *unit.Enabled { if err := s.Logger.LogOp( func() error { return s.EnableUnit(unit) }, "enabling unit %q", unit.Name, ); err != nil { return err } } else { if err := s.Logger.LogOp( func() error { return s.DisableUnit(unit) }, "disabling unit %q", unit.Name, ); err != nil { return err } } enabledOneUnit = true } if unit.Mask != nil && *unit.Mask { if err := s.Logger.LogOp( func() error { return s.MaskUnit(unit) }, "masking unit %q", unit.Name, ); err != nil { return err } } } // and relabel the preset file itself if we enabled/disabled something if enabledOneUnit { s.relabel(util.PresetPath) } return nil }
go
func (s *stage) createUnits(config types.Config) error { enabledOneUnit := false for _, unit := range config.Systemd.Units { if err := s.writeSystemdUnit(unit, false); err != nil { return err } if unit.Enabled != nil { if *unit.Enabled { if err := s.Logger.LogOp( func() error { return s.EnableUnit(unit) }, "enabling unit %q", unit.Name, ); err != nil { return err } } else { if err := s.Logger.LogOp( func() error { return s.DisableUnit(unit) }, "disabling unit %q", unit.Name, ); err != nil { return err } } enabledOneUnit = true } if unit.Mask != nil && *unit.Mask { if err := s.Logger.LogOp( func() error { return s.MaskUnit(unit) }, "masking unit %q", unit.Name, ); err != nil { return err } } } // and relabel the preset file itself if we enabled/disabled something if enabledOneUnit { s.relabel(util.PresetPath) } return nil }
[ "func", "(", "s", "*", "stage", ")", "createUnits", "(", "config", "types", ".", "Config", ")", "error", "{", "enabledOneUnit", ":=", "false", "\n", "for", "_", ",", "unit", ":=", "range", "config", ".", "Systemd", ".", "Units", "{", "if", "err", ":=", "s", ".", "writeSystemdUnit", "(", "unit", ",", "false", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "unit", ".", "Enabled", "!=", "nil", "{", "if", "*", "unit", ".", "Enabled", "{", "if", "err", ":=", "s", ".", "Logger", ".", "LogOp", "(", "func", "(", ")", "error", "{", "return", "s", ".", "EnableUnit", "(", "unit", ")", "}", ",", "\"", "\"", ",", "unit", ".", "Name", ",", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "else", "{", "if", "err", ":=", "s", ".", "Logger", ".", "LogOp", "(", "func", "(", ")", "error", "{", "return", "s", ".", "DisableUnit", "(", "unit", ")", "}", ",", "\"", "\"", ",", "unit", ".", "Name", ",", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "enabledOneUnit", "=", "true", "\n", "}", "\n", "if", "unit", ".", "Mask", "!=", "nil", "&&", "*", "unit", ".", "Mask", "{", "if", "err", ":=", "s", ".", "Logger", ".", "LogOp", "(", "func", "(", ")", "error", "{", "return", "s", ".", "MaskUnit", "(", "unit", ")", "}", ",", "\"", "\"", ",", "unit", ".", "Name", ",", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "// and relabel the preset file itself if we enabled/disabled something", "if", "enabledOneUnit", "{", "s", ".", "relabel", "(", "util", ".", "PresetPath", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// createUnits creates the units listed under systemd.units.
[ "createUnits", "creates", "the", "units", "listed", "under", "systemd", ".", "units", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/files/units.go#L28-L66
train
coreos/ignition
internal/exec/stages/files/units.go
writeSystemdUnit
func (s *stage) writeSystemdUnit(unit types.Unit, runtime bool) error { // use a different DestDir if it's runtime so it affects our /run (but not // if we're running locally through blackbox tests) u := s.Util if runtime && !distro.BlackboxTesting() { u.DestDir = "/" } return s.Logger.LogOp(func() error { relabeledDropinDir := false for _, dropin := range unit.Dropins { if dropin.Contents == nil || *dropin.Contents == "" { continue } f, err := u.FileFromSystemdUnitDropin(unit, dropin, runtime) if err != nil { s.Logger.Crit("error converting systemd dropin: %v", err) return err } relabelPath := f.Node.Path if !runtime { // trim off prefix since this needs to be relative to the sysroot if !strings.HasPrefix(f.Node.Path, s.DestDir) { panic(fmt.Sprintf("Dropin path %s isn't under prefix %s", f.Node.Path, s.DestDir)) } relabelPath = f.Node.Path[len(s.DestDir):] } if err := s.Logger.LogOp( func() error { return u.PerformFetch(f) }, "writing systemd drop-in %q at %q", dropin.Name, f.Node.Path, ); err != nil { return err } if !relabeledDropinDir { s.relabel(filepath.Dir(relabelPath)) relabeledDropinDir = true } } if unit.Contents == nil || *unit.Contents == "" { return nil } f, err := u.FileFromSystemdUnit(unit, runtime) if err != nil { s.Logger.Crit("error converting unit: %v", err) return err } relabelPath := f.Node.Path if !runtime { // trim off prefix since this needs to be relative to the sysroot if !strings.HasPrefix(f.Node.Path, s.DestDir) { panic(fmt.Sprintf("Unit path %s isn't under prefix %s", f.Node.Path, s.DestDir)) } relabelPath = f.Node.Path[len(s.DestDir):] } if err := s.Logger.LogOp( func() error { return u.PerformFetch(f) }, "writing unit %q at %q", unit.Name, f.Node.Path, ); err != nil { return err } s.relabel(relabelPath) return nil }, "processing unit %q", unit.Name) }
go
func (s *stage) writeSystemdUnit(unit types.Unit, runtime bool) error { // use a different DestDir if it's runtime so it affects our /run (but not // if we're running locally through blackbox tests) u := s.Util if runtime && !distro.BlackboxTesting() { u.DestDir = "/" } return s.Logger.LogOp(func() error { relabeledDropinDir := false for _, dropin := range unit.Dropins { if dropin.Contents == nil || *dropin.Contents == "" { continue } f, err := u.FileFromSystemdUnitDropin(unit, dropin, runtime) if err != nil { s.Logger.Crit("error converting systemd dropin: %v", err) return err } relabelPath := f.Node.Path if !runtime { // trim off prefix since this needs to be relative to the sysroot if !strings.HasPrefix(f.Node.Path, s.DestDir) { panic(fmt.Sprintf("Dropin path %s isn't under prefix %s", f.Node.Path, s.DestDir)) } relabelPath = f.Node.Path[len(s.DestDir):] } if err := s.Logger.LogOp( func() error { return u.PerformFetch(f) }, "writing systemd drop-in %q at %q", dropin.Name, f.Node.Path, ); err != nil { return err } if !relabeledDropinDir { s.relabel(filepath.Dir(relabelPath)) relabeledDropinDir = true } } if unit.Contents == nil || *unit.Contents == "" { return nil } f, err := u.FileFromSystemdUnit(unit, runtime) if err != nil { s.Logger.Crit("error converting unit: %v", err) return err } relabelPath := f.Node.Path if !runtime { // trim off prefix since this needs to be relative to the sysroot if !strings.HasPrefix(f.Node.Path, s.DestDir) { panic(fmt.Sprintf("Unit path %s isn't under prefix %s", f.Node.Path, s.DestDir)) } relabelPath = f.Node.Path[len(s.DestDir):] } if err := s.Logger.LogOp( func() error { return u.PerformFetch(f) }, "writing unit %q at %q", unit.Name, f.Node.Path, ); err != nil { return err } s.relabel(relabelPath) return nil }, "processing unit %q", unit.Name) }
[ "func", "(", "s", "*", "stage", ")", "writeSystemdUnit", "(", "unit", "types", ".", "Unit", ",", "runtime", "bool", ")", "error", "{", "// use a different DestDir if it's runtime so it affects our /run (but not", "// if we're running locally through blackbox tests)", "u", ":=", "s", ".", "Util", "\n", "if", "runtime", "&&", "!", "distro", ".", "BlackboxTesting", "(", ")", "{", "u", ".", "DestDir", "=", "\"", "\"", "\n", "}", "\n\n", "return", "s", ".", "Logger", ".", "LogOp", "(", "func", "(", ")", "error", "{", "relabeledDropinDir", ":=", "false", "\n", "for", "_", ",", "dropin", ":=", "range", "unit", ".", "Dropins", "{", "if", "dropin", ".", "Contents", "==", "nil", "||", "*", "dropin", ".", "Contents", "==", "\"", "\"", "{", "continue", "\n", "}", "\n", "f", ",", "err", ":=", "u", ".", "FileFromSystemdUnitDropin", "(", "unit", ",", "dropin", ",", "runtime", ")", "\n", "if", "err", "!=", "nil", "{", "s", ".", "Logger", ".", "Crit", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "relabelPath", ":=", "f", ".", "Node", ".", "Path", "\n", "if", "!", "runtime", "{", "// trim off prefix since this needs to be relative to the sysroot", "if", "!", "strings", ".", "HasPrefix", "(", "f", ".", "Node", ".", "Path", ",", "s", ".", "DestDir", ")", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "f", ".", "Node", ".", "Path", ",", "s", ".", "DestDir", ")", ")", "\n", "}", "\n", "relabelPath", "=", "f", ".", "Node", ".", "Path", "[", "len", "(", "s", ".", "DestDir", ")", ":", "]", "\n", "}", "\n", "if", "err", ":=", "s", ".", "Logger", ".", "LogOp", "(", "func", "(", ")", "error", "{", "return", "u", ".", "PerformFetch", "(", "f", ")", "}", ",", "\"", "\"", ",", "dropin", ".", "Name", ",", "f", ".", "Node", ".", "Path", ",", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "relabeledDropinDir", "{", "s", ".", "relabel", "(", "filepath", ".", "Dir", "(", "relabelPath", ")", ")", "\n", "relabeledDropinDir", "=", "true", "\n", "}", "\n", "}", "\n\n", "if", "unit", ".", "Contents", "==", "nil", "||", "*", "unit", ".", "Contents", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n\n", "f", ",", "err", ":=", "u", ".", "FileFromSystemdUnit", "(", "unit", ",", "runtime", ")", "\n", "if", "err", "!=", "nil", "{", "s", ".", "Logger", ".", "Crit", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "relabelPath", ":=", "f", ".", "Node", ".", "Path", "\n", "if", "!", "runtime", "{", "// trim off prefix since this needs to be relative to the sysroot", "if", "!", "strings", ".", "HasPrefix", "(", "f", ".", "Node", ".", "Path", ",", "s", ".", "DestDir", ")", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "f", ".", "Node", ".", "Path", ",", "s", ".", "DestDir", ")", ")", "\n", "}", "\n", "relabelPath", "=", "f", ".", "Node", ".", "Path", "[", "len", "(", "s", ".", "DestDir", ")", ":", "]", "\n", "}", "\n", "if", "err", ":=", "s", ".", "Logger", ".", "LogOp", "(", "func", "(", ")", "error", "{", "return", "u", ".", "PerformFetch", "(", "f", ")", "}", ",", "\"", "\"", ",", "unit", ".", "Name", ",", "f", ".", "Node", ".", "Path", ",", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "s", ".", "relabel", "(", "relabelPath", ")", "\n\n", "return", "nil", "\n", "}", ",", "\"", "\"", ",", "unit", ".", "Name", ")", "\n", "}" ]
// writeSystemdUnit creates the specified unit and any dropins for that unit. // If the contents of the unit or are empty, the unit is not created. The same // applies to the unit's dropins.
[ "writeSystemdUnit", "creates", "the", "specified", "unit", "and", "any", "dropins", "for", "that", "unit", ".", "If", "the", "contents", "of", "the", "unit", "or", "are", "empty", "the", "unit", "is", "not", "created", ".", "The", "same", "applies", "to", "the", "unit", "s", "dropins", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/files/units.go#L71-L137
train
coreos/ignition
internal/exec/util/blkid.go
cResultToErr
func cResultToErr(res C.result_t, device string) error { switch res { case C.RESULT_OK: return nil case C.RESULT_OPEN_FAILED: return fmt.Errorf("failed to open %q", device) case C.RESULT_PROBE_FAILED: return fmt.Errorf("failed to probe %q", device) case C.RESULT_LOOKUP_FAILED: return fmt.Errorf("failed to lookup attribute on %q", device) case C.RESULT_NO_PARTITION_TABLE: return fmt.Errorf("no partition table found on %q", device) case C.RESULT_BAD_INDEX: return fmt.Errorf("bad partition index specified for device %q", device) case C.RESULT_GET_PARTLIST_FAILED: return fmt.Errorf("failed to get list of partitions on %q", device) case C.RESULT_DISK_HAS_NO_TYPE: return fmt.Errorf("%q has no type string, despite having a partition table", device) case C.RESULT_DISK_NOT_GPT: return fmt.Errorf("%q is not a gpt disk", device) case C.RESULT_BAD_PARAMS: return fmt.Errorf("internal error. bad params passed while handling %q", device) case C.RESULT_OVERFLOW: return fmt.Errorf("internal error. libblkid returned impossibly large value when handling %q", device) case C.RESULT_NO_TOPO: return fmt.Errorf("failed to get topology information for %q", device) case C.RESULT_NO_SECTOR_SIZE: return fmt.Errorf("failed to get logical sector size for %q", device) case C.RESULT_BAD_SECTOR_SIZE: return fmt.Errorf("logical sector size for %q was not a multiple of 512", device) default: return fmt.Errorf("Unknown error while handling %q. err code: %d", device, res) } }
go
func cResultToErr(res C.result_t, device string) error { switch res { case C.RESULT_OK: return nil case C.RESULT_OPEN_FAILED: return fmt.Errorf("failed to open %q", device) case C.RESULT_PROBE_FAILED: return fmt.Errorf("failed to probe %q", device) case C.RESULT_LOOKUP_FAILED: return fmt.Errorf("failed to lookup attribute on %q", device) case C.RESULT_NO_PARTITION_TABLE: return fmt.Errorf("no partition table found on %q", device) case C.RESULT_BAD_INDEX: return fmt.Errorf("bad partition index specified for device %q", device) case C.RESULT_GET_PARTLIST_FAILED: return fmt.Errorf("failed to get list of partitions on %q", device) case C.RESULT_DISK_HAS_NO_TYPE: return fmt.Errorf("%q has no type string, despite having a partition table", device) case C.RESULT_DISK_NOT_GPT: return fmt.Errorf("%q is not a gpt disk", device) case C.RESULT_BAD_PARAMS: return fmt.Errorf("internal error. bad params passed while handling %q", device) case C.RESULT_OVERFLOW: return fmt.Errorf("internal error. libblkid returned impossibly large value when handling %q", device) case C.RESULT_NO_TOPO: return fmt.Errorf("failed to get topology information for %q", device) case C.RESULT_NO_SECTOR_SIZE: return fmt.Errorf("failed to get logical sector size for %q", device) case C.RESULT_BAD_SECTOR_SIZE: return fmt.Errorf("logical sector size for %q was not a multiple of 512", device) default: return fmt.Errorf("Unknown error while handling %q. err code: %d", device, res) } }
[ "func", "cResultToErr", "(", "res", "C", ".", "result_t", ",", "device", "string", ")", "error", "{", "switch", "res", "{", "case", "C", ".", "RESULT_OK", ":", "return", "nil", "\n", "case", "C", ".", "RESULT_OPEN_FAILED", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "device", ")", "\n", "case", "C", ".", "RESULT_PROBE_FAILED", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "device", ")", "\n", "case", "C", ".", "RESULT_LOOKUP_FAILED", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "device", ")", "\n", "case", "C", ".", "RESULT_NO_PARTITION_TABLE", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "device", ")", "\n", "case", "C", ".", "RESULT_BAD_INDEX", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "device", ")", "\n", "case", "C", ".", "RESULT_GET_PARTLIST_FAILED", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "device", ")", "\n", "case", "C", ".", "RESULT_DISK_HAS_NO_TYPE", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "device", ")", "\n", "case", "C", ".", "RESULT_DISK_NOT_GPT", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "device", ")", "\n", "case", "C", ".", "RESULT_BAD_PARAMS", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "device", ")", "\n", "case", "C", ".", "RESULT_OVERFLOW", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "device", ")", "\n", "case", "C", ".", "RESULT_NO_TOPO", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "device", ")", "\n", "case", "C", ".", "RESULT_NO_SECTOR_SIZE", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "device", ")", "\n", "case", "C", ".", "RESULT_BAD_SECTOR_SIZE", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "device", ")", "\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "device", ",", "res", ")", "\n", "}", "\n", "}" ]
// cResultToErr takes a result_t from the blkid c code and a device it was operating on // and returns a golang error describing the result code.
[ "cResultToErr", "takes", "a", "result_t", "from", "the", "blkid", "c", "code", "and", "a", "device", "it", "was", "operating", "on", "and", "returns", "a", "golang", "error", "describing", "the", "result", "code", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/blkid.go#L80-L113
train
coreos/ignition
internal/providers/packet/packet.go
PostStatus
func PostStatus(stageName string, f resource.Fetcher, errMsg error) error { f.Logger.Info("POST message to Packet Timeline") // fetch JSON from https://metadata.packet.net/metadata data, err := f.FetchToBuffer(metadataUrl, resource.FetchOptions{ Headers: nil, }) if err != nil { return err } if data == nil { return ErrValidFetchEmptyData } metadata := struct { PhoneHomeURL string `json:"phone_home_url"` }{} err = json.Unmarshal(data, &metadata) if err != nil { return err } phonehomeURL := metadata.PhoneHomeURL // to get phonehome IPv4 phonehomeURL = strings.TrimSuffix(phonehomeURL, "/phone-home") // POST Message to phonehome IP postMessageURL := phonehomeURL + "/events" return postMessage(stageName, errMsg, postMessageURL) }
go
func PostStatus(stageName string, f resource.Fetcher, errMsg error) error { f.Logger.Info("POST message to Packet Timeline") // fetch JSON from https://metadata.packet.net/metadata data, err := f.FetchToBuffer(metadataUrl, resource.FetchOptions{ Headers: nil, }) if err != nil { return err } if data == nil { return ErrValidFetchEmptyData } metadata := struct { PhoneHomeURL string `json:"phone_home_url"` }{} err = json.Unmarshal(data, &metadata) if err != nil { return err } phonehomeURL := metadata.PhoneHomeURL // to get phonehome IPv4 phonehomeURL = strings.TrimSuffix(phonehomeURL, "/phone-home") // POST Message to phonehome IP postMessageURL := phonehomeURL + "/events" return postMessage(stageName, errMsg, postMessageURL) }
[ "func", "PostStatus", "(", "stageName", "string", ",", "f", "resource", ".", "Fetcher", ",", "errMsg", "error", ")", "error", "{", "f", ".", "Logger", ".", "Info", "(", "\"", "\"", ")", "\n", "// fetch JSON from https://metadata.packet.net/metadata", "data", ",", "err", ":=", "f", ".", "FetchToBuffer", "(", "metadataUrl", ",", "resource", ".", "FetchOptions", "{", "Headers", ":", "nil", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "data", "==", "nil", "{", "return", "ErrValidFetchEmptyData", "\n", "}", "\n", "metadata", ":=", "struct", "{", "PhoneHomeURL", "string", "`json:\"phone_home_url\"`", "\n", "}", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "metadata", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "phonehomeURL", ":=", "metadata", ".", "PhoneHomeURL", "\n", "// to get phonehome IPv4", "phonehomeURL", "=", "strings", ".", "TrimSuffix", "(", "phonehomeURL", ",", "\"", "\"", ")", "\n", "// POST Message to phonehome IP", "postMessageURL", ":=", "phonehomeURL", "+", "\"", "\"", "\n\n", "return", "postMessage", "(", "stageName", ",", "errMsg", ",", "postMessageURL", ")", "\n", "}" ]
// PostStatus posts a message that will show on the Packet Instance Timeline
[ "PostStatus", "posts", "a", "message", "that", "will", "show", "on", "the", "Packet", "Instance", "Timeline" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/providers/packet/packet.go#L70-L96
train
coreos/ignition
internal/providers/packet/packet.go
postMessage
func postMessage(stageName string, e error, url string) error { stageName = "[" + stageName + "]" type mStruct struct { State string `json:"state"` Message string `json:"message"` } m := mStruct{} if e != nil { m = mStruct{ State: "failed", Message: stageName + " Ignition error: " + e.Error(), } } else { m = mStruct{ State: "running", Message: stageName + " Ignition status: finished successfully", } } messageJSON, err := json.Marshal(m) if err != nil { return err } postReq, err := http.NewRequest("POST", url, bytes.NewBuffer(messageJSON)) if err != nil { return err } postReq.Header.Set("Content-Type", "application/json") client := &http.Client{} respPost, err := client.Do(postReq) if err != nil { return err } defer respPost.Body.Close() return err }
go
func postMessage(stageName string, e error, url string) error { stageName = "[" + stageName + "]" type mStruct struct { State string `json:"state"` Message string `json:"message"` } m := mStruct{} if e != nil { m = mStruct{ State: "failed", Message: stageName + " Ignition error: " + e.Error(), } } else { m = mStruct{ State: "running", Message: stageName + " Ignition status: finished successfully", } } messageJSON, err := json.Marshal(m) if err != nil { return err } postReq, err := http.NewRequest("POST", url, bytes.NewBuffer(messageJSON)) if err != nil { return err } postReq.Header.Set("Content-Type", "application/json") client := &http.Client{} respPost, err := client.Do(postReq) if err != nil { return err } defer respPost.Body.Close() return err }
[ "func", "postMessage", "(", "stageName", "string", ",", "e", "error", ",", "url", "string", ")", "error", "{", "stageName", "=", "\"", "\"", "+", "stageName", "+", "\"", "\"", "\n\n", "type", "mStruct", "struct", "{", "State", "string", "`json:\"state\"`", "\n", "Message", "string", "`json:\"message\"`", "\n", "}", "\n", "m", ":=", "mStruct", "{", "}", "\n", "if", "e", "!=", "nil", "{", "m", "=", "mStruct", "{", "State", ":", "\"", "\"", ",", "Message", ":", "stageName", "+", "\"", "\"", "+", "e", ".", "Error", "(", ")", ",", "}", "\n", "}", "else", "{", "m", "=", "mStruct", "{", "State", ":", "\"", "\"", ",", "Message", ":", "stageName", "+", "\"", "\"", ",", "}", "\n", "}", "\n", "messageJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "m", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "postReq", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "url", ",", "bytes", ".", "NewBuffer", "(", "messageJSON", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "postReq", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "client", ":=", "&", "http", ".", "Client", "{", "}", "\n", "respPost", ",", "err", ":=", "client", ".", "Do", "(", "postReq", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "respPost", ".", "Body", ".", "Close", "(", ")", "\n", "return", "err", "\n", "}" ]
// postMessage makes a post request with the supplied message to the url
[ "postMessage", "makes", "a", "post", "request", "with", "the", "supplied", "message", "to", "the", "url" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/providers/packet/packet.go#L99-L135
train
coreos/ignition
internal/exec/stages/disks/disks.go
waitOnDevices
func (s stage) waitOnDevices(devs []string, ctxt string) error { if err := s.LogOp( func() error { return systemd.WaitOnDevices(devs, ctxt) }, "waiting for devices %v", devs, ); err != nil { return fmt.Errorf("failed to wait on %s devs: %v", ctxt, err) } return nil }
go
func (s stage) waitOnDevices(devs []string, ctxt string) error { if err := s.LogOp( func() error { return systemd.WaitOnDevices(devs, ctxt) }, "waiting for devices %v", devs, ); err != nil { return fmt.Errorf("failed to wait on %s devs: %v", ctxt, err) } return nil }
[ "func", "(", "s", "stage", ")", "waitOnDevices", "(", "devs", "[", "]", "string", ",", "ctxt", "string", ")", "error", "{", "if", "err", ":=", "s", ".", "LogOp", "(", "func", "(", ")", "error", "{", "return", "systemd", ".", "WaitOnDevices", "(", "devs", ",", "ctxt", ")", "}", ",", "\"", "\"", ",", "devs", ",", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ctxt", ",", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// waitOnDevices waits for the devices enumerated in devs as a logged operation // using ctxt for the logging and systemd unit identity.
[ "waitOnDevices", "waits", "for", "the", "devices", "enumerated", "in", "devs", "as", "a", "logged", "operation", "using", "ctxt", "for", "the", "logging", "and", "systemd", "unit", "identity", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/disks/disks.go#L126-L135
train
coreos/ignition
internal/exec/stages/disks/disks.go
createDeviceAliases
func (s stage) createDeviceAliases(devs []string) error { for _, dev := range devs { target, err := util.CreateDeviceAlias(dev) if err != nil { return fmt.Errorf("failed to create device alias for %q: %v", dev, err) } s.Logger.Info("created device alias for %q: %q -> %q", dev, util.DeviceAlias(dev), target) } return nil }
go
func (s stage) createDeviceAliases(devs []string) error { for _, dev := range devs { target, err := util.CreateDeviceAlias(dev) if err != nil { return fmt.Errorf("failed to create device alias for %q: %v", dev, err) } s.Logger.Info("created device alias for %q: %q -> %q", dev, util.DeviceAlias(dev), target) } return nil }
[ "func", "(", "s", "stage", ")", "createDeviceAliases", "(", "devs", "[", "]", "string", ")", "error", "{", "for", "_", ",", "dev", ":=", "range", "devs", "{", "target", ",", "err", ":=", "util", ".", "CreateDeviceAlias", "(", "dev", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dev", ",", "err", ")", "\n", "}", "\n", "s", ".", "Logger", ".", "Info", "(", "\"", "\"", ",", "dev", ",", "util", ".", "DeviceAlias", "(", "dev", ")", ",", "target", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// createDeviceAliases creates device aliases for every device in devs.
[ "createDeviceAliases", "creates", "device", "aliases", "for", "every", "device", "in", "devs", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/disks/disks.go#L138-L148
train
coreos/ignition
internal/exec/stages/disks/disks.go
waitOnDevicesAndCreateAliases
func (s stage) waitOnDevicesAndCreateAliases(devs []string, ctxt string) error { if err := s.waitOnDevices(devs, ctxt); err != nil { return err } if err := s.createDeviceAliases(devs); err != nil { return err } return nil }
go
func (s stage) waitOnDevicesAndCreateAliases(devs []string, ctxt string) error { if err := s.waitOnDevices(devs, ctxt); err != nil { return err } if err := s.createDeviceAliases(devs); err != nil { return err } return nil }
[ "func", "(", "s", "stage", ")", "waitOnDevicesAndCreateAliases", "(", "devs", "[", "]", "string", ",", "ctxt", "string", ")", "error", "{", "if", "err", ":=", "s", ".", "waitOnDevices", "(", "devs", ",", "ctxt", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "s", ".", "createDeviceAliases", "(", "devs", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// waitOnDevicesAndCreateAliases simply wraps waitOnDevices and createDeviceAliases.
[ "waitOnDevicesAndCreateAliases", "simply", "wraps", "waitOnDevices", "and", "createDeviceAliases", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/disks/disks.go#L151-L161
train
coreos/ignition
config/v3_1_experimental/config.go
Parse
func Parse(rawConfig []byte) (types.Config, report.Report, error) { if isEmpty(rawConfig) { return types.Config{}, report.Report{}, errors.ErrEmpty } var config types.Config if rpt, err := util.HandleParseErrors(rawConfig, &config); err != nil { return types.Config{}, rpt, err } version, err := semver.NewVersion(config.Ignition.Version) if err != nil || *version != types.MaxVersion { return types.Config{}, report.Report{}, errors.ErrUnknownVersion } rpt := validate.ValidateConfig(rawConfig, config) if rpt.IsFatal() { return types.Config{}, rpt, errors.ErrInvalid } return config, rpt, nil }
go
func Parse(rawConfig []byte) (types.Config, report.Report, error) { if isEmpty(rawConfig) { return types.Config{}, report.Report{}, errors.ErrEmpty } var config types.Config if rpt, err := util.HandleParseErrors(rawConfig, &config); err != nil { return types.Config{}, rpt, err } version, err := semver.NewVersion(config.Ignition.Version) if err != nil || *version != types.MaxVersion { return types.Config{}, report.Report{}, errors.ErrUnknownVersion } rpt := validate.ValidateConfig(rawConfig, config) if rpt.IsFatal() { return types.Config{}, rpt, errors.ErrInvalid } return config, rpt, nil }
[ "func", "Parse", "(", "rawConfig", "[", "]", "byte", ")", "(", "types", ".", "Config", ",", "report", ".", "Report", ",", "error", ")", "{", "if", "isEmpty", "(", "rawConfig", ")", "{", "return", "types", ".", "Config", "{", "}", ",", "report", ".", "Report", "{", "}", ",", "errors", ".", "ErrEmpty", "\n", "}", "\n\n", "var", "config", "types", ".", "Config", "\n", "if", "rpt", ",", "err", ":=", "util", ".", "HandleParseErrors", "(", "rawConfig", ",", "&", "config", ")", ";", "err", "!=", "nil", "{", "return", "types", ".", "Config", "{", "}", ",", "rpt", ",", "err", "\n", "}", "\n\n", "version", ",", "err", ":=", "semver", ".", "NewVersion", "(", "config", ".", "Ignition", ".", "Version", ")", "\n\n", "if", "err", "!=", "nil", "||", "*", "version", "!=", "types", ".", "MaxVersion", "{", "return", "types", ".", "Config", "{", "}", ",", "report", ".", "Report", "{", "}", ",", "errors", ".", "ErrUnknownVersion", "\n", "}", "\n\n", "rpt", ":=", "validate", ".", "ValidateConfig", "(", "rawConfig", ",", "config", ")", "\n", "if", "rpt", ".", "IsFatal", "(", ")", "{", "return", "types", ".", "Config", "{", "}", ",", "rpt", ",", "errors", ".", "ErrInvalid", "\n", "}", "\n\n", "return", "config", ",", "rpt", ",", "nil", "\n", "}" ]
// Parse parses the raw config into a types.Config struct and generates a report of any // errors, warnings, info, and deprecations it encountered
[ "Parse", "parses", "the", "raw", "config", "into", "a", "types", ".", "Config", "struct", "and", "generates", "a", "report", "of", "any", "errors", "warnings", "info", "and", "deprecations", "it", "encountered" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/config/v3_1_experimental/config.go#L41-L63
train
coreos/ignition
config/validate/report/report.go
addFromError
func (r *Report) addFromError(err error, severity entryKind) { if err == nil { return } r.Add(Entry{ Kind: severity, Message: err.Error(), }) }
go
func (r *Report) addFromError(err error, severity entryKind) { if err == nil { return } r.Add(Entry{ Kind: severity, Message: err.Error(), }) }
[ "func", "(", "r", "*", "Report", ")", "addFromError", "(", "err", "error", ",", "severity", "entryKind", ")", "{", "if", "err", "==", "nil", "{", "return", "\n", "}", "\n", "r", ".", "Add", "(", "Entry", "{", "Kind", ":", "severity", ",", "Message", ":", "err", ".", "Error", "(", ")", ",", "}", ")", "\n", "}" ]
// Helpers to cut verbosity
[ "Helpers", "to", "cut", "verbosity" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/config/validate/report/report.go#L47-L55
train
coreos/ignition
config/validate/report/report.go
IsFatal
func (r Report) IsFatal() bool { for _, entry := range r.Entries { if entry.Kind == EntryError { return true } } return false }
go
func (r Report) IsFatal() bool { for _, entry := range r.Entries { if entry.Kind == EntryError { return true } } return false }
[ "func", "(", "r", "Report", ")", "IsFatal", "(", ")", "bool", "{", "for", "_", ",", "entry", ":=", "range", "r", ".", "Entries", "{", "if", "entry", ".", "Kind", "==", "EntryError", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsFatal returns if there were any errors that make the config invalid
[ "IsFatal", "returns", "if", "there", "were", "any", "errors", "that", "make", "the", "config", "invalid" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/config/validate/report/report.go#L132-L139
train
coreos/ignition
config/validate/report/report.go
IsDeprecated
func (r Report) IsDeprecated() bool { for _, entry := range r.Entries { if entry.Kind == EntryDeprecated { return true } } return false }
go
func (r Report) IsDeprecated() bool { for _, entry := range r.Entries { if entry.Kind == EntryDeprecated { return true } } return false }
[ "func", "(", "r", "Report", ")", "IsDeprecated", "(", ")", "bool", "{", "for", "_", ",", "entry", ":=", "range", "r", ".", "Entries", "{", "if", "entry", ".", "Kind", "==", "EntryDeprecated", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsDeprecated returns if the report has deprecations
[ "IsDeprecated", "returns", "if", "the", "report", "has", "deprecations" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/config/validate/report/report.go#L142-L149
train
coreos/ignition
internal/exec/stages/mount/mount.go
checkForNonDirectories
func checkForNonDirectories(path string) error { p := "/" for _, component := range util.SplitPath(path) { p = filepath.Join(p, component) st, err := os.Lstat(p) if err != nil && os.IsNotExist(err) { return nil // nonexistent is ok } else if err != nil { return err } if !st.Mode().IsDir() { return fmt.Errorf("Mount path %q contains non-directory component %q", path, p) } } return nil }
go
func checkForNonDirectories(path string) error { p := "/" for _, component := range util.SplitPath(path) { p = filepath.Join(p, component) st, err := os.Lstat(p) if err != nil && os.IsNotExist(err) { return nil // nonexistent is ok } else if err != nil { return err } if !st.Mode().IsDir() { return fmt.Errorf("Mount path %q contains non-directory component %q", path, p) } } return nil }
[ "func", "checkForNonDirectories", "(", "path", "string", ")", "error", "{", "p", ":=", "\"", "\"", "\n", "for", "_", ",", "component", ":=", "range", "util", ".", "SplitPath", "(", "path", ")", "{", "p", "=", "filepath", ".", "Join", "(", "p", ",", "component", ")", "\n", "st", ",", "err", ":=", "os", ".", "Lstat", "(", "p", ")", "\n", "if", "err", "!=", "nil", "&&", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", "// nonexistent is ok", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "st", ".", "Mode", "(", ")", ".", "IsDir", "(", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "path", ",", "p", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// checkForNonDirectories returns an error if any element of path is not a directory
[ "checkForNonDirectories", "returns", "an", "error", "if", "any", "element", "of", "path", "is", "not", "a", "directory" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/mount/mount.go#L83-L98
train
coreos/ignition
internal/exec/util/device_alias.go
DeviceAlias
func DeviceAlias(path string) string { return filepath.Join(deviceAliasDir, filepath.Clean(path)) }
go
func DeviceAlias(path string) string { return filepath.Join(deviceAliasDir, filepath.Clean(path)) }
[ "func", "DeviceAlias", "(", "path", "string", ")", "string", "{", "return", "filepath", ".", "Join", "(", "deviceAliasDir", ",", "filepath", ".", "Clean", "(", "path", ")", ")", "\n", "}" ]
// DeviceAlias returns the aliased form of the supplied path. // Note device paths in ignition are always absolute.
[ "DeviceAlias", "returns", "the", "aliased", "form", "of", "the", "supplied", "path", ".", "Note", "device", "paths", "in", "ignition", "are", "always", "absolute", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/device_alias.go#L33-L35
train
coreos/ignition
internal/exec/util/device_alias.go
evalSymlinks
func evalSymlinks(path string) (res string, err error) { for i := 0; i < retrySymlinkCount; i++ { res, err = filepath.EvalSymlinks(path) if err == nil { return res, nil } else if os.IsNotExist(err) { time.Sleep(retrySymlinkDelay) } else { return "", err } } return "", fmt.Errorf("Failed to evaluate symlink after %v: %v", retrySymlinkTimeout, err) }
go
func evalSymlinks(path string) (res string, err error) { for i := 0; i < retrySymlinkCount; i++ { res, err = filepath.EvalSymlinks(path) if err == nil { return res, nil } else if os.IsNotExist(err) { time.Sleep(retrySymlinkDelay) } else { return "", err } } return "", fmt.Errorf("Failed to evaluate symlink after %v: %v", retrySymlinkTimeout, err) }
[ "func", "evalSymlinks", "(", "path", "string", ")", "(", "res", "string", ",", "err", "error", ")", "{", "for", "i", ":=", "0", ";", "i", "<", "retrySymlinkCount", ";", "i", "++", "{", "res", ",", "err", "=", "filepath", ".", "EvalSymlinks", "(", "path", ")", "\n", "if", "err", "==", "nil", "{", "return", "res", ",", "nil", "\n", "}", "else", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "time", ".", "Sleep", "(", "retrySymlinkDelay", ")", "\n", "}", "else", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "retrySymlinkTimeout", ",", "err", ")", "\n", "}" ]
// evalSymlinks wraps filepath.EvalSymlinks, retrying if it fails
[ "evalSymlinks", "wraps", "filepath", ".", "EvalSymlinks", "retrying", "if", "it", "fails" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/device_alias.go#L38-L51
train
coreos/ignition
internal/exec/util/device_alias.go
CreateDeviceAlias
func CreateDeviceAlias(path string) (string, error) { target, err := evalSymlinks(path) if err != nil { return "", err } alias := DeviceAlias(path) if err := os.Remove(alias); err != nil { if !os.IsNotExist(err) { return "", err } if err = os.MkdirAll(filepath.Dir(alias), 0750); err != nil { return "", err } } if err = os.Symlink(target, alias); err != nil { return "", err } return target, nil }
go
func CreateDeviceAlias(path string) (string, error) { target, err := evalSymlinks(path) if err != nil { return "", err } alias := DeviceAlias(path) if err := os.Remove(alias); err != nil { if !os.IsNotExist(err) { return "", err } if err = os.MkdirAll(filepath.Dir(alias), 0750); err != nil { return "", err } } if err = os.Symlink(target, alias); err != nil { return "", err } return target, nil }
[ "func", "CreateDeviceAlias", "(", "path", "string", ")", "(", "string", ",", "error", ")", "{", "target", ",", "err", ":=", "evalSymlinks", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "alias", ":=", "DeviceAlias", "(", "path", ")", "\n\n", "if", "err", ":=", "os", ".", "Remove", "(", "alias", ")", ";", "err", "!=", "nil", "{", "if", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "if", "err", "=", "os", ".", "MkdirAll", "(", "filepath", ".", "Dir", "(", "alias", ")", ",", "0750", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "}", "\n\n", "if", "err", "=", "os", ".", "Symlink", "(", "target", ",", "alias", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "target", ",", "nil", "\n", "}" ]
// CreateDeviceAlias creates a device alias for the supplied path. // On success the canonicalized path used as the alias target is returned.
[ "CreateDeviceAlias", "creates", "a", "device", "alias", "for", "the", "supplied", "path", ".", "On", "success", "the", "canonicalized", "path", "used", "as", "the", "alias", "target", "is", "returned", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/device_alias.go#L55-L78
train
decred/dcrdata
exchanges/websocket.go
Read
func (client *socketClient) Read() (msg []byte, err error) { _, msg, err = client.conn.ReadMessage() return }
go
func (client *socketClient) Read() (msg []byte, err error) { _, msg, err = client.conn.ReadMessage() return }
[ "func", "(", "client", "*", "socketClient", ")", "Read", "(", ")", "(", "msg", "[", "]", "byte", ",", "err", "error", ")", "{", "_", ",", "msg", ",", "err", "=", "client", ".", "conn", ".", "ReadMessage", "(", ")", "\n", "return", "\n", "}" ]
// Read is a wrapper for gorilla's ReadMessage that satisfies websocketFeed.Read.
[ "Read", "is", "a", "wrapper", "for", "gorilla", "s", "ReadMessage", "that", "satisfies", "websocketFeed", ".", "Read", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/websocket.go#L50-L53
train
decred/dcrdata
exchanges/websocket.go
Write
func (client *socketClient) Write(msg interface{}) error { client.writeMtx.Lock() defer client.writeMtx.Unlock() bytes, err := json.Marshal(msg) if err != nil { return err } return client.conn.WriteMessage(websocket.TextMessage, bytes) }
go
func (client *socketClient) Write(msg interface{}) error { client.writeMtx.Lock() defer client.writeMtx.Unlock() bytes, err := json.Marshal(msg) if err != nil { return err } return client.conn.WriteMessage(websocket.TextMessage, bytes) }
[ "func", "(", "client", "*", "socketClient", ")", "Write", "(", "msg", "interface", "{", "}", ")", "error", "{", "client", ".", "writeMtx", ".", "Lock", "(", ")", "\n", "defer", "client", ".", "writeMtx", ".", "Unlock", "(", ")", "\n", "bytes", ",", "err", ":=", "json", ".", "Marshal", "(", "msg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "client", ".", "conn", ".", "WriteMessage", "(", "websocket", ".", "TextMessage", ",", "bytes", ")", "\n", "}" ]
// Write is a wrapper for gorilla WriteMessage. Satisfies websocketFeed.Write. // JSON marshaling is performed before sending. Writes are sequenced with a // mutex lock for per-connection multi-threaded use.
[ "Write", "is", "a", "wrapper", "for", "gorilla", "WriteMessage", ".", "Satisfies", "websocketFeed", ".", "Write", ".", "JSON", "marshaling", "is", "performed", "before", "sending", ".", "Writes", "are", "sequenced", "with", "a", "mutex", "lock", "for", "per", "-", "connection", "multi", "-", "threaded", "use", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/websocket.go#L58-L66
train
decred/dcrdata
exchanges/websocket.go
newSocketConnection
func newSocketConnection(cfg *socketConfig) (websocketFeed, error) { dialer := &websocket.Dialer{ Proxy: http.ProxyFromEnvironment, // Same as DefaultDialer. HandshakeTimeout: 10 * time.Second, // DefaultDialer is 45 seconds. } conn, _, err := dialer.Dial(cfg.address, nil) if err != nil { return nil, err } return &socketClient{ conn: conn, done: make(chan struct{}), }, nil }
go
func newSocketConnection(cfg *socketConfig) (websocketFeed, error) { dialer := &websocket.Dialer{ Proxy: http.ProxyFromEnvironment, // Same as DefaultDialer. HandshakeTimeout: 10 * time.Second, // DefaultDialer is 45 seconds. } conn, _, err := dialer.Dial(cfg.address, nil) if err != nil { return nil, err } return &socketClient{ conn: conn, done: make(chan struct{}), }, nil }
[ "func", "newSocketConnection", "(", "cfg", "*", "socketConfig", ")", "(", "websocketFeed", ",", "error", ")", "{", "dialer", ":=", "&", "websocket", ".", "Dialer", "{", "Proxy", ":", "http", ".", "ProxyFromEnvironment", ",", "// Same as DefaultDialer.", "HandshakeTimeout", ":", "10", "*", "time", ".", "Second", ",", "// DefaultDialer is 45 seconds.", "}", "\n\n", "conn", ",", "_", ",", "err", ":=", "dialer", ".", "Dial", "(", "cfg", ".", "address", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "socketClient", "{", "conn", ":", "conn", ",", "done", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", ",", "nil", "\n", "}" ]
// Constructor for a socketClient, but returned as a websocketFeed.
[ "Constructor", "for", "a", "socketClient", "but", "returned", "as", "a", "websocketFeed", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/websocket.go#L80-L94
train
decred/dcrdata
cmd/rebuilddb2/log.go
InitLogger
func InitLogger() error { logFilePath, _ := filepath.Abs(logFile) var err error logFILE, err = os.OpenFile(logFilePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0664) if err != nil { return fmt.Errorf("Error opening log file: %v", err) } logrus.SetOutput(io.MultiWriter(logFILE, os.Stdout)) logrus.SetLevel(logrus.DebugLevel) logrus.SetFormatter(&prefix_fmt.TextFormatter{ ForceColors: true, ForceFormatting: true, FullTimestamp: true, }) //logrus.SetOutput(ansicolor.NewAnsiColorWriter(os.Stdout)) //logrus.SetOutput(colorable.NewColorableStdout()) log = logrus.New() log.Level = logrus.DebugLevel log.Formatter = &prefix_fmt.TextFormatter{ ForceColors: true, ForceFormatting: true, FullTimestamp: true, TimestampFormat: "02 Jan 06 15:04:05.00 -0700", } //log.Out = colorable.NewColorableStdout() //log.Out = colorable.NewNonColorable(io.MultiWriter(logFILE, os.Stdout)) log.Out = ansicolor.NewAnsiColorWriter(io.MultiWriter(logFILE, os.Stdout)) log.Debug("rebuilddb logger started.") return nil }
go
func InitLogger() error { logFilePath, _ := filepath.Abs(logFile) var err error logFILE, err = os.OpenFile(logFilePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0664) if err != nil { return fmt.Errorf("Error opening log file: %v", err) } logrus.SetOutput(io.MultiWriter(logFILE, os.Stdout)) logrus.SetLevel(logrus.DebugLevel) logrus.SetFormatter(&prefix_fmt.TextFormatter{ ForceColors: true, ForceFormatting: true, FullTimestamp: true, }) //logrus.SetOutput(ansicolor.NewAnsiColorWriter(os.Stdout)) //logrus.SetOutput(colorable.NewColorableStdout()) log = logrus.New() log.Level = logrus.DebugLevel log.Formatter = &prefix_fmt.TextFormatter{ ForceColors: true, ForceFormatting: true, FullTimestamp: true, TimestampFormat: "02 Jan 06 15:04:05.00 -0700", } //log.Out = colorable.NewColorableStdout() //log.Out = colorable.NewNonColorable(io.MultiWriter(logFILE, os.Stdout)) log.Out = ansicolor.NewAnsiColorWriter(io.MultiWriter(logFILE, os.Stdout)) log.Debug("rebuilddb logger started.") return nil }
[ "func", "InitLogger", "(", ")", "error", "{", "logFilePath", ",", "_", ":=", "filepath", ".", "Abs", "(", "logFile", ")", "\n", "var", "err", "error", "\n", "logFILE", ",", "err", "=", "os", ".", "OpenFile", "(", "logFilePath", ",", "os", ".", "O_RDWR", "|", "os", ".", "O_CREATE", "|", "os", ".", "O_APPEND", ",", "0664", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "logrus", ".", "SetOutput", "(", "io", ".", "MultiWriter", "(", "logFILE", ",", "os", ".", "Stdout", ")", ")", "\n", "logrus", ".", "SetLevel", "(", "logrus", ".", "DebugLevel", ")", "\n", "logrus", ".", "SetFormatter", "(", "&", "prefix_fmt", ".", "TextFormatter", "{", "ForceColors", ":", "true", ",", "ForceFormatting", ":", "true", ",", "FullTimestamp", ":", "true", ",", "}", ")", "\n", "//logrus.SetOutput(ansicolor.NewAnsiColorWriter(os.Stdout))", "//logrus.SetOutput(colorable.NewColorableStdout())", "log", "=", "logrus", ".", "New", "(", ")", "\n", "log", ".", "Level", "=", "logrus", ".", "DebugLevel", "\n", "log", ".", "Formatter", "=", "&", "prefix_fmt", ".", "TextFormatter", "{", "ForceColors", ":", "true", ",", "ForceFormatting", ":", "true", ",", "FullTimestamp", ":", "true", ",", "TimestampFormat", ":", "\"", "\"", ",", "}", "\n\n", "//log.Out = colorable.NewColorableStdout()", "//log.Out = colorable.NewNonColorable(io.MultiWriter(logFILE, os.Stdout))", "log", ".", "Out", "=", "ansicolor", ".", "NewAnsiColorWriter", "(", "io", ".", "MultiWriter", "(", "logFILE", ",", "os", ".", "Stdout", ")", ")", "\n\n", "log", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "return", "nil", "\n", "}" ]
// InitLogger starts the logger
[ "InitLogger", "starts", "the", "logger" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/cmd/rebuilddb2/log.go#L23-L58
train
decred/dcrdata
db/dcrpg/tables.go
DropTables
func DropTables(db *sql.DB) { for tableName := range createTableStatements { log.Infof("DROPPING the \"%s\" table.", tableName) if err := dropTable(db, tableName); err != nil { log.Errorf(`DROP TABLE "%s" failed.`, tableName) } } _, err := db.Exec(`DROP TYPE IF EXISTS vin;`) if err != nil { log.Errorf("DROP TYPE vin failed.") } }
go
func DropTables(db *sql.DB) { for tableName := range createTableStatements { log.Infof("DROPPING the \"%s\" table.", tableName) if err := dropTable(db, tableName); err != nil { log.Errorf(`DROP TABLE "%s" failed.`, tableName) } } _, err := db.Exec(`DROP TYPE IF EXISTS vin;`) if err != nil { log.Errorf("DROP TYPE vin failed.") } }
[ "func", "DropTables", "(", "db", "*", "sql", ".", "DB", ")", "{", "for", "tableName", ":=", "range", "createTableStatements", "{", "log", ".", "Infof", "(", "\"", "\\\"", "\\\"", "\"", ",", "tableName", ")", "\n", "if", "err", ":=", "dropTable", "(", "db", ",", "tableName", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "`DROP TABLE \"%s\" failed.`", ",", "tableName", ")", "\n", "}", "\n", "}", "\n\n", "_", ",", "err", ":=", "db", ".", "Exec", "(", "`DROP TYPE IF EXISTS vin;`", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// DropTables drops all of the tables internally recognized tables.
[ "DropTables", "drops", "all", "of", "the", "tables", "internally", "recognized", "tables", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/tables.go#L67-L79
train
decred/dcrdata
db/dcrpg/tables.go
AnalyzeAllTables
func AnalyzeAllTables(db *sql.DB, statisticsTarget int) error { dbTx, err := db.Begin() if err != nil { return fmt.Errorf("failed to begin transactions: %v", err) } _, err = dbTx.Exec(fmt.Sprintf("SET LOCAL default_statistics_target TO %d;", statisticsTarget)) if err != nil { _ = dbTx.Rollback() return fmt.Errorf("failed to set default_statistics_target: %v", err) } _, err = dbTx.Exec(`ANALYZE;`) if err != nil { _ = dbTx.Rollback() return fmt.Errorf("failed to ANALYZE all tables: %v", err) } return dbTx.Commit() }
go
func AnalyzeAllTables(db *sql.DB, statisticsTarget int) error { dbTx, err := db.Begin() if err != nil { return fmt.Errorf("failed to begin transactions: %v", err) } _, err = dbTx.Exec(fmt.Sprintf("SET LOCAL default_statistics_target TO %d;", statisticsTarget)) if err != nil { _ = dbTx.Rollback() return fmt.Errorf("failed to set default_statistics_target: %v", err) } _, err = dbTx.Exec(`ANALYZE;`) if err != nil { _ = dbTx.Rollback() return fmt.Errorf("failed to ANALYZE all tables: %v", err) } return dbTx.Commit() }
[ "func", "AnalyzeAllTables", "(", "db", "*", "sql", ".", "DB", ",", "statisticsTarget", "int", ")", "error", "{", "dbTx", ",", "err", ":=", "db", ".", "Begin", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "_", ",", "err", "=", "dbTx", ".", "Exec", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "statisticsTarget", ")", ")", "\n", "if", "err", "!=", "nil", "{", "_", "=", "dbTx", ".", "Rollback", "(", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "_", ",", "err", "=", "dbTx", ".", "Exec", "(", "`ANALYZE;`", ")", "\n", "if", "err", "!=", "nil", "{", "_", "=", "dbTx", ".", "Rollback", "(", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "dbTx", ".", "Commit", "(", ")", "\n", "}" ]
// AnalyzeAllTables performs an ANALYZE on all tables after setting // default_statistics_target for the transaction.
[ "AnalyzeAllTables", "performs", "an", "ANALYZE", "on", "all", "tables", "after", "setting", "default_statistics_target", "for", "the", "transaction", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/tables.go#L89-L108
train
decred/dcrdata
db/dcrpg/tables.go
CreateTables
func CreateTables(db *sql.DB) error { // Create all of the data tables. for tableName, createCommand := range createTableStatements { err := createTable(db, tableName, createCommand) if err != nil { return err } } return ClearTestingTable(db) }
go
func CreateTables(db *sql.DB) error { // Create all of the data tables. for tableName, createCommand := range createTableStatements { err := createTable(db, tableName, createCommand) if err != nil { return err } } return ClearTestingTable(db) }
[ "func", "CreateTables", "(", "db", "*", "sql", ".", "DB", ")", "error", "{", "// Create all of the data tables.", "for", "tableName", ",", "createCommand", ":=", "range", "createTableStatements", "{", "err", ":=", "createTable", "(", "db", ",", "tableName", ",", "createCommand", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "ClearTestingTable", "(", "db", ")", "\n", "}" ]
// CreateTables creates all tables required by dcrdata if they do not already // exist.
[ "CreateTables", "creates", "all", "tables", "required", "by", "dcrdata", "if", "they", "do", "not", "already", "exist", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/tables.go#L180-L190
train
decred/dcrdata
db/dcrpg/tables.go
CreateTable
func CreateTable(db *sql.DB, tableName string) error { createCommand, tableNameFound := createTableStatements[tableName] if !tableNameFound { return fmt.Errorf("table name %s unknown", tableName) } return createTable(db, tableName, createCommand) }
go
func CreateTable(db *sql.DB, tableName string) error { createCommand, tableNameFound := createTableStatements[tableName] if !tableNameFound { return fmt.Errorf("table name %s unknown", tableName) } return createTable(db, tableName, createCommand) }
[ "func", "CreateTable", "(", "db", "*", "sql", ".", "DB", ",", "tableName", "string", ")", "error", "{", "createCommand", ",", "tableNameFound", ":=", "createTableStatements", "[", "tableName", "]", "\n", "if", "!", "tableNameFound", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tableName", ")", "\n", "}", "\n\n", "return", "createTable", "(", "db", ",", "tableName", ",", "createCommand", ")", "\n", "}" ]
// CreateTable creates one of the known tables by name.
[ "CreateTable", "creates", "one", "of", "the", "known", "tables", "by", "name", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/tables.go#L193-L200
train
decred/dcrdata
db/dcrpg/tables.go
createTable
func createTable(db *sql.DB, tableName, stmt string) error { exists, err := TableExists(db, tableName) if err != nil { return err } if !exists { log.Infof(`Creating the "%s" table.`, tableName) _, err = db.Exec(stmt) if err != nil { return err } } else { log.Tracef(`Table "%s" exists.`, tableName) } return err }
go
func createTable(db *sql.DB, tableName, stmt string) error { exists, err := TableExists(db, tableName) if err != nil { return err } if !exists { log.Infof(`Creating the "%s" table.`, tableName) _, err = db.Exec(stmt) if err != nil { return err } } else { log.Tracef(`Table "%s" exists.`, tableName) } return err }
[ "func", "createTable", "(", "db", "*", "sql", ".", "DB", ",", "tableName", ",", "stmt", "string", ")", "error", "{", "exists", ",", "err", ":=", "TableExists", "(", "db", ",", "tableName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "!", "exists", "{", "log", ".", "Infof", "(", "`Creating the \"%s\" table.`", ",", "tableName", ")", "\n", "_", ",", "err", "=", "db", ".", "Exec", "(", "stmt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "else", "{", "log", ".", "Tracef", "(", "`Table \"%s\" exists.`", ",", "tableName", ")", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// createTable creates a table with the given name using the provided SQL // statement, if it does not already exist.
[ "createTable", "creates", "a", "table", "with", "the", "given", "name", "using", "the", "provided", "SQL", "statement", "if", "it", "does", "not", "already", "exist", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/tables.go#L204-L221
train
decred/dcrdata
db/dcrpg/tables.go
CheckColumnDataType
func CheckColumnDataType(db *sql.DB, table, column string) (dataType string, err error) { err = db.QueryRow(`SELECT data_type FROM information_schema.columns WHERE table_name=$1 AND column_name=$2`, table, column).Scan(&dataType) return }
go
func CheckColumnDataType(db *sql.DB, table, column string) (dataType string, err error) { err = db.QueryRow(`SELECT data_type FROM information_schema.columns WHERE table_name=$1 AND column_name=$2`, table, column).Scan(&dataType) return }
[ "func", "CheckColumnDataType", "(", "db", "*", "sql", ".", "DB", ",", "table", ",", "column", "string", ")", "(", "dataType", "string", ",", "err", "error", ")", "{", "err", "=", "db", ".", "QueryRow", "(", "`SELECT data_type\n\t\tFROM information_schema.columns\n\t\tWHERE table_name=$1 AND column_name=$2`", ",", "table", ",", "column", ")", ".", "Scan", "(", "&", "dataType", ")", "\n", "return", "\n", "}" ]
// CheckColumnDataType gets the data type of specified table column .
[ "CheckColumnDataType", "gets", "the", "data", "type", "of", "specified", "table", "column", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/tables.go#L224-L230
train
decred/dcrdata
db/dcrpg/tables.go
DeleteDuplicates
func (pgb *ChainDB) DeleteDuplicates(barLoad chan *dbtypes.ProgressBarLoad) error { allDuplicates := []dropDuplicatesInfo{ // Remove duplicate vins {TableName: "vins", DropDupsFunc: pgb.DeleteDuplicateVins}, // Remove duplicate vouts {TableName: "vouts", DropDupsFunc: pgb.DeleteDuplicateVouts}, // Remove duplicate transactions {TableName: "transactions", DropDupsFunc: pgb.DeleteDuplicateTxns}, // Remove duplicate agendas {TableName: "agendas", DropDupsFunc: pgb.DeleteDuplicateAgendas}, // Remove duplicate agenda_votes {TableName: "agenda_votes", DropDupsFunc: pgb.DeleteDuplicateAgendaVotes}, } var err error for _, val := range allDuplicates { msg := fmt.Sprintf("Finding and removing duplicate %s entries...", val.TableName) if barLoad != nil { barLoad <- &dbtypes.ProgressBarLoad{BarID: dbtypes.InitialDBLoad, Subtitle: msg} } log.Info(msg) var numRemoved int64 if numRemoved, err = val.DropDupsFunc(); err != nil { return fmt.Errorf("delete %s duplicate failed: %v", val.TableName, err) } msg = fmt.Sprintf("Removed %d duplicate %s entries.", numRemoved, val.TableName) if barLoad != nil { barLoad <- &dbtypes.ProgressBarLoad{BarID: dbtypes.InitialDBLoad, Subtitle: msg} } log.Info(msg) } // Signal task is done if barLoad != nil { barLoad <- &dbtypes.ProgressBarLoad{BarID: dbtypes.InitialDBLoad, Subtitle: " "} } return nil }
go
func (pgb *ChainDB) DeleteDuplicates(barLoad chan *dbtypes.ProgressBarLoad) error { allDuplicates := []dropDuplicatesInfo{ // Remove duplicate vins {TableName: "vins", DropDupsFunc: pgb.DeleteDuplicateVins}, // Remove duplicate vouts {TableName: "vouts", DropDupsFunc: pgb.DeleteDuplicateVouts}, // Remove duplicate transactions {TableName: "transactions", DropDupsFunc: pgb.DeleteDuplicateTxns}, // Remove duplicate agendas {TableName: "agendas", DropDupsFunc: pgb.DeleteDuplicateAgendas}, // Remove duplicate agenda_votes {TableName: "agenda_votes", DropDupsFunc: pgb.DeleteDuplicateAgendaVotes}, } var err error for _, val := range allDuplicates { msg := fmt.Sprintf("Finding and removing duplicate %s entries...", val.TableName) if barLoad != nil { barLoad <- &dbtypes.ProgressBarLoad{BarID: dbtypes.InitialDBLoad, Subtitle: msg} } log.Info(msg) var numRemoved int64 if numRemoved, err = val.DropDupsFunc(); err != nil { return fmt.Errorf("delete %s duplicate failed: %v", val.TableName, err) } msg = fmt.Sprintf("Removed %d duplicate %s entries.", numRemoved, val.TableName) if barLoad != nil { barLoad <- &dbtypes.ProgressBarLoad{BarID: dbtypes.InitialDBLoad, Subtitle: msg} } log.Info(msg) } // Signal task is done if barLoad != nil { barLoad <- &dbtypes.ProgressBarLoad{BarID: dbtypes.InitialDBLoad, Subtitle: " "} } return nil }
[ "func", "(", "pgb", "*", "ChainDB", ")", "DeleteDuplicates", "(", "barLoad", "chan", "*", "dbtypes", ".", "ProgressBarLoad", ")", "error", "{", "allDuplicates", ":=", "[", "]", "dropDuplicatesInfo", "{", "// Remove duplicate vins", "{", "TableName", ":", "\"", "\"", ",", "DropDupsFunc", ":", "pgb", ".", "DeleteDuplicateVins", "}", ",", "// Remove duplicate vouts", "{", "TableName", ":", "\"", "\"", ",", "DropDupsFunc", ":", "pgb", ".", "DeleteDuplicateVouts", "}", ",", "// Remove duplicate transactions", "{", "TableName", ":", "\"", "\"", ",", "DropDupsFunc", ":", "pgb", ".", "DeleteDuplicateTxns", "}", ",", "// Remove duplicate agendas", "{", "TableName", ":", "\"", "\"", ",", "DropDupsFunc", ":", "pgb", ".", "DeleteDuplicateAgendas", "}", ",", "// Remove duplicate agenda_votes", "{", "TableName", ":", "\"", "\"", ",", "DropDupsFunc", ":", "pgb", ".", "DeleteDuplicateAgendaVotes", "}", ",", "}", "\n\n", "var", "err", "error", "\n", "for", "_", ",", "val", ":=", "range", "allDuplicates", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "val", ".", "TableName", ")", "\n", "if", "barLoad", "!=", "nil", "{", "barLoad", "<-", "&", "dbtypes", ".", "ProgressBarLoad", "{", "BarID", ":", "dbtypes", ".", "InitialDBLoad", ",", "Subtitle", ":", "msg", "}", "\n", "}", "\n", "log", ".", "Info", "(", "msg", ")", "\n\n", "var", "numRemoved", "int64", "\n", "if", "numRemoved", ",", "err", "=", "val", ".", "DropDupsFunc", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "val", ".", "TableName", ",", "err", ")", "\n", "}", "\n\n", "msg", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "numRemoved", ",", "val", ".", "TableName", ")", "\n", "if", "barLoad", "!=", "nil", "{", "barLoad", "<-", "&", "dbtypes", ".", "ProgressBarLoad", "{", "BarID", ":", "dbtypes", ".", "InitialDBLoad", ",", "Subtitle", ":", "msg", "}", "\n", "}", "\n", "log", ".", "Info", "(", "msg", ")", "\n", "}", "\n", "// Signal task is done", "if", "barLoad", "!=", "nil", "{", "barLoad", "<-", "&", "dbtypes", ".", "ProgressBarLoad", "{", "BarID", ":", "dbtypes", ".", "InitialDBLoad", ",", "Subtitle", ":", "\"", "\"", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeleteDuplicates attempts to delete "duplicate" rows in tables where unique // indexes are to be created.
[ "DeleteDuplicates", "attempts", "to", "delete", "duplicate", "rows", "in", "tables", "where", "unique", "indexes", "are", "to", "be", "created", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/tables.go#L234-L276
train
decred/dcrdata
api/apirouter.go
stackedMux
func stackedMux(useRealIP bool) *chi.Mux { mux := chi.NewRouter() if useRealIP { mux.Use(middleware.RealIP) } mux.Use(middleware.Logger) mux.Use(middleware.Recoverer) corsMW := cors.Default() mux.Use(corsMW.Handler) return mux }
go
func stackedMux(useRealIP bool) *chi.Mux { mux := chi.NewRouter() if useRealIP { mux.Use(middleware.RealIP) } mux.Use(middleware.Logger) mux.Use(middleware.Recoverer) corsMW := cors.Default() mux.Use(corsMW.Handler) return mux }
[ "func", "stackedMux", "(", "useRealIP", "bool", ")", "*", "chi", ".", "Mux", "{", "mux", ":=", "chi", ".", "NewRouter", "(", ")", "\n", "if", "useRealIP", "{", "mux", ".", "Use", "(", "middleware", ".", "RealIP", ")", "\n", "}", "\n", "mux", ".", "Use", "(", "middleware", ".", "Logger", ")", "\n", "mux", ".", "Use", "(", "middleware", ".", "Recoverer", ")", "\n", "corsMW", ":=", "cors", ".", "Default", "(", ")", "\n", "mux", ".", "Use", "(", "corsMW", ".", "Handler", ")", "\n", "return", "mux", "\n", "}" ]
// Stacks some middleware common to both file and api router.
[ "Stacks", "some", "middleware", "common", "to", "both", "file", "and", "api", "router", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apirouter.go#L289-L299
train
decred/dcrdata
api/apiroutes.go
NewContext
func NewContext(cfg *AppContextConfig) *appContext { conns, _ := cfg.Client.GetConnectionCount() nodeHeight, _ := cfg.Client.GetBlockCount() // auxDataSource is an interface that could have a value of pointer type. if cfg.DBSource == nil || reflect.ValueOf(cfg.DBSource).IsNil() { log.Errorf("NewContext: a DataSourceAux is required.") return nil } return &appContext{ nodeClient: cfg.Client, Params: cfg.Params, BlockData: cfg.DataSource, AuxDataSource: cfg.DBSource, xcBot: cfg.XcBot, AgendaDB: cfg.AgendasDBInstance, Status: apitypes.NewStatus(uint32(nodeHeight), conns, APIVersion, appver.Version(), cfg.Params.Name), JSONIndent: cfg.JsonIndent, maxCSVAddrs: cfg.MaxAddrs, charts: cfg.Charts, } }
go
func NewContext(cfg *AppContextConfig) *appContext { conns, _ := cfg.Client.GetConnectionCount() nodeHeight, _ := cfg.Client.GetBlockCount() // auxDataSource is an interface that could have a value of pointer type. if cfg.DBSource == nil || reflect.ValueOf(cfg.DBSource).IsNil() { log.Errorf("NewContext: a DataSourceAux is required.") return nil } return &appContext{ nodeClient: cfg.Client, Params: cfg.Params, BlockData: cfg.DataSource, AuxDataSource: cfg.DBSource, xcBot: cfg.XcBot, AgendaDB: cfg.AgendasDBInstance, Status: apitypes.NewStatus(uint32(nodeHeight), conns, APIVersion, appver.Version(), cfg.Params.Name), JSONIndent: cfg.JsonIndent, maxCSVAddrs: cfg.MaxAddrs, charts: cfg.Charts, } }
[ "func", "NewContext", "(", "cfg", "*", "AppContextConfig", ")", "*", "appContext", "{", "conns", ",", "_", ":=", "cfg", ".", "Client", ".", "GetConnectionCount", "(", ")", "\n", "nodeHeight", ",", "_", ":=", "cfg", ".", "Client", ".", "GetBlockCount", "(", ")", "\n\n", "// auxDataSource is an interface that could have a value of pointer type.", "if", "cfg", ".", "DBSource", "==", "nil", "||", "reflect", ".", "ValueOf", "(", "cfg", ".", "DBSource", ")", ".", "IsNil", "(", ")", "{", "log", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "return", "&", "appContext", "{", "nodeClient", ":", "cfg", ".", "Client", ",", "Params", ":", "cfg", ".", "Params", ",", "BlockData", ":", "cfg", ".", "DataSource", ",", "AuxDataSource", ":", "cfg", ".", "DBSource", ",", "xcBot", ":", "cfg", ".", "XcBot", ",", "AgendaDB", ":", "cfg", ".", "AgendasDBInstance", ",", "Status", ":", "apitypes", ".", "NewStatus", "(", "uint32", "(", "nodeHeight", ")", ",", "conns", ",", "APIVersion", ",", "appver", ".", "Version", "(", ")", ",", "cfg", ".", "Params", ".", "Name", ")", ",", "JSONIndent", ":", "cfg", ".", "JsonIndent", ",", "maxCSVAddrs", ":", "cfg", ".", "MaxAddrs", ",", "charts", ":", "cfg", ".", "Charts", ",", "}", "\n", "}" ]
// NewContext constructs a new appContext from the RPC client, primary and // auxiliary data sources, and JSON indentation string.
[ "NewContext", "constructs", "a", "new", "appContext", "from", "the", "RPC", "client", "primary", "and", "auxiliary", "data", "sources", "and", "JSON", "indentation", "string", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apiroutes.go#L150-L172
train
decred/dcrdata
api/apiroutes.go
StatusNtfnHandler
func (c *appContext) StatusNtfnHandler(ctx context.Context, wg *sync.WaitGroup) { defer wg.Done() out: for { keepon: select { case height, ok := <-notify.NtfnChans.UpdateStatusNodeHeight: if !ok { log.Warnf("Block connected channel closed.") break out } nodeConnections, err := c.nodeClient.GetConnectionCount() if err == nil { c.Status.SetHeightAndConnections(height, nodeConnections) } else { c.Status.SetHeight(height) c.Status.SetReady(false) log.Warn("Failed to get connection count: ", err) break keepon } case height, ok := <-notify.NtfnChans.UpdateStatusDBHeight: if !ok { log.Warnf("Block connected channel closed.") break out } if c.BlockData == nil { panic("BlockData DataSourceLite is nil") } summary := c.BlockData.GetBestBlockSummary() if summary == nil { log.Errorf("BlockData summary is nil for height %d.", height) break keepon } c.Status.DBUpdate(height, summary.Time.S.UNIX()) bdHeight, err := c.BlockData.GetHeight() // Catch certain pathological conditions. switch { case err != nil: log.Errorf("GetHeight failed: %v", err) case (height != uint32(bdHeight)) || (height != summary.Height): log.Errorf("New DB height (%d) and stored block data (%d, %d) are not consistent.", height, bdHeight, summary.Height) case bdHeight < 0: log.Warnf("DB empty (height = %d)", bdHeight) default: // If DB height agrees with node height, then we're ready. break keepon } c.Status.SetReady(false) case <-ctx.Done(): log.Debugf("Got quit signal. Exiting block connected handler for STATUS monitor.") break out } } }
go
func (c *appContext) StatusNtfnHandler(ctx context.Context, wg *sync.WaitGroup) { defer wg.Done() out: for { keepon: select { case height, ok := <-notify.NtfnChans.UpdateStatusNodeHeight: if !ok { log.Warnf("Block connected channel closed.") break out } nodeConnections, err := c.nodeClient.GetConnectionCount() if err == nil { c.Status.SetHeightAndConnections(height, nodeConnections) } else { c.Status.SetHeight(height) c.Status.SetReady(false) log.Warn("Failed to get connection count: ", err) break keepon } case height, ok := <-notify.NtfnChans.UpdateStatusDBHeight: if !ok { log.Warnf("Block connected channel closed.") break out } if c.BlockData == nil { panic("BlockData DataSourceLite is nil") } summary := c.BlockData.GetBestBlockSummary() if summary == nil { log.Errorf("BlockData summary is nil for height %d.", height) break keepon } c.Status.DBUpdate(height, summary.Time.S.UNIX()) bdHeight, err := c.BlockData.GetHeight() // Catch certain pathological conditions. switch { case err != nil: log.Errorf("GetHeight failed: %v", err) case (height != uint32(bdHeight)) || (height != summary.Height): log.Errorf("New DB height (%d) and stored block data (%d, %d) are not consistent.", height, bdHeight, summary.Height) case bdHeight < 0: log.Warnf("DB empty (height = %d)", bdHeight) default: // If DB height agrees with node height, then we're ready. break keepon } c.Status.SetReady(false) case <-ctx.Done(): log.Debugf("Got quit signal. Exiting block connected handler for STATUS monitor.") break out } } }
[ "func", "(", "c", "*", "appContext", ")", "StatusNtfnHandler", "(", "ctx", "context", ".", "Context", ",", "wg", "*", "sync", ".", "WaitGroup", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "out", ":", "for", "{", "keepon", ":", "select", "{", "case", "height", ",", "ok", ":=", "<-", "notify", ".", "NtfnChans", ".", "UpdateStatusNodeHeight", ":", "if", "!", "ok", "{", "log", ".", "Warnf", "(", "\"", "\"", ")", "\n", "break", "out", "\n", "}", "\n\n", "nodeConnections", ",", "err", ":=", "c", ".", "nodeClient", ".", "GetConnectionCount", "(", ")", "\n", "if", "err", "==", "nil", "{", "c", ".", "Status", ".", "SetHeightAndConnections", "(", "height", ",", "nodeConnections", ")", "\n", "}", "else", "{", "c", ".", "Status", ".", "SetHeight", "(", "height", ")", "\n", "c", ".", "Status", ".", "SetReady", "(", "false", ")", "\n", "log", ".", "Warn", "(", "\"", "\"", ",", "err", ")", "\n", "break", "keepon", "\n", "}", "\n\n", "case", "height", ",", "ok", ":=", "<-", "notify", ".", "NtfnChans", ".", "UpdateStatusDBHeight", ":", "if", "!", "ok", "{", "log", ".", "Warnf", "(", "\"", "\"", ")", "\n", "break", "out", "\n", "}", "\n\n", "if", "c", ".", "BlockData", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "summary", ":=", "c", ".", "BlockData", ".", "GetBestBlockSummary", "(", ")", "\n", "if", "summary", "==", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "height", ")", "\n", "break", "keepon", "\n", "}", "\n\n", "c", ".", "Status", ".", "DBUpdate", "(", "height", ",", "summary", ".", "Time", ".", "S", ".", "UNIX", "(", ")", ")", "\n\n", "bdHeight", ",", "err", ":=", "c", ".", "BlockData", ".", "GetHeight", "(", ")", "\n", "// Catch certain pathological conditions.", "switch", "{", "case", "err", "!=", "nil", ":", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "case", "(", "height", "!=", "uint32", "(", "bdHeight", ")", ")", "||", "(", "height", "!=", "summary", ".", "Height", ")", ":", "log", ".", "Errorf", "(", "\"", "\"", ",", "height", ",", "bdHeight", ",", "summary", ".", "Height", ")", "\n", "case", "bdHeight", "<", "0", ":", "log", ".", "Warnf", "(", "\"", "\"", ",", "bdHeight", ")", "\n", "default", ":", "// If DB height agrees with node height, then we're ready.", "break", "keepon", "\n", "}", "\n\n", "c", ".", "Status", ".", "SetReady", "(", "false", ")", "\n\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "log", ".", "Debugf", "(", "\"", "\"", ")", "\n", "break", "out", "\n", "}", "\n", "}", "\n", "}" ]
// StatusNtfnHandler keeps the appContext's Status up-to-date with changes in // node and DB status.
[ "StatusNtfnHandler", "keeps", "the", "appContext", "s", "Status", "up", "-", "to", "-", "date", "with", "changes", "in", "node", "and", "DB", "status", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apiroutes.go#L176-L238
train
decred/dcrdata
api/apiroutes.go
root
func (c *appContext) root(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "dcrdata api running") }
go
func (c *appContext) root(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "dcrdata api running") }
[ "func", "(", "c", "*", "appContext", ")", "root", "(", "w", "http", ".", "ResponseWriter", ",", "_", "*", "http", ".", "Request", ")", "{", "fmt", ".", "Fprint", "(", "w", ",", "\"", "\"", ")", "\n", "}" ]
// root is a http.Handler intended for the API root path. This essentially // provides a heartbeat, and no information about the application status.
[ "root", "is", "a", "http", ".", "Handler", "intended", "for", "the", "API", "root", "path", ".", "This", "essentially", "provides", "a", "heartbeat", "and", "no", "information", "about", "the", "application", "status", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apiroutes.go#L242-L244
train
decred/dcrdata
api/apiroutes.go
writeJSONBytes
func writeJSONBytes(w http.ResponseWriter, data []byte) { w.Header().Set("Content-Type", "application/json; charset=utf-8") _, err := w.Write(data) if err != nil { apiLog.Warnf("ResponseWriter.Write error: %v", err) } }
go
func writeJSONBytes(w http.ResponseWriter, data []byte) { w.Header().Set("Content-Type", "application/json; charset=utf-8") _, err := w.Write(data) if err != nil { apiLog.Warnf("ResponseWriter.Write error: %v", err) } }
[ "func", "writeJSONBytes", "(", "w", "http", ".", "ResponseWriter", ",", "data", "[", "]", "byte", ")", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "_", ",", "err", ":=", "w", ".", "Write", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "apiLog", ".", "Warnf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// writeJSONBytes prepares the headers for pre-encoded JSON and writes the JSON // bytes.
[ "writeJSONBytes", "prepares", "the", "headers", "for", "pre", "-", "encoded", "JSON", "and", "writes", "the", "JSON", "bytes", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apiroutes.go#L263-L269
train
decred/dcrdata
api/apiroutes.go
writeCSV
func writeCSV(w http.ResponseWriter, rows [][]string, filename string, useCRLF bool) { w.Header().Set("Content-Disposition", fmt.Sprintf("attachment;filename=%s", filename)) w.Header().Set("Content-Type", "text/csv") // To set the Content-Length response header, it is necessary to write the // CSV data into a buffer rather than streaming the response directly to the // http.ResponseWriter. buffer := new(bytes.Buffer) writer := csv.NewWriter(buffer) writer.UseCRLF = useCRLF err := writer.WriteAll(rows) if err != nil { log.Errorf("Failed to write address rows to buffer: %v", err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } bytesToSend := int64(buffer.Len()) w.Header().Set("Content-Length", strconv.FormatInt(bytesToSend, 10)) bytesWritten, err := buffer.WriteTo(w) if err != nil { log.Errorf("Failed to transfer address rows from buffer. "+ "%d bytes written. %v", bytesWritten, err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } // Warn if the number of bytes sent differs from buffer length. if bytesWritten != bytesToSend { log.Warnf("Failed to send the entire file. Sent %d of %d bytes.", bytesWritten, bytesToSend) } }
go
func writeCSV(w http.ResponseWriter, rows [][]string, filename string, useCRLF bool) { w.Header().Set("Content-Disposition", fmt.Sprintf("attachment;filename=%s", filename)) w.Header().Set("Content-Type", "text/csv") // To set the Content-Length response header, it is necessary to write the // CSV data into a buffer rather than streaming the response directly to the // http.ResponseWriter. buffer := new(bytes.Buffer) writer := csv.NewWriter(buffer) writer.UseCRLF = useCRLF err := writer.WriteAll(rows) if err != nil { log.Errorf("Failed to write address rows to buffer: %v", err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } bytesToSend := int64(buffer.Len()) w.Header().Set("Content-Length", strconv.FormatInt(bytesToSend, 10)) bytesWritten, err := buffer.WriteTo(w) if err != nil { log.Errorf("Failed to transfer address rows from buffer. "+ "%d bytes written. %v", bytesWritten, err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } // Warn if the number of bytes sent differs from buffer length. if bytesWritten != bytesToSend { log.Warnf("Failed to send the entire file. Sent %d of %d bytes.", bytesWritten, bytesToSend) } }
[ "func", "writeCSV", "(", "w", "http", ".", "ResponseWriter", ",", "rows", "[", "]", "[", "]", "string", ",", "filename", "string", ",", "useCRLF", "bool", ")", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "filename", ")", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// To set the Content-Length response header, it is necessary to write the", "// CSV data into a buffer rather than streaming the response directly to the", "// http.ResponseWriter.", "buffer", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "writer", ":=", "csv", ".", "NewWriter", "(", "buffer", ")", "\n", "writer", ".", "UseCRLF", "=", "useCRLF", "\n", "err", ":=", "writer", ".", "WriteAll", "(", "rows", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "http", ".", "Error", "(", "w", ",", "http", ".", "StatusText", "(", "http", ".", "StatusInternalServerError", ")", ",", "http", ".", "StatusInternalServerError", ")", "\n", "return", "\n", "}", "\n\n", "bytesToSend", ":=", "int64", "(", "buffer", ".", "Len", "(", ")", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "bytesToSend", ",", "10", ")", ")", "\n\n", "bytesWritten", ",", "err", ":=", "buffer", ".", "WriteTo", "(", "w", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "bytesWritten", ",", "err", ")", "\n", "http", ".", "Error", "(", "w", ",", "http", ".", "StatusText", "(", "http", ".", "StatusInternalServerError", ")", ",", "http", ".", "StatusInternalServerError", ")", "\n", "return", "\n", "}", "\n\n", "// Warn if the number of bytes sent differs from buffer length.", "if", "bytesWritten", "!=", "bytesToSend", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "bytesWritten", ",", "bytesToSend", ")", "\n", "}", "\n", "}" ]
// Measures length, sets common headers, formats, and sends CSV data.
[ "Measures", "length", "sets", "common", "headers", "formats", "and", "sends", "CSV", "data", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apiroutes.go#L272-L308
train
decred/dcrdata
api/apiroutes.go
setTrimmedTxSpends
func (c *appContext) setTrimmedTxSpends(tx *apitypes.TrimmedTx) error { return c.setOutputSpends(tx.TxID, tx.Vout) }
go
func (c *appContext) setTrimmedTxSpends(tx *apitypes.TrimmedTx) error { return c.setOutputSpends(tx.TxID, tx.Vout) }
[ "func", "(", "c", "*", "appContext", ")", "setTrimmedTxSpends", "(", "tx", "*", "apitypes", ".", "TrimmedTx", ")", "error", "{", "return", "c", ".", "setOutputSpends", "(", "tx", ".", "TxID", ",", "tx", ".", "Vout", ")", "\n", "}" ]
// setTrimmedTxSpends is like setTxSpends except that it operates on a TrimmedTx // instead of a Tx.
[ "setTrimmedTxSpends", "is", "like", "setTxSpends", "except", "that", "it", "operates", "on", "a", "TrimmedTx", "instead", "of", "a", "Tx", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apiroutes.go#L603-L605
train
decred/dcrdata
api/apiroutes.go
getBlockStakeInfoExtendedByHash
func (c *appContext) getBlockStakeInfoExtendedByHash(w http.ResponseWriter, r *http.Request) { hash, err := c.getBlockHashCtx(r) if err != nil { http.Error(w, http.StatusText(422), 422) return } stakeinfo := c.BlockData.GetStakeInfoExtendedByHash(hash) if stakeinfo == nil { apiLog.Errorf("Unable to get block fee info for %s", hash) http.Error(w, http.StatusText(422), 422) return } writeJSON(w, stakeinfo, c.getIndentQuery(r)) }
go
func (c *appContext) getBlockStakeInfoExtendedByHash(w http.ResponseWriter, r *http.Request) { hash, err := c.getBlockHashCtx(r) if err != nil { http.Error(w, http.StatusText(422), 422) return } stakeinfo := c.BlockData.GetStakeInfoExtendedByHash(hash) if stakeinfo == nil { apiLog.Errorf("Unable to get block fee info for %s", hash) http.Error(w, http.StatusText(422), 422) return } writeJSON(w, stakeinfo, c.getIndentQuery(r)) }
[ "func", "(", "c", "*", "appContext", ")", "getBlockStakeInfoExtendedByHash", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "hash", ",", "err", ":=", "c", ".", "getBlockHashCtx", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "http", ".", "StatusText", "(", "422", ")", ",", "422", ")", "\n", "return", "\n", "}", "\n\n", "stakeinfo", ":=", "c", ".", "BlockData", ".", "GetStakeInfoExtendedByHash", "(", "hash", ")", "\n", "if", "stakeinfo", "==", "nil", "{", "apiLog", ".", "Errorf", "(", "\"", "\"", ",", "hash", ")", "\n", "http", ".", "Error", "(", "w", ",", "http", ".", "StatusText", "(", "422", ")", ",", "422", ")", "\n", "return", "\n", "}", "\n\n", "writeJSON", "(", "w", ",", "stakeinfo", ",", "c", ".", "getIndentQuery", "(", "r", ")", ")", "\n", "}" ]
// getBlockStakeInfoExtendedByHash retrieves the apitype.StakeInfoExtended // for the given blockhash
[ "getBlockStakeInfoExtendedByHash", "retrieves", "the", "apitype", ".", "StakeInfoExtended", "for", "the", "given", "blockhash" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apiroutes.go#L894-L909
train
decred/dcrdata
api/apiroutes.go
getBlockStakeInfoExtendedByHeight
func (c *appContext) getBlockStakeInfoExtendedByHeight(w http.ResponseWriter, r *http.Request) { idx, err := c.getBlockHeightCtx(r) if err != nil { http.Error(w, http.StatusText(422), 422) return } stakeinfo := c.BlockData.GetStakeInfoExtendedByHeight(int(idx)) if stakeinfo == nil { apiLog.Errorf("Unable to get block fee info for height %d", idx) http.Error(w, http.StatusText(422), 422) return } writeJSON(w, stakeinfo, c.getIndentQuery(r)) }
go
func (c *appContext) getBlockStakeInfoExtendedByHeight(w http.ResponseWriter, r *http.Request) { idx, err := c.getBlockHeightCtx(r) if err != nil { http.Error(w, http.StatusText(422), 422) return } stakeinfo := c.BlockData.GetStakeInfoExtendedByHeight(int(idx)) if stakeinfo == nil { apiLog.Errorf("Unable to get block fee info for height %d", idx) http.Error(w, http.StatusText(422), 422) return } writeJSON(w, stakeinfo, c.getIndentQuery(r)) }
[ "func", "(", "c", "*", "appContext", ")", "getBlockStakeInfoExtendedByHeight", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "idx", ",", "err", ":=", "c", ".", "getBlockHeightCtx", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "http", ".", "StatusText", "(", "422", ")", ",", "422", ")", "\n", "return", "\n", "}", "\n", "stakeinfo", ":=", "c", ".", "BlockData", ".", "GetStakeInfoExtendedByHeight", "(", "int", "(", "idx", ")", ")", "\n", "if", "stakeinfo", "==", "nil", "{", "apiLog", ".", "Errorf", "(", "\"", "\"", ",", "idx", ")", "\n", "http", ".", "Error", "(", "w", ",", "http", ".", "StatusText", "(", "422", ")", ",", "422", ")", "\n", "return", "\n", "}", "\n\n", "writeJSON", "(", "w", ",", "stakeinfo", ",", "c", ".", "getIndentQuery", "(", "r", ")", ")", "\n", "}" ]
// getBlockStakeInfoExtendedByHeight retrieves the apitype.StakeInfoExtended // for the given blockheight on mainchain
[ "getBlockStakeInfoExtendedByHeight", "retrieves", "the", "apitype", ".", "StakeInfoExtended", "for", "the", "given", "blockheight", "on", "mainchain" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apiroutes.go#L913-L927
train
decred/dcrdata
api/apiroutes.go
getPowerlessTickets
func (c *appContext) getPowerlessTickets(w http.ResponseWriter, r *http.Request) { tickets, err := c.AuxDataSource.PowerlessTickets() if err != nil { http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } writeJSON(w, tickets, c.getIndentQuery(r)) }
go
func (c *appContext) getPowerlessTickets(w http.ResponseWriter, r *http.Request) { tickets, err := c.AuxDataSource.PowerlessTickets() if err != nil { http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } writeJSON(w, tickets, c.getIndentQuery(r)) }
[ "func", "(", "c", "*", "appContext", ")", "getPowerlessTickets", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "tickets", ",", "err", ":=", "c", ".", "AuxDataSource", ".", "PowerlessTickets", "(", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "http", ".", "StatusText", "(", "http", ".", "StatusInternalServerError", ")", ",", "http", ".", "StatusInternalServerError", ")", "\n", "return", "\n", "}", "\n", "writeJSON", "(", "w", ",", "tickets", ",", "c", ".", "getIndentQuery", "(", "r", ")", ")", "\n", "}" ]
// Encodes apitypes.PowerlessTickets, which is missed or expired tickets sorted // by revocation status.
[ "Encodes", "apitypes", ".", "PowerlessTickets", "which", "is", "missed", "or", "expired", "tickets", "sorted", "by", "revocation", "status", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apiroutes.go#L942-L949
train
decred/dcrdata
api/apiroutes.go
getAgendasData
func (c *appContext) getAgendasData(w http.ResponseWriter, _ *http.Request) { agendas, err := c.AgendaDB.AllAgendas() if err != nil { apiLog.Errorf("agendadb AllAgendas error: %v", err) http.Error(w, "agendadb.AllAgendas failed.", http.StatusServiceUnavailable) return } voteMilestones, err := c.AuxDataSource.AllAgendas() if err != nil { apiLog.Errorf("AllAgendas timeout error: %v", err) http.Error(w, "Database timeout.", http.StatusServiceUnavailable) } data := make([]apitypes.AgendasInfo, 0, len(agendas)) for index := range agendas { val := agendas[index] agendaMilestone := voteMilestones[val.ID] agendaMilestone.StartTime = time.Unix(int64(val.StartTime), 0).UTC() agendaMilestone.ExpireTime = time.Unix(int64(val.ExpireTime), 0).UTC() data = append(data, apitypes.AgendasInfo{ Name: val.ID, Description: val.Description, VoteVersion: val.VoteVersion, MileStone: &agendaMilestone, Mask: val.Mask, }) } writeJSON(w, data, "") }
go
func (c *appContext) getAgendasData(w http.ResponseWriter, _ *http.Request) { agendas, err := c.AgendaDB.AllAgendas() if err != nil { apiLog.Errorf("agendadb AllAgendas error: %v", err) http.Error(w, "agendadb.AllAgendas failed.", http.StatusServiceUnavailable) return } voteMilestones, err := c.AuxDataSource.AllAgendas() if err != nil { apiLog.Errorf("AllAgendas timeout error: %v", err) http.Error(w, "Database timeout.", http.StatusServiceUnavailable) } data := make([]apitypes.AgendasInfo, 0, len(agendas)) for index := range agendas { val := agendas[index] agendaMilestone := voteMilestones[val.ID] agendaMilestone.StartTime = time.Unix(int64(val.StartTime), 0).UTC() agendaMilestone.ExpireTime = time.Unix(int64(val.ExpireTime), 0).UTC() data = append(data, apitypes.AgendasInfo{ Name: val.ID, Description: val.Description, VoteVersion: val.VoteVersion, MileStone: &agendaMilestone, Mask: val.Mask, }) } writeJSON(w, data, "") }
[ "func", "(", "c", "*", "appContext", ")", "getAgendasData", "(", "w", "http", ".", "ResponseWriter", ",", "_", "*", "http", ".", "Request", ")", "{", "agendas", ",", "err", ":=", "c", ".", "AgendaDB", ".", "AllAgendas", "(", ")", "\n", "if", "err", "!=", "nil", "{", "apiLog", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "http", ".", "Error", "(", "w", ",", "\"", "\"", ",", "http", ".", "StatusServiceUnavailable", ")", "\n", "return", "\n", "}", "\n\n", "voteMilestones", ",", "err", ":=", "c", ".", "AuxDataSource", ".", "AllAgendas", "(", ")", "\n", "if", "err", "!=", "nil", "{", "apiLog", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "http", ".", "Error", "(", "w", ",", "\"", "\"", ",", "http", ".", "StatusServiceUnavailable", ")", "\n", "}", "\n\n", "data", ":=", "make", "(", "[", "]", "apitypes", ".", "AgendasInfo", ",", "0", ",", "len", "(", "agendas", ")", ")", "\n", "for", "index", ":=", "range", "agendas", "{", "val", ":=", "agendas", "[", "index", "]", "\n", "agendaMilestone", ":=", "voteMilestones", "[", "val", ".", "ID", "]", "\n", "agendaMilestone", ".", "StartTime", "=", "time", ".", "Unix", "(", "int64", "(", "val", ".", "StartTime", ")", ",", "0", ")", ".", "UTC", "(", ")", "\n", "agendaMilestone", ".", "ExpireTime", "=", "time", ".", "Unix", "(", "int64", "(", "val", ".", "ExpireTime", ")", ",", "0", ")", ".", "UTC", "(", ")", "\n\n", "data", "=", "append", "(", "data", ",", "apitypes", ".", "AgendasInfo", "{", "Name", ":", "val", ".", "ID", ",", "Description", ":", "val", ".", "Description", ",", "VoteVersion", ":", "val", ".", "VoteVersion", ",", "MileStone", ":", "&", "agendaMilestone", ",", "Mask", ":", "val", ".", "Mask", ",", "}", ")", "\n", "}", "\n", "writeJSON", "(", "w", ",", "data", ",", "\"", "\"", ")", "\n", "}" ]
// getAgendasData returns high level agendas details that includes Name, // Description, Vote Version, VotingDone height, Activated, HardForked, // StartTime and ExpireTime.
[ "getAgendasData", "returns", "high", "level", "agendas", "details", "that", "includes", "Name", "Description", "Vote", "Version", "VotingDone", "height", "Activated", "HardForked", "StartTime", "and", "ExpireTime", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apiroutes.go#L1757-L1787
train
decred/dcrdata
db/dbtypes/types.go
IsTimeout
func IsTimeout(msg string) bool { // Contains is used instead of HasPrefix since error messages are often // supplemented with additional information. return strings.Contains(msg, TimeoutPrefix) || strings.Contains(msg, CtxDeadlineExceeded) }
go
func IsTimeout(msg string) bool { // Contains is used instead of HasPrefix since error messages are often // supplemented with additional information. return strings.Contains(msg, TimeoutPrefix) || strings.Contains(msg, CtxDeadlineExceeded) }
[ "func", "IsTimeout", "(", "msg", "string", ")", "bool", "{", "// Contains is used instead of HasPrefix since error messages are often", "// supplemented with additional information.", "return", "strings", ".", "Contains", "(", "msg", ",", "TimeoutPrefix", ")", "||", "strings", ".", "Contains", "(", "msg", ",", "CtxDeadlineExceeded", ")", "\n", "}" ]
// IsTimeout checks if the message is prefixed with the expected DB timeout // message prefix.
[ "IsTimeout", "checks", "if", "the", "message", "is", "prefixed", "with", "the", "expected", "DB", "timeout", "message", "prefix", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/types.go#L32-L37
train
decred/dcrdata
db/dbtypes/types.go
Value
func (t TimeDef) Value() (driver.Value, error) { return t.T.UTC(), nil }
go
func (t TimeDef) Value() (driver.Value, error) { return t.T.UTC(), nil }
[ "func", "(", "t", "TimeDef", ")", "Value", "(", ")", "(", "driver", ".", "Value", ",", "error", ")", "{", "return", "t", ".", "T", ".", "UTC", "(", ")", ",", "nil", "\n", "}" ]
// Value implements the sql.Valuer interface. It ensures that the Time Values // are for the UTC time zone. Times will only survive a round trip to and from // the DB tables if they are stored from a time.Time with Location set to UTC.
[ "Value", "implements", "the", "sql", ".", "Valuer", "interface", ".", "It", "ensures", "that", "the", "Time", "Values", "are", "for", "the", "UTC", "time", "zone", ".", "Times", "will", "only", "survive", "a", "round", "trip", "to", "and", "from", "the", "DB", "tables", "if", "they", "are", "stored", "from", "a", "time", ".", "Time", "with", "Location", "set", "to", "UTC", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/types.go#L130-L132
train
decred/dcrdata
db/dbtypes/types.go
Value
func (t TimeDefLocal) Value() (driver.Value, error) { return t.T.Local(), nil }
go
func (t TimeDefLocal) Value() (driver.Value, error) { return t.T.Local(), nil }
[ "func", "(", "t", "TimeDefLocal", ")", "Value", "(", ")", "(", "driver", ".", "Value", ",", "error", ")", "{", "return", "t", ".", "T", ".", "Local", "(", ")", ",", "nil", "\n", "}" ]
// Value implements the sql.Valuer interface. It ensures that the Time Values // are for the Local time zone. It is unlikely to be desirable to store values // this way. Only storing a time.Time in UTC allows round trip fidelity.
[ "Value", "implements", "the", "sql", ".", "Valuer", "interface", ".", "It", "ensures", "that", "the", "Time", "Values", "are", "for", "the", "Local", "time", "zone", ".", "It", "is", "unlikely", "to", "be", "desirable", "to", "store", "values", "this", "way", ".", "Only", "storing", "a", "time", ".", "Time", "in", "UTC", "allows", "round", "trip", "fidelity", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/types.go#L143-L145
train
decred/dcrdata
db/dbtypes/types.go
UnmarshalJSON
func (a *AgendaStatusType) UnmarshalJSON(b []byte) error { var str string if err := json.Unmarshal(b, &str); err != nil { return err } *a = AgendaStatusFromStr(str) return nil }
go
func (a *AgendaStatusType) UnmarshalJSON(b []byte) error { var str string if err := json.Unmarshal(b, &str); err != nil { return err } *a = AgendaStatusFromStr(str) return nil }
[ "func", "(", "a", "*", "AgendaStatusType", ")", "UnmarshalJSON", "(", "b", "[", "]", "byte", ")", "error", "{", "var", "str", "string", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "b", ",", "&", "str", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "*", "a", "=", "AgendaStatusFromStr", "(", "str", ")", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON is the default unmarshaller for AgendaStatusType.
[ "UnmarshalJSON", "is", "the", "default", "unmarshaller", "for", "AgendaStatusType", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/types.go#L232-L239
train
decred/dcrdata
db/dbtypes/types.go
AgendaStatusFromStr
func AgendaStatusFromStr(status string) AgendaStatusType { switch strings.ToLower(status) { case "defined", "upcoming": return InitialAgendaStatus case "started", "in progress": return StartedAgendaStatus case "failed": return FailedAgendaStatus case "lockedin", "locked in": return LockedInAgendaStatus case "active", "finished": return ActivatedAgendaStatus default: return UnknownStatus } }
go
func AgendaStatusFromStr(status string) AgendaStatusType { switch strings.ToLower(status) { case "defined", "upcoming": return InitialAgendaStatus case "started", "in progress": return StartedAgendaStatus case "failed": return FailedAgendaStatus case "lockedin", "locked in": return LockedInAgendaStatus case "active", "finished": return ActivatedAgendaStatus default: return UnknownStatus } }
[ "func", "AgendaStatusFromStr", "(", "status", "string", ")", "AgendaStatusType", "{", "switch", "strings", ".", "ToLower", "(", "status", ")", "{", "case", "\"", "\"", ",", "\"", "\"", ":", "return", "InitialAgendaStatus", "\n", "case", "\"", "\"", ",", "\"", "\"", ":", "return", "StartedAgendaStatus", "\n", "case", "\"", "\"", ":", "return", "FailedAgendaStatus", "\n", "case", "\"", "\"", ",", "\"", "\"", ":", "return", "LockedInAgendaStatus", "\n", "case", "\"", "\"", ",", "\"", "\"", ":", "return", "ActivatedAgendaStatus", "\n", "default", ":", "return", "UnknownStatus", "\n", "}", "\n", "}" ]
// AgendaStatusFromStr creates an agenda status from a string. If "UnknownStatus" // is returned then an invalid status string has been passed.
[ "AgendaStatusFromStr", "creates", "an", "agenda", "status", "from", "a", "string", ".", "If", "UnknownStatus", "is", "returned", "then", "an", "invalid", "status", "string", "has", "been", "passed", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/types.go#L243-L258
train
decred/dcrdata
db/dbtypes/types.go
IsMerged
func (a AddrTxnViewType) IsMerged() (bool, error) { switch a { case AddrTxnAll, AddrTxnCredit, AddrTxnDebit: return false, nil case AddrMergedTxn, AddrMergedTxnCredit, AddrMergedTxnDebit: return true, nil default: return false, fmt.Errorf("unrecognized address transaction view: %v", a) } }
go
func (a AddrTxnViewType) IsMerged() (bool, error) { switch a { case AddrTxnAll, AddrTxnCredit, AddrTxnDebit: return false, nil case AddrMergedTxn, AddrMergedTxnCredit, AddrMergedTxnDebit: return true, nil default: return false, fmt.Errorf("unrecognized address transaction view: %v", a) } }
[ "func", "(", "a", "AddrTxnViewType", ")", "IsMerged", "(", ")", "(", "bool", ",", "error", ")", "{", "switch", "a", "{", "case", "AddrTxnAll", ",", "AddrTxnCredit", ",", "AddrTxnDebit", ":", "return", "false", ",", "nil", "\n", "case", "AddrMergedTxn", ",", "AddrMergedTxnCredit", ",", "AddrMergedTxnDebit", ":", "return", "true", ",", "nil", "\n", "default", ":", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "a", ")", "\n", "}", "\n", "}" ]
// IsMerged indicates if the address transactions view type is a merged view. If // the type is invalid, a non-nil error is returned.
[ "IsMerged", "indicates", "if", "the", "address", "transactions", "view", "type", "is", "a", "merged", "view", ".", "If", "the", "type", "is", "invalid", "a", "non", "-", "nil", "error", "is", "returned", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/types.go#L291-L300
train
decred/dcrdata
db/dbtypes/types.go
AddrTxnViewTypeFromStr
func AddrTxnViewTypeFromStr(txnType string) AddrTxnViewType { txnType = strings.ToLower(txnType) switch txnType { case "all": return AddrTxnAll case "credit", "credits": return AddrTxnCredit case "debit", "debits": return AddrTxnDebit case "merged_debit", "merged debit": return AddrMergedTxnDebit case "merged_credit", "merged credit": return AddrMergedTxnCredit case "merged": return AddrMergedTxn default: return AddrTxnUnknown } }
go
func AddrTxnViewTypeFromStr(txnType string) AddrTxnViewType { txnType = strings.ToLower(txnType) switch txnType { case "all": return AddrTxnAll case "credit", "credits": return AddrTxnCredit case "debit", "debits": return AddrTxnDebit case "merged_debit", "merged debit": return AddrMergedTxnDebit case "merged_credit", "merged credit": return AddrMergedTxnCredit case "merged": return AddrMergedTxn default: return AddrTxnUnknown } }
[ "func", "AddrTxnViewTypeFromStr", "(", "txnType", "string", ")", "AddrTxnViewType", "{", "txnType", "=", "strings", ".", "ToLower", "(", "txnType", ")", "\n", "switch", "txnType", "{", "case", "\"", "\"", ":", "return", "AddrTxnAll", "\n", "case", "\"", "\"", ",", "\"", "\"", ":", "return", "AddrTxnCredit", "\n", "case", "\"", "\"", ",", "\"", "\"", ":", "return", "AddrTxnDebit", "\n", "case", "\"", "\"", ",", "\"", "\"", ":", "return", "AddrMergedTxnDebit", "\n", "case", "\"", "\"", ",", "\"", "\"", ":", "return", "AddrMergedTxnCredit", "\n", "case", "\"", "\"", ":", "return", "AddrMergedTxn", "\n", "default", ":", "return", "AddrTxnUnknown", "\n", "}", "\n", "}" ]
// AddrTxnViewTypeFromStr attempts to decode a string into an AddrTxnViewType.
[ "AddrTxnViewTypeFromStr", "attempts", "to", "decode", "a", "string", "into", "an", "AddrTxnViewType", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/types.go#L303-L321
train
decred/dcrdata
db/dbtypes/types.go
TimeGroupingFromStr
func TimeGroupingFromStr(groupings string) TimeBasedGrouping { switch strings.ToLower(groupings) { case "all": return AllGrouping case "yr", "year", "years": return YearGrouping case "mo", "month", "months": return MonthGrouping case "wk", "week", "weeks": return WeekGrouping case "day", "days": return DayGrouping default: return UnknownGrouping } }
go
func TimeGroupingFromStr(groupings string) TimeBasedGrouping { switch strings.ToLower(groupings) { case "all": return AllGrouping case "yr", "year", "years": return YearGrouping case "mo", "month", "months": return MonthGrouping case "wk", "week", "weeks": return WeekGrouping case "day", "days": return DayGrouping default: return UnknownGrouping } }
[ "func", "TimeGroupingFromStr", "(", "groupings", "string", ")", "TimeBasedGrouping", "{", "switch", "strings", ".", "ToLower", "(", "groupings", ")", "{", "case", "\"", "\"", ":", "return", "AllGrouping", "\n", "case", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ":", "return", "YearGrouping", "\n", "case", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ":", "return", "MonthGrouping", "\n", "case", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ":", "return", "WeekGrouping", "\n", "case", "\"", "\"", ",", "\"", "\"", ":", "return", "DayGrouping", "\n", "default", ":", "return", "UnknownGrouping", "\n", "}", "\n", "}" ]
// TimeGroupingFromStr converts groupings string to its respective TimeBasedGrouping value.
[ "TimeGroupingFromStr", "converts", "groupings", "string", "to", "its", "respective", "TimeBasedGrouping", "value", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/types.go#L411-L426
train
decred/dcrdata
db/dbtypes/types.go
ChoiceIndexFromStr
func ChoiceIndexFromStr(choice string) (VoteChoice, error) { switch choice { case "abstain": return Abstain, nil case "yes": return Yes, nil case "no": return No, nil default: return VoteChoiceUnknown, fmt.Errorf(`Vote Choice "%s" is unknown`, choice) } }
go
func ChoiceIndexFromStr(choice string) (VoteChoice, error) { switch choice { case "abstain": return Abstain, nil case "yes": return Yes, nil case "no": return No, nil default: return VoteChoiceUnknown, fmt.Errorf(`Vote Choice "%s" is unknown`, choice) } }
[ "func", "ChoiceIndexFromStr", "(", "choice", "string", ")", "(", "VoteChoice", ",", "error", ")", "{", "switch", "choice", "{", "case", "\"", "\"", ":", "return", "Abstain", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "Yes", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "No", ",", "nil", "\n", "default", ":", "return", "VoteChoiceUnknown", ",", "fmt", ".", "Errorf", "(", "`Vote Choice \"%s\" is unknown`", ",", "choice", ")", "\n", "}", "\n", "}" ]
// ChoiceIndexFromStr converts the vote choice string to a vote choice index.
[ "ChoiceIndexFromStr", "converts", "the", "vote", "choice", "string", "to", "a", "vote", "choice", "index", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/types.go#L488-L499
train
decred/dcrdata
db/dbtypes/types.go
Value
func (p VinTxPropertyARRAY) Value() (driver.Value, error) { j, err := json.Marshal(p) return j, err }
go
func (p VinTxPropertyARRAY) Value() (driver.Value, error) { j, err := json.Marshal(p) return j, err }
[ "func", "(", "p", "VinTxPropertyARRAY", ")", "Value", "(", ")", "(", "driver", ".", "Value", ",", "error", ")", "{", "j", ",", "err", ":=", "json", ".", "Marshal", "(", "p", ")", "\n", "return", "j", ",", "err", "\n", "}" ]
// Value satisfies driver.Valuer
[ "Value", "satisfies", "driver", ".", "Valuer" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/types.go#L585-L588
train
decred/dcrdata
db/dbtypes/types.go
Scan
func (p *VinTxPropertyARRAY) Scan(src interface{}) error { source, ok := src.([]byte) if !ok { return fmt.Errorf("scan type assertion .([]byte) failed") } var i interface{} err := json.Unmarshal(source, &i) if err != nil { return err } // Set this JSONB is, ok := i.([]interface{}) if !ok { return fmt.Errorf("type assertion .([]interface{}) failed") } numVin := len(is) ba := make(VinTxPropertyARRAY, numVin) for ii := range is { VinTxPropertyMapIface, ok := is[ii].(map[string]interface{}) if !ok { return fmt.Errorf("type assertion .(map[string]interface) failed") } b, _ := json.Marshal(VinTxPropertyMapIface) err := json.Unmarshal(b, &ba[ii]) if err != nil { return err } } *p = ba return nil }
go
func (p *VinTxPropertyARRAY) Scan(src interface{}) error { source, ok := src.([]byte) if !ok { return fmt.Errorf("scan type assertion .([]byte) failed") } var i interface{} err := json.Unmarshal(source, &i) if err != nil { return err } // Set this JSONB is, ok := i.([]interface{}) if !ok { return fmt.Errorf("type assertion .([]interface{}) failed") } numVin := len(is) ba := make(VinTxPropertyARRAY, numVin) for ii := range is { VinTxPropertyMapIface, ok := is[ii].(map[string]interface{}) if !ok { return fmt.Errorf("type assertion .(map[string]interface) failed") } b, _ := json.Marshal(VinTxPropertyMapIface) err := json.Unmarshal(b, &ba[ii]) if err != nil { return err } } *p = ba return nil }
[ "func", "(", "p", "*", "VinTxPropertyARRAY", ")", "Scan", "(", "src", "interface", "{", "}", ")", "error", "{", "source", ",", "ok", ":=", "src", ".", "(", "[", "]", "byte", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "i", "interface", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "source", ",", "&", "i", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Set this JSONB", "is", ",", "ok", ":=", "i", ".", "(", "[", "]", "interface", "{", "}", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "numVin", ":=", "len", "(", "is", ")", "\n", "ba", ":=", "make", "(", "VinTxPropertyARRAY", ",", "numVin", ")", "\n", "for", "ii", ":=", "range", "is", "{", "VinTxPropertyMapIface", ",", "ok", ":=", "is", "[", "ii", "]", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "b", ",", "_", ":=", "json", ".", "Marshal", "(", "VinTxPropertyMapIface", ")", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "b", ",", "&", "ba", "[", "ii", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "*", "p", "=", "ba", "\n\n", "return", "nil", "\n", "}" ]
// Scan satisfies sql.Scanner
[ "Scan", "satisfies", "sql", ".", "Scanner" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/types.go#L591-L624
train
decred/dcrdata
db/dbtypes/types.go
String
func (s DeletionSummary) String() string { summary := fmt.Sprintf("%9d Blocks purged\n", s.Blocks) summary += fmt.Sprintf("%9d Vins purged\n", s.Vins) summary += fmt.Sprintf("%9d Vouts purged\n", s.Vouts) summary += fmt.Sprintf("%9d Addresses purged\n", s.Addresses) summary += fmt.Sprintf("%9d Transactions purged\n", s.Transactions) summary += fmt.Sprintf("%9d Tickets purged\n", s.Tickets) summary += fmt.Sprintf("%9d Votes purged\n", s.Votes) summary += fmt.Sprintf("%9d Misses purged", s.Misses) return summary }
go
func (s DeletionSummary) String() string { summary := fmt.Sprintf("%9d Blocks purged\n", s.Blocks) summary += fmt.Sprintf("%9d Vins purged\n", s.Vins) summary += fmt.Sprintf("%9d Vouts purged\n", s.Vouts) summary += fmt.Sprintf("%9d Addresses purged\n", s.Addresses) summary += fmt.Sprintf("%9d Transactions purged\n", s.Transactions) summary += fmt.Sprintf("%9d Tickets purged\n", s.Tickets) summary += fmt.Sprintf("%9d Votes purged\n", s.Votes) summary += fmt.Sprintf("%9d Misses purged", s.Misses) return summary }
[ "func", "(", "s", "DeletionSummary", ")", "String", "(", ")", "string", "{", "summary", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "s", ".", "Blocks", ")", "\n", "summary", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "s", ".", "Vins", ")", "\n", "summary", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "s", ".", "Vouts", ")", "\n", "summary", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "s", ".", "Addresses", ")", "\n", "summary", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "s", ".", "Transactions", ")", "\n", "summary", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "s", ".", "Tickets", ")", "\n", "summary", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "s", ".", "Votes", ")", "\n", "summary", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "s", ".", "Misses", ")", "\n", "return", "summary", "\n", "}" ]
// String makes a pretty summary of the totals.
[ "String", "makes", "a", "pretty", "summary", "of", "the", "totals", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/types.go#L634-L644
train
decred/dcrdata
db/dbtypes/types.go
Reduce
func (ds DeletionSummarySlice) Reduce() DeletionSummary { var s DeletionSummary for i := range ds { s.Blocks += ds[i].Blocks s.Vins += ds[i].Vins s.Vouts += ds[i].Vouts s.Addresses += ds[i].Addresses s.Transactions += ds[i].Transactions s.Tickets += ds[i].Tickets s.Votes += ds[i].Votes s.Misses += ds[i].Misses } return s }
go
func (ds DeletionSummarySlice) Reduce() DeletionSummary { var s DeletionSummary for i := range ds { s.Blocks += ds[i].Blocks s.Vins += ds[i].Vins s.Vouts += ds[i].Vouts s.Addresses += ds[i].Addresses s.Transactions += ds[i].Transactions s.Tickets += ds[i].Tickets s.Votes += ds[i].Votes s.Misses += ds[i].Misses } return s }
[ "func", "(", "ds", "DeletionSummarySlice", ")", "Reduce", "(", ")", "DeletionSummary", "{", "var", "s", "DeletionSummary", "\n", "for", "i", ":=", "range", "ds", "{", "s", ".", "Blocks", "+=", "ds", "[", "i", "]", ".", "Blocks", "\n", "s", ".", "Vins", "+=", "ds", "[", "i", "]", ".", "Vins", "\n", "s", ".", "Vouts", "+=", "ds", "[", "i", "]", ".", "Vouts", "\n", "s", ".", "Addresses", "+=", "ds", "[", "i", "]", ".", "Addresses", "\n", "s", ".", "Transactions", "+=", "ds", "[", "i", "]", ".", "Transactions", "\n", "s", ".", "Tickets", "+=", "ds", "[", "i", "]", ".", "Tickets", "\n", "s", ".", "Votes", "+=", "ds", "[", "i", "]", ".", "Votes", "\n", "s", ".", "Misses", "+=", "ds", "[", "i", "]", ".", "Misses", "\n", "}", "\n", "return", "s", "\n", "}" ]
// Reduce returns a single DeletionSummary with the corresponding fields summed.
[ "Reduce", "returns", "a", "single", "DeletionSummary", "with", "the", "corresponding", "fields", "summed", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/types.go#L650-L663
train
decred/dcrdata
db/dbtypes/types.go
ReduceAddressHistory
func ReduceAddressHistory(addrHist []*AddressRow) (*AddressInfo, float64, float64) { if len(addrHist) == 0 { return nil, 0, 0 } var received, sent, fromStake, toStake int64 var transactions, creditTxns, debitTxns []*AddressTx for _, addrOut := range addrHist { if !addrOut.ValidMainChain { continue } coin := dcrutil.Amount(addrOut.Value).ToCoin() txType := txhelpers.TxTypeToString(int(addrOut.TxType)) tx := AddressTx{ Time: addrOut.TxBlockTime, InOutID: addrOut.TxVinVoutIndex, TxID: addrOut.TxHash, TxType: txType, MatchedTx: addrOut.MatchingTxHash, IsFunding: addrOut.IsFunding, MergedTxnCount: addrOut.MergedCount, } if addrOut.IsFunding { // Funding transaction received += int64(addrOut.Value) tx.ReceivedTotal = coin creditTxns = append(creditTxns, &tx) if txType != "Regular" { fromStake += int64(addrOut.Value) } } else { // Spending transaction sent += int64(addrOut.Value) tx.SentTotal = coin debitTxns = append(debitTxns, &tx) if txType != "Regular" { toStake += int64(addrOut.Value) } } transactions = append(transactions, &tx) } var fromStakeFraction, toStakeFraction float64 if sent > 0 { toStakeFraction = float64(toStake) / float64(sent) } if received > 0 { fromStakeFraction = float64(fromStake) / float64(received) } ai := &AddressInfo{ Address: addrHist[0].Address, Transactions: transactions, TxnsFunding: creditTxns, TxnsSpending: debitTxns, NumFundingTxns: int64(len(creditTxns)), NumSpendingTxns: int64(len(debitTxns)), AmountReceived: dcrutil.Amount(received), AmountSent: dcrutil.Amount(sent), AmountUnspent: dcrutil.Amount(received - sent), } return ai, fromStakeFraction, toStakeFraction }
go
func ReduceAddressHistory(addrHist []*AddressRow) (*AddressInfo, float64, float64) { if len(addrHist) == 0 { return nil, 0, 0 } var received, sent, fromStake, toStake int64 var transactions, creditTxns, debitTxns []*AddressTx for _, addrOut := range addrHist { if !addrOut.ValidMainChain { continue } coin := dcrutil.Amount(addrOut.Value).ToCoin() txType := txhelpers.TxTypeToString(int(addrOut.TxType)) tx := AddressTx{ Time: addrOut.TxBlockTime, InOutID: addrOut.TxVinVoutIndex, TxID: addrOut.TxHash, TxType: txType, MatchedTx: addrOut.MatchingTxHash, IsFunding: addrOut.IsFunding, MergedTxnCount: addrOut.MergedCount, } if addrOut.IsFunding { // Funding transaction received += int64(addrOut.Value) tx.ReceivedTotal = coin creditTxns = append(creditTxns, &tx) if txType != "Regular" { fromStake += int64(addrOut.Value) } } else { // Spending transaction sent += int64(addrOut.Value) tx.SentTotal = coin debitTxns = append(debitTxns, &tx) if txType != "Regular" { toStake += int64(addrOut.Value) } } transactions = append(transactions, &tx) } var fromStakeFraction, toStakeFraction float64 if sent > 0 { toStakeFraction = float64(toStake) / float64(sent) } if received > 0 { fromStakeFraction = float64(fromStake) / float64(received) } ai := &AddressInfo{ Address: addrHist[0].Address, Transactions: transactions, TxnsFunding: creditTxns, TxnsSpending: debitTxns, NumFundingTxns: int64(len(creditTxns)), NumSpendingTxns: int64(len(debitTxns)), AmountReceived: dcrutil.Amount(received), AmountSent: dcrutil.Amount(sent), AmountUnspent: dcrutil.Amount(received - sent), } return ai, fromStakeFraction, toStakeFraction }
[ "func", "ReduceAddressHistory", "(", "addrHist", "[", "]", "*", "AddressRow", ")", "(", "*", "AddressInfo", ",", "float64", ",", "float64", ")", "{", "if", "len", "(", "addrHist", ")", "==", "0", "{", "return", "nil", ",", "0", ",", "0", "\n", "}", "\n\n", "var", "received", ",", "sent", ",", "fromStake", ",", "toStake", "int64", "\n", "var", "transactions", ",", "creditTxns", ",", "debitTxns", "[", "]", "*", "AddressTx", "\n", "for", "_", ",", "addrOut", ":=", "range", "addrHist", "{", "if", "!", "addrOut", ".", "ValidMainChain", "{", "continue", "\n", "}", "\n", "coin", ":=", "dcrutil", ".", "Amount", "(", "addrOut", ".", "Value", ")", ".", "ToCoin", "(", ")", "\n", "txType", ":=", "txhelpers", ".", "TxTypeToString", "(", "int", "(", "addrOut", ".", "TxType", ")", ")", "\n", "tx", ":=", "AddressTx", "{", "Time", ":", "addrOut", ".", "TxBlockTime", ",", "InOutID", ":", "addrOut", ".", "TxVinVoutIndex", ",", "TxID", ":", "addrOut", ".", "TxHash", ",", "TxType", ":", "txType", ",", "MatchedTx", ":", "addrOut", ".", "MatchingTxHash", ",", "IsFunding", ":", "addrOut", ".", "IsFunding", ",", "MergedTxnCount", ":", "addrOut", ".", "MergedCount", ",", "}", "\n\n", "if", "addrOut", ".", "IsFunding", "{", "// Funding transaction", "received", "+=", "int64", "(", "addrOut", ".", "Value", ")", "\n", "tx", ".", "ReceivedTotal", "=", "coin", "\n", "creditTxns", "=", "append", "(", "creditTxns", ",", "&", "tx", ")", "\n", "if", "txType", "!=", "\"", "\"", "{", "fromStake", "+=", "int64", "(", "addrOut", ".", "Value", ")", "\n", "}", "\n", "}", "else", "{", "// Spending transaction", "sent", "+=", "int64", "(", "addrOut", ".", "Value", ")", "\n", "tx", ".", "SentTotal", "=", "coin", "\n", "debitTxns", "=", "append", "(", "debitTxns", ",", "&", "tx", ")", "\n", "if", "txType", "!=", "\"", "\"", "{", "toStake", "+=", "int64", "(", "addrOut", ".", "Value", ")", "\n", "}", "\n", "}", "\n\n", "transactions", "=", "append", "(", "transactions", ",", "&", "tx", ")", "\n", "}", "\n\n", "var", "fromStakeFraction", ",", "toStakeFraction", "float64", "\n", "if", "sent", ">", "0", "{", "toStakeFraction", "=", "float64", "(", "toStake", ")", "/", "float64", "(", "sent", ")", "\n", "}", "\n", "if", "received", ">", "0", "{", "fromStakeFraction", "=", "float64", "(", "fromStake", ")", "/", "float64", "(", "received", ")", "\n", "}", "\n\n", "ai", ":=", "&", "AddressInfo", "{", "Address", ":", "addrHist", "[", "0", "]", ".", "Address", ",", "Transactions", ":", "transactions", ",", "TxnsFunding", ":", "creditTxns", ",", "TxnsSpending", ":", "debitTxns", ",", "NumFundingTxns", ":", "int64", "(", "len", "(", "creditTxns", ")", ")", ",", "NumSpendingTxns", ":", "int64", "(", "len", "(", "debitTxns", ")", ")", ",", "AmountReceived", ":", "dcrutil", ".", "Amount", "(", "received", ")", ",", "AmountSent", ":", "dcrutil", ".", "Amount", "(", "sent", ")", ",", "AmountUnspent", ":", "dcrutil", ".", "Amount", "(", "received", "-", "sent", ")", ",", "}", "\n", "return", "ai", ",", "fromStakeFraction", ",", "toStakeFraction", "\n", "}" ]
// ReduceAddressHistory generates a template AddressInfo from a slice of // AddressRow. All fields except NumUnconfirmed and Transactions are set // completely. Transactions is partially set, with each transaction having only // the TxID and ReceivedTotal set. The rest of the data should be filled in by // other means, such as RPC calls or database queries. Additionally, the // fractions of sent and received from stake-related transactions is returned. // These values are analogous to AddressBalance.FromStake and // AddressBalance.ToStake, but based on only the rows given.
[ "ReduceAddressHistory", "generates", "a", "template", "AddressInfo", "from", "a", "slice", "of", "AddressRow", ".", "All", "fields", "except", "NumUnconfirmed", "and", "Transactions", "are", "set", "completely", ".", "Transactions", "is", "partially", "set", "with", "each", "transaction", "having", "only", "the", "TxID", "and", "ReceivedTotal", "set", ".", "The", "rest", "of", "the", "data", "should", "be", "filled", "in", "by", "other", "means", "such", "as", "RPC", "calls", "or", "database", "queries", ".", "Additionally", "the", "fractions", "of", "sent", "and", "received", "from", "stake", "-", "related", "transactions", "is", "returned", ".", "These", "values", "are", "analogous", "to", "AddressBalance", ".", "FromStake", "and", "AddressBalance", ".", "ToStake", "but", "based", "on", "only", "the", "rows", "given", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/types.go#L1567-L1631
train
decred/dcrdata
stakedb/chainmonitor.go
ReorgHandler
func (p *ChainMonitor) ReorgHandler() { defer p.wg.Done() out: for { //keepon: select { case reorgData, ok := <-p.reorgChan: p.mtx.Lock() if !ok { p.mtx.Unlock() log.Warnf("Reorg channel closed.") break out } newHeight, oldHeight := reorgData.NewChainHeight, reorgData.OldChainHeight newHash, oldHash := reorgData.NewChainHead, reorgData.OldChainHead log.Infof("Reorganize started. NEW head block %v at height %d.", newHash, newHeight) log.Infof("Reorganize started. OLD head block %v at height %d.", oldHash, oldHeight) // Switch to the side chain. stakeDBTipHeight, stakeDBTipHash, err := p.switchToSideChain(reorgData) if err != nil { log.Errorf("switchToSideChain failed: %v", err) } if stakeDBTipHeight != newHeight { log.Errorf("stakeDBTipHeight is %d, expected %d", stakeDBTipHeight, newHeight) } if *stakeDBTipHash != newHash { log.Errorf("stakeDBTipHash is %d, expected %d", stakeDBTipHash, newHash) } p.mtx.Unlock() reorgData.WG.Done() case <-p.ctx.Done(): log.Debugf("Got quit signal. Exiting stakedb reorg notification handler.") break out } } }
go
func (p *ChainMonitor) ReorgHandler() { defer p.wg.Done() out: for { //keepon: select { case reorgData, ok := <-p.reorgChan: p.mtx.Lock() if !ok { p.mtx.Unlock() log.Warnf("Reorg channel closed.") break out } newHeight, oldHeight := reorgData.NewChainHeight, reorgData.OldChainHeight newHash, oldHash := reorgData.NewChainHead, reorgData.OldChainHead log.Infof("Reorganize started. NEW head block %v at height %d.", newHash, newHeight) log.Infof("Reorganize started. OLD head block %v at height %d.", oldHash, oldHeight) // Switch to the side chain. stakeDBTipHeight, stakeDBTipHash, err := p.switchToSideChain(reorgData) if err != nil { log.Errorf("switchToSideChain failed: %v", err) } if stakeDBTipHeight != newHeight { log.Errorf("stakeDBTipHeight is %d, expected %d", stakeDBTipHeight, newHeight) } if *stakeDBTipHash != newHash { log.Errorf("stakeDBTipHash is %d, expected %d", stakeDBTipHash, newHash) } p.mtx.Unlock() reorgData.WG.Done() case <-p.ctx.Done(): log.Debugf("Got quit signal. Exiting stakedb reorg notification handler.") break out } } }
[ "func", "(", "p", "*", "ChainMonitor", ")", "ReorgHandler", "(", ")", "{", "defer", "p", ".", "wg", ".", "Done", "(", ")", "\n", "out", ":", "for", "{", "//keepon:", "select", "{", "case", "reorgData", ",", "ok", ":=", "<-", "p", ".", "reorgChan", ":", "p", ".", "mtx", ".", "Lock", "(", ")", "\n", "if", "!", "ok", "{", "p", ".", "mtx", ".", "Unlock", "(", ")", "\n", "log", ".", "Warnf", "(", "\"", "\"", ")", "\n", "break", "out", "\n", "}", "\n\n", "newHeight", ",", "oldHeight", ":=", "reorgData", ".", "NewChainHeight", ",", "reorgData", ".", "OldChainHeight", "\n", "newHash", ",", "oldHash", ":=", "reorgData", ".", "NewChainHead", ",", "reorgData", ".", "OldChainHead", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ",", "newHash", ",", "newHeight", ")", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "oldHash", ",", "oldHeight", ")", "\n\n", "// Switch to the side chain.", "stakeDBTipHeight", ",", "stakeDBTipHash", ",", "err", ":=", "p", ".", "switchToSideChain", "(", "reorgData", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "stakeDBTipHeight", "!=", "newHeight", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "stakeDBTipHeight", ",", "newHeight", ")", "\n", "}", "\n", "if", "*", "stakeDBTipHash", "!=", "newHash", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "stakeDBTipHash", ",", "newHash", ")", "\n", "}", "\n\n", "p", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "reorgData", ".", "WG", ".", "Done", "(", ")", "\n\n", "case", "<-", "p", ".", "ctx", ".", "Done", "(", ")", ":", "log", ".", "Debugf", "(", "\"", "\"", ")", "\n", "break", "out", "\n", "}", "\n", "}", "\n", "}" ]
// ReorgHandler receives notification of a chain reorganization and initiates a // corresponding reorganization of the stakedb.StakeDatabase.
[ "ReorgHandler", "receives", "notification", "of", "a", "chain", "reorganization", "and", "initiates", "a", "corresponding", "reorganization", "of", "the", "stakedb", ".", "StakeDatabase", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/chainmonitor.go#L155-L200
train
decred/dcrdata
api/types/apicache.go
NewAPICache
func NewAPICache(capacity uint32) *APICache { apic := &APICache{ capacity: capacity, blockCache: make(blockCache), MainchainBlocks: make(map[int64]chainhash.Hash, capacity), expireQueue: NewBlockPriorityQueue(capacity), } go WatchPriorityQueue(apic.expireQueue) return apic }
go
func NewAPICache(capacity uint32) *APICache { apic := &APICache{ capacity: capacity, blockCache: make(blockCache), MainchainBlocks: make(map[int64]chainhash.Hash, capacity), expireQueue: NewBlockPriorityQueue(capacity), } go WatchPriorityQueue(apic.expireQueue) return apic }
[ "func", "NewAPICache", "(", "capacity", "uint32", ")", "*", "APICache", "{", "apic", ":=", "&", "APICache", "{", "capacity", ":", "capacity", ",", "blockCache", ":", "make", "(", "blockCache", ")", ",", "MainchainBlocks", ":", "make", "(", "map", "[", "int64", "]", "chainhash", ".", "Hash", ",", "capacity", ")", ",", "expireQueue", ":", "NewBlockPriorityQueue", "(", "capacity", ")", ",", "}", "\n\n", "go", "WatchPriorityQueue", "(", "apic", ".", "expireQueue", ")", "\n\n", "return", "apic", "\n", "}" ]
// NewAPICache creates an APICache with the specified capacity.
[ "NewAPICache", "creates", "an", "APICache", "with", "the", "specified", "capacity", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L66-L77
train
decred/dcrdata
api/types/apicache.go
Utilization
func (apic *APICache) Utilization() float64 { apic.mtx.RLock() defer apic.mtx.RUnlock() return 100.0 * float64(len(apic.blockCache)) / float64(apic.capacity) }
go
func (apic *APICache) Utilization() float64 { apic.mtx.RLock() defer apic.mtx.RUnlock() return 100.0 * float64(len(apic.blockCache)) / float64(apic.capacity) }
[ "func", "(", "apic", "*", "APICache", ")", "Utilization", "(", ")", "float64", "{", "apic", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "apic", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "100.0", "*", "float64", "(", "len", "(", "apic", ".", "blockCache", ")", ")", "/", "float64", "(", "apic", ".", "capacity", ")", "\n", "}" ]
// Utilization returns the percent utilization of the cache
[ "Utilization", "returns", "the", "percent", "utilization", "of", "the", "cache" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L103-L107
train
decred/dcrdata
api/types/apicache.go
StoreStakeInfo
func (apic *APICache) StoreStakeInfo(stakeInfo *StakeInfoExtended) error { if !apic.IsEnabled() { fmt.Printf("API cache is disabled") return nil } height := stakeInfo.Feeinfo.Height hash, err := chainhash.NewHashFromStr(stakeInfo.Hash) if err != nil { panic("that's not a real hash") } apic.mtx.Lock() defer apic.mtx.Unlock() b, ok := apic.blockCache[*hash] if ok { // If CachedBlock found, but without stakeInfo, just add it in. if b.stakeInfo == nil { b.stakeInfo = stakeInfo return nil } fmt.Printf("Already have the block's stake info in cache for block %s at height %d.\n", hash, height) return nil } // Insert into the cache and expire queue. cachedBlock := newCachedBlock(nil, stakeInfo) cachedBlock.Access() // Insert into queue and delete any cached block that was removed. wasAdded, removedBlock, removedHeight := apic.expireQueue.Insert(nil, stakeInfo) if removedBlock != nil { delete(apic.blockCache, *removedBlock) delete(apic.MainchainBlocks, removedHeight) } // Add new block to to the block cache, if it went into the queue. if wasAdded { apic.blockCache[*hash] = cachedBlock apic.MainchainBlocks[int64(height)] = *hash } return nil }
go
func (apic *APICache) StoreStakeInfo(stakeInfo *StakeInfoExtended) error { if !apic.IsEnabled() { fmt.Printf("API cache is disabled") return nil } height := stakeInfo.Feeinfo.Height hash, err := chainhash.NewHashFromStr(stakeInfo.Hash) if err != nil { panic("that's not a real hash") } apic.mtx.Lock() defer apic.mtx.Unlock() b, ok := apic.blockCache[*hash] if ok { // If CachedBlock found, but without stakeInfo, just add it in. if b.stakeInfo == nil { b.stakeInfo = stakeInfo return nil } fmt.Printf("Already have the block's stake info in cache for block %s at height %d.\n", hash, height) return nil } // Insert into the cache and expire queue. cachedBlock := newCachedBlock(nil, stakeInfo) cachedBlock.Access() // Insert into queue and delete any cached block that was removed. wasAdded, removedBlock, removedHeight := apic.expireQueue.Insert(nil, stakeInfo) if removedBlock != nil { delete(apic.blockCache, *removedBlock) delete(apic.MainchainBlocks, removedHeight) } // Add new block to to the block cache, if it went into the queue. if wasAdded { apic.blockCache[*hash] = cachedBlock apic.MainchainBlocks[int64(height)] = *hash } return nil }
[ "func", "(", "apic", "*", "APICache", ")", "StoreStakeInfo", "(", "stakeInfo", "*", "StakeInfoExtended", ")", "error", "{", "if", "!", "apic", ".", "IsEnabled", "(", ")", "{", "fmt", ".", "Printf", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "height", ":=", "stakeInfo", ".", "Feeinfo", ".", "Height", "\n", "hash", ",", "err", ":=", "chainhash", ".", "NewHashFromStr", "(", "stakeInfo", ".", "Hash", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "apic", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "apic", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "b", ",", "ok", ":=", "apic", ".", "blockCache", "[", "*", "hash", "]", "\n", "if", "ok", "{", "// If CachedBlock found, but without stakeInfo, just add it in.", "if", "b", ".", "stakeInfo", "==", "nil", "{", "b", ".", "stakeInfo", "=", "stakeInfo", "\n", "return", "nil", "\n", "}", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "hash", ",", "height", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// Insert into the cache and expire queue.", "cachedBlock", ":=", "newCachedBlock", "(", "nil", ",", "stakeInfo", ")", "\n", "cachedBlock", ".", "Access", "(", ")", "\n\n", "// Insert into queue and delete any cached block that was removed.", "wasAdded", ",", "removedBlock", ",", "removedHeight", ":=", "apic", ".", "expireQueue", ".", "Insert", "(", "nil", ",", "stakeInfo", ")", "\n", "if", "removedBlock", "!=", "nil", "{", "delete", "(", "apic", ".", "blockCache", ",", "*", "removedBlock", ")", "\n", "delete", "(", "apic", ".", "MainchainBlocks", ",", "removedHeight", ")", "\n", "}", "\n\n", "// Add new block to to the block cache, if it went into the queue.", "if", "wasAdded", "{", "apic", ".", "blockCache", "[", "*", "hash", "]", "=", "cachedBlock", "\n", "apic", ".", "MainchainBlocks", "[", "int64", "(", "height", ")", "]", "=", "*", "hash", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// StoreStakeInfo caches the input StakeInfoExtended, if the priority queue // indicates that the block should be added.
[ "StoreStakeInfo", "caches", "the", "input", "StakeInfoExtended", "if", "the", "priority", "queue", "indicates", "that", "the", "block", "should", "be", "added", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L176-L221
train
decred/dcrdata
api/types/apicache.go
removeCachedBlock
func (apic *APICache) removeCachedBlock(cachedBlock *CachedBlock) { if cachedBlock == nil { return } // remove the block from the expiration queue apic.expireQueue.RemoveBlock(cachedBlock) // remove from block cache if hash, err := chainhash.NewHashFromStr(cachedBlock.hash); err != nil { delete(apic.blockCache, *hash) } delete(apic.MainchainBlocks, int64(cachedBlock.height)) }
go
func (apic *APICache) removeCachedBlock(cachedBlock *CachedBlock) { if cachedBlock == nil { return } // remove the block from the expiration queue apic.expireQueue.RemoveBlock(cachedBlock) // remove from block cache if hash, err := chainhash.NewHashFromStr(cachedBlock.hash); err != nil { delete(apic.blockCache, *hash) } delete(apic.MainchainBlocks, int64(cachedBlock.height)) }
[ "func", "(", "apic", "*", "APICache", ")", "removeCachedBlock", "(", "cachedBlock", "*", "CachedBlock", ")", "{", "if", "cachedBlock", "==", "nil", "{", "return", "\n", "}", "\n", "// remove the block from the expiration queue", "apic", ".", "expireQueue", ".", "RemoveBlock", "(", "cachedBlock", ")", "\n", "// remove from block cache", "if", "hash", ",", "err", ":=", "chainhash", ".", "NewHashFromStr", "(", "cachedBlock", ".", "hash", ")", ";", "err", "!=", "nil", "{", "delete", "(", "apic", ".", "blockCache", ",", "*", "hash", ")", "\n", "}", "\n", "delete", "(", "apic", ".", "MainchainBlocks", ",", "int64", "(", "cachedBlock", ".", "height", ")", ")", "\n", "}" ]
// removeCachedBlock is the non-thread-safe version of RemoveCachedBlock.
[ "removeCachedBlock", "is", "the", "non", "-", "thread", "-", "safe", "version", "of", "RemoveCachedBlock", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L224-L235
train
decred/dcrdata
api/types/apicache.go
RemoveCachedBlock
func (apic *APICache) RemoveCachedBlock(cachedBlock *CachedBlock) { apic.mtx.Lock() defer apic.mtx.Unlock() apic.removeCachedBlock(cachedBlock) }
go
func (apic *APICache) RemoveCachedBlock(cachedBlock *CachedBlock) { apic.mtx.Lock() defer apic.mtx.Unlock() apic.removeCachedBlock(cachedBlock) }
[ "func", "(", "apic", "*", "APICache", ")", "RemoveCachedBlock", "(", "cachedBlock", "*", "CachedBlock", ")", "{", "apic", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "apic", ".", "mtx", ".", "Unlock", "(", ")", "\n", "apic", ".", "removeCachedBlock", "(", "cachedBlock", ")", "\n", "}" ]
// RemoveCachedBlock removes the input CachedBlock the cache. If the block is // not in cache, this is essentially a silent no-op.
[ "RemoveCachedBlock", "removes", "the", "input", "CachedBlock", "the", "cache", ".", "If", "the", "block", "is", "not", "in", "cache", "this", "is", "essentially", "a", "silent", "no", "-", "op", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L239-L243
train
decred/dcrdata
api/types/apicache.go
RemoveCachedBlockByHeight
func (apic *APICache) RemoveCachedBlockByHeight(height int64) { apic.mtx.Lock() defer apic.mtx.Unlock() hash, ok := apic.MainchainBlocks[height] if !ok { return } cb := apic.getCachedBlockByHash(hash) apic.removeCachedBlock(cb) }
go
func (apic *APICache) RemoveCachedBlockByHeight(height int64) { apic.mtx.Lock() defer apic.mtx.Unlock() hash, ok := apic.MainchainBlocks[height] if !ok { return } cb := apic.getCachedBlockByHash(hash) apic.removeCachedBlock(cb) }
[ "func", "(", "apic", "*", "APICache", ")", "RemoveCachedBlockByHeight", "(", "height", "int64", ")", "{", "apic", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "apic", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "hash", ",", "ok", ":=", "apic", ".", "MainchainBlocks", "[", "height", "]", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n\n", "cb", ":=", "apic", ".", "getCachedBlockByHash", "(", "hash", ")", "\n", "apic", ".", "removeCachedBlock", "(", "cb", ")", "\n", "}" ]
// RemoveCachedBlockByHeight attempts to remove a CachedBlock with the given // height.
[ "RemoveCachedBlockByHeight", "attempts", "to", "remove", "a", "CachedBlock", "with", "the", "given", "height", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L247-L258
train
decred/dcrdata
api/types/apicache.go
blockHash
func (apic *APICache) blockHash(height int64) (chainhash.Hash, bool) { apic.mtx.RLock() defer apic.mtx.RUnlock() hash, ok := apic.MainchainBlocks[height] return hash, ok }
go
func (apic *APICache) blockHash(height int64) (chainhash.Hash, bool) { apic.mtx.RLock() defer apic.mtx.RUnlock() hash, ok := apic.MainchainBlocks[height] return hash, ok }
[ "func", "(", "apic", "*", "APICache", ")", "blockHash", "(", "height", "int64", ")", "(", "chainhash", ".", "Hash", ",", "bool", ")", "{", "apic", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "apic", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "hash", ",", "ok", ":=", "apic", ".", "MainchainBlocks", "[", "height", "]", "\n", "return", "hash", ",", "ok", "\n", "}" ]
// blockHash attempts to get the block hash for the main chain block at the // given height. The boolean indicates a cache miss.
[ "blockHash", "attempts", "to", "get", "the", "block", "hash", "for", "the", "main", "chain", "block", "at", "the", "given", "height", ".", "The", "boolean", "indicates", "a", "cache", "miss", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L262-L267
train
decred/dcrdata
api/types/apicache.go
GetBlockSize
func (apic *APICache) GetBlockSize(height int64) int32 { if !apic.IsEnabled() { return -1 } cachedBlock := apic.GetCachedBlockByHeight(height) if cachedBlock != nil && cachedBlock.summary != nil { return int32(cachedBlock.summary.Size) } return -1 }
go
func (apic *APICache) GetBlockSize(height int64) int32 { if !apic.IsEnabled() { return -1 } cachedBlock := apic.GetCachedBlockByHeight(height) if cachedBlock != nil && cachedBlock.summary != nil { return int32(cachedBlock.summary.Size) } return -1 }
[ "func", "(", "apic", "*", "APICache", ")", "GetBlockSize", "(", "height", "int64", ")", "int32", "{", "if", "!", "apic", ".", "IsEnabled", "(", ")", "{", "return", "-", "1", "\n", "}", "\n", "cachedBlock", ":=", "apic", ".", "GetCachedBlockByHeight", "(", "height", ")", "\n", "if", "cachedBlock", "!=", "nil", "&&", "cachedBlock", ".", "summary", "!=", "nil", "{", "return", "int32", "(", "cachedBlock", ".", "summary", ".", "Size", ")", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// GetBlockSize attempts to retrieve the block size for the input height. The // return is -1 if no block with that height is cached.
[ "GetBlockSize", "attempts", "to", "retrieve", "the", "block", "size", "for", "the", "input", "height", ".", "The", "return", "is", "-", "1", "if", "no", "block", "with", "that", "height", "is", "cached", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L284-L293
train
decred/dcrdata
api/types/apicache.go
GetBlockSummary
func (apic *APICache) GetBlockSummary(height int64) *BlockDataBasic { if !apic.IsEnabled() { return nil } cachedBlock := apic.GetCachedBlockByHeight(height) if cachedBlock != nil { return cachedBlock.summary } return nil }
go
func (apic *APICache) GetBlockSummary(height int64) *BlockDataBasic { if !apic.IsEnabled() { return nil } cachedBlock := apic.GetCachedBlockByHeight(height) if cachedBlock != nil { return cachedBlock.summary } return nil }
[ "func", "(", "apic", "*", "APICache", ")", "GetBlockSummary", "(", "height", "int64", ")", "*", "BlockDataBasic", "{", "if", "!", "apic", ".", "IsEnabled", "(", ")", "{", "return", "nil", "\n", "}", "\n", "cachedBlock", ":=", "apic", ".", "GetCachedBlockByHeight", "(", "height", ")", "\n", "if", "cachedBlock", "!=", "nil", "{", "return", "cachedBlock", ".", "summary", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetBlockSummary attempts to retrieve the block summary for the input height. // The return is nil if no block with that height is cached.
[ "GetBlockSummary", "attempts", "to", "retrieve", "the", "block", "summary", "for", "the", "input", "height", ".", "The", "return", "is", "nil", "if", "no", "block", "with", "that", "height", "is", "cached", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L297-L306
train
decred/dcrdata
api/types/apicache.go
GetStakeInfo
func (apic *APICache) GetStakeInfo(height int64) *StakeInfoExtended { if !apic.IsEnabled() { return nil } cachedBlock := apic.GetCachedBlockByHeight(height) if cachedBlock != nil { return cachedBlock.stakeInfo } return nil }
go
func (apic *APICache) GetStakeInfo(height int64) *StakeInfoExtended { if !apic.IsEnabled() { return nil } cachedBlock := apic.GetCachedBlockByHeight(height) if cachedBlock != nil { return cachedBlock.stakeInfo } return nil }
[ "func", "(", "apic", "*", "APICache", ")", "GetStakeInfo", "(", "height", "int64", ")", "*", "StakeInfoExtended", "{", "if", "!", "apic", ".", "IsEnabled", "(", ")", "{", "return", "nil", "\n", "}", "\n", "cachedBlock", ":=", "apic", ".", "GetCachedBlockByHeight", "(", "height", ")", "\n", "if", "cachedBlock", "!=", "nil", "{", "return", "cachedBlock", ".", "stakeInfo", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetStakeInfo attempts to retrieve the stake info for block at the the input // height. The return is nil if no block with that height is cached.
[ "GetStakeInfo", "attempts", "to", "retrieve", "the", "stake", "info", "for", "block", "at", "the", "the", "input", "height", ".", "The", "return", "is", "nil", "if", "no", "block", "with", "that", "height", "is", "cached", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L310-L319
train
decred/dcrdata
api/types/apicache.go
GetStakeInfoByHash
func (apic *APICache) GetStakeInfoByHash(hash string) *StakeInfoExtended { if !apic.IsEnabled() { return nil } cachedBlock := apic.GetCachedBlockByHashStr(hash) if cachedBlock != nil { return cachedBlock.stakeInfo } return nil }
go
func (apic *APICache) GetStakeInfoByHash(hash string) *StakeInfoExtended { if !apic.IsEnabled() { return nil } cachedBlock := apic.GetCachedBlockByHashStr(hash) if cachedBlock != nil { return cachedBlock.stakeInfo } return nil }
[ "func", "(", "apic", "*", "APICache", ")", "GetStakeInfoByHash", "(", "hash", "string", ")", "*", "StakeInfoExtended", "{", "if", "!", "apic", ".", "IsEnabled", "(", ")", "{", "return", "nil", "\n", "}", "\n", "cachedBlock", ":=", "apic", ".", "GetCachedBlockByHashStr", "(", "hash", ")", "\n", "if", "cachedBlock", "!=", "nil", "{", "return", "cachedBlock", ".", "stakeInfo", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetStakeInfoByHash attempts to retrieve the stake info for block with the // input hash. The return is nil if no block with that hash is cached.
[ "GetStakeInfoByHash", "attempts", "to", "retrieve", "the", "stake", "info", "for", "block", "with", "the", "input", "hash", ".", "The", "return", "is", "nil", "if", "no", "block", "with", "that", "hash", "is", "cached", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L323-L332
train
decred/dcrdata
api/types/apicache.go
GetCachedBlockByHeight
func (apic *APICache) GetCachedBlockByHeight(height int64) *CachedBlock { apic.mtx.Lock() defer apic.mtx.Unlock() hash, ok := apic.MainchainBlocks[height] if !ok { return nil } return apic.getCachedBlockByHash(hash) }
go
func (apic *APICache) GetCachedBlockByHeight(height int64) *CachedBlock { apic.mtx.Lock() defer apic.mtx.Unlock() hash, ok := apic.MainchainBlocks[height] if !ok { return nil } return apic.getCachedBlockByHash(hash) }
[ "func", "(", "apic", "*", "APICache", ")", "GetCachedBlockByHeight", "(", "height", "int64", ")", "*", "CachedBlock", "{", "apic", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "apic", ".", "mtx", ".", "Unlock", "(", ")", "\n", "hash", ",", "ok", ":=", "apic", ".", "MainchainBlocks", "[", "height", "]", "\n", "if", "!", "ok", "{", "return", "nil", "\n", "}", "\n", "return", "apic", ".", "getCachedBlockByHash", "(", "hash", ")", "\n", "}" ]
// GetCachedBlockByHeight attempts to fetch a CachedBlock with the given height. // The return is nil if no block with that height is cached.
[ "GetCachedBlockByHeight", "attempts", "to", "fetch", "a", "CachedBlock", "with", "the", "given", "height", ".", "The", "return", "is", "nil", "if", "no", "block", "with", "that", "height", "is", "cached", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L336-L344
train
decred/dcrdata
api/types/apicache.go
GetBlockSummaryByHash
func (apic *APICache) GetBlockSummaryByHash(hash string) *BlockDataBasic { if !apic.IsEnabled() { return nil } cachedBlock := apic.GetCachedBlockByHashStr(hash) if cachedBlock != nil { return cachedBlock.summary } return nil }
go
func (apic *APICache) GetBlockSummaryByHash(hash string) *BlockDataBasic { if !apic.IsEnabled() { return nil } cachedBlock := apic.GetCachedBlockByHashStr(hash) if cachedBlock != nil { return cachedBlock.summary } return nil }
[ "func", "(", "apic", "*", "APICache", ")", "GetBlockSummaryByHash", "(", "hash", "string", ")", "*", "BlockDataBasic", "{", "if", "!", "apic", ".", "IsEnabled", "(", ")", "{", "return", "nil", "\n", "}", "\n", "cachedBlock", ":=", "apic", ".", "GetCachedBlockByHashStr", "(", "hash", ")", "\n", "if", "cachedBlock", "!=", "nil", "{", "return", "cachedBlock", ".", "summary", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetBlockSummaryByHash attempts to retrieve the block summary for the given // block hash. The return is nil if no block with that hash is cached.
[ "GetBlockSummaryByHash", "attempts", "to", "retrieve", "the", "block", "summary", "for", "the", "given", "block", "hash", ".", "The", "return", "is", "nil", "if", "no", "block", "with", "that", "hash", "is", "cached", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L348-L357
train
decred/dcrdata
api/types/apicache.go
GetCachedBlockByHashStr
func (apic *APICache) GetCachedBlockByHashStr(hashStr string) *CachedBlock { // Validate the hash string, and get a *chainhash.Hash hash, err := chainhash.NewHashFromStr(hashStr) if err != nil { fmt.Printf("that's not a real hash!") return nil } apic.mtx.Lock() defer apic.mtx.Unlock() return apic.getCachedBlockByHash(*hash) }
go
func (apic *APICache) GetCachedBlockByHashStr(hashStr string) *CachedBlock { // Validate the hash string, and get a *chainhash.Hash hash, err := chainhash.NewHashFromStr(hashStr) if err != nil { fmt.Printf("that's not a real hash!") return nil } apic.mtx.Lock() defer apic.mtx.Unlock() return apic.getCachedBlockByHash(*hash) }
[ "func", "(", "apic", "*", "APICache", ")", "GetCachedBlockByHashStr", "(", "hashStr", "string", ")", "*", "CachedBlock", "{", "// Validate the hash string, and get a *chainhash.Hash", "hash", ",", "err", ":=", "chainhash", ".", "NewHashFromStr", "(", "hashStr", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "apic", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "apic", ".", "mtx", ".", "Unlock", "(", ")", "\n", "return", "apic", ".", "getCachedBlockByHash", "(", "*", "hash", ")", "\n", "}" ]
// GetCachedBlockByHashStr attempts to fetch a CachedBlock with the given hash. // The return is nil if no block with that hash is cached.
[ "GetCachedBlockByHashStr", "attempts", "to", "fetch", "a", "CachedBlock", "with", "the", "given", "hash", ".", "The", "return", "is", "nil", "if", "no", "block", "with", "that", "hash", "is", "cached", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L361-L372
train
decred/dcrdata
api/types/apicache.go
GetCachedBlockByHash
func (apic *APICache) GetCachedBlockByHash(hash chainhash.Hash) *CachedBlock { // validate the chainhash.Hash if _, err := chainhash.NewHashFromStr(hash.String()); err != nil { fmt.Printf("that's not a real hash!") return nil } apic.mtx.Lock() defer apic.mtx.Unlock() return apic.getCachedBlockByHash(hash) }
go
func (apic *APICache) GetCachedBlockByHash(hash chainhash.Hash) *CachedBlock { // validate the chainhash.Hash if _, err := chainhash.NewHashFromStr(hash.String()); err != nil { fmt.Printf("that's not a real hash!") return nil } apic.mtx.Lock() defer apic.mtx.Unlock() return apic.getCachedBlockByHash(hash) }
[ "func", "(", "apic", "*", "APICache", ")", "GetCachedBlockByHash", "(", "hash", "chainhash", ".", "Hash", ")", "*", "CachedBlock", "{", "// validate the chainhash.Hash", "if", "_", ",", "err", ":=", "chainhash", ".", "NewHashFromStr", "(", "hash", ".", "String", "(", ")", ")", ";", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "apic", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "apic", ".", "mtx", ".", "Unlock", "(", ")", "\n", "return", "apic", ".", "getCachedBlockByHash", "(", "hash", ")", "\n", "}" ]
// GetCachedBlockByHash attempts to fetch a CachedBlock with the given hash. The // return is nil if no block with that hash is cached.
[ "GetCachedBlockByHash", "attempts", "to", "fetch", "a", "CachedBlock", "with", "the", "given", "hash", ".", "The", "return", "is", "nil", "if", "no", "block", "with", "that", "hash", "is", "cached", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L376-L386
train
decred/dcrdata
api/types/apicache.go
getCachedBlockByHash
func (apic *APICache) getCachedBlockByHash(hash chainhash.Hash) *CachedBlock { cachedBlock, ok := apic.blockCache[hash] if ok { cachedBlock.Access() apic.expireQueue.setNeedsReheap(true) apic.expireQueue.setAccessTime(time.Now()) apic.hits++ return cachedBlock } apic.misses++ return nil }
go
func (apic *APICache) getCachedBlockByHash(hash chainhash.Hash) *CachedBlock { cachedBlock, ok := apic.blockCache[hash] if ok { cachedBlock.Access() apic.expireQueue.setNeedsReheap(true) apic.expireQueue.setAccessTime(time.Now()) apic.hits++ return cachedBlock } apic.misses++ return nil }
[ "func", "(", "apic", "*", "APICache", ")", "getCachedBlockByHash", "(", "hash", "chainhash", ".", "Hash", ")", "*", "CachedBlock", "{", "cachedBlock", ",", "ok", ":=", "apic", ".", "blockCache", "[", "hash", "]", "\n", "if", "ok", "{", "cachedBlock", ".", "Access", "(", ")", "\n", "apic", ".", "expireQueue", ".", "setNeedsReheap", "(", "true", ")", "\n", "apic", ".", "expireQueue", ".", "setAccessTime", "(", "time", ".", "Now", "(", ")", ")", "\n", "apic", ".", "hits", "++", "\n", "return", "cachedBlock", "\n", "}", "\n", "apic", ".", "misses", "++", "\n", "return", "nil", "\n", "}" ]
// getCachedBlockByHash retrieves the block with the given hash, or nil if it is // not found. Successful retrieval will update the cached block's access time, // and increment the block's access count. This function is not thread-safe. See // GetCachedBlockByHash and GetCachedBlockByHashStr for thread safety and hash // validation.
[ "getCachedBlockByHash", "retrieves", "the", "block", "with", "the", "given", "hash", "or", "nil", "if", "it", "is", "not", "found", ".", "Successful", "retrieval", "will", "update", "the", "cached", "block", "s", "access", "time", "and", "increment", "the", "block", "s", "access", "count", ".", "This", "function", "is", "not", "thread", "-", "safe", ".", "See", "GetCachedBlockByHash", "and", "GetCachedBlockByHashStr", "for", "thread", "safety", "and", "hash", "validation", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L393-L404
train
decred/dcrdata
api/types/apicache.go
IsEnabled
func (apic *APICache) IsEnabled() bool { enabled, ok := apic.isEnabled.Load().(bool) return ok && enabled }
go
func (apic *APICache) IsEnabled() bool { enabled, ok := apic.isEnabled.Load().(bool) return ok && enabled }
[ "func", "(", "apic", "*", "APICache", ")", "IsEnabled", "(", ")", "bool", "{", "enabled", ",", "ok", ":=", "apic", ".", "isEnabled", ".", "Load", "(", ")", ".", "(", "bool", ")", "\n", "return", "ok", "&&", "enabled", "\n", "}" ]
// IsEnabled checks if the cache is enabled.
[ "IsEnabled", "checks", "if", "the", "cache", "is", "enabled", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L417-L420
train
decred/dcrdata
api/types/apicache.go
newCachedBlock
func newCachedBlock(summary *BlockDataBasic, stakeInfo *StakeInfoExtended) *CachedBlock { if summary == nil && stakeInfo == nil { return nil } height, hash, mismatch := checkBlockHeightHash(&cachedBlockData{ blockSummary: summary, stakeInfo: stakeInfo, }) if mismatch { return nil } return &CachedBlock{ height: height, hash: hash, summary: summary, stakeInfo: stakeInfo, heapIdx: -1, } }
go
func newCachedBlock(summary *BlockDataBasic, stakeInfo *StakeInfoExtended) *CachedBlock { if summary == nil && stakeInfo == nil { return nil } height, hash, mismatch := checkBlockHeightHash(&cachedBlockData{ blockSummary: summary, stakeInfo: stakeInfo, }) if mismatch { return nil } return &CachedBlock{ height: height, hash: hash, summary: summary, stakeInfo: stakeInfo, heapIdx: -1, } }
[ "func", "newCachedBlock", "(", "summary", "*", "BlockDataBasic", ",", "stakeInfo", "*", "StakeInfoExtended", ")", "*", "CachedBlock", "{", "if", "summary", "==", "nil", "&&", "stakeInfo", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "height", ",", "hash", ",", "mismatch", ":=", "checkBlockHeightHash", "(", "&", "cachedBlockData", "{", "blockSummary", ":", "summary", ",", "stakeInfo", ":", "stakeInfo", ",", "}", ")", "\n", "if", "mismatch", "{", "return", "nil", "\n", "}", "\n\n", "return", "&", "CachedBlock", "{", "height", ":", "height", ",", "hash", ":", "hash", ",", "summary", ":", "summary", ",", "stakeInfo", ":", "stakeInfo", ",", "heapIdx", ":", "-", "1", ",", "}", "\n", "}" ]
// newCachedBlock wraps the given BlockDataBasic in a CachedBlock with no // accesses and an invalid heap index. Use Access to set the access counter and // time. The priority queue will set the heapIdx.
[ "newCachedBlock", "wraps", "the", "given", "BlockDataBasic", "in", "a", "CachedBlock", "with", "no", "accesses", "and", "an", "invalid", "heap", "index", ".", "Use", "Access", "to", "set", "the", "access", "counter", "and", "time", ".", "The", "priority", "queue", "will", "set", "the", "heapIdx", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L430-L450
train
decred/dcrdata
api/types/apicache.go
Access
func (b *CachedBlock) Access() *BlockDataBasic { b.accesses++ b.accessTime = time.Now().UnixNano() return b.summary }
go
func (b *CachedBlock) Access() *BlockDataBasic { b.accesses++ b.accessTime = time.Now().UnixNano() return b.summary }
[ "func", "(", "b", "*", "CachedBlock", ")", "Access", "(", ")", "*", "BlockDataBasic", "{", "b", ".", "accesses", "++", "\n", "b", ".", "accessTime", "=", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "\n", "return", "b", ".", "summary", "\n", "}" ]
// Access increments the access count and sets the accessTime to now. The // BlockDataBasic stored in the CachedBlock is returned.
[ "Access", "increments", "the", "access", "count", "and", "sets", "the", "accessTime", "to", "now", ".", "The", "BlockDataBasic", "stored", "in", "the", "CachedBlock", "is", "returned", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L454-L458
train
decred/dcrdata
api/types/apicache.go
LessByAccessCountThenHeight
func LessByAccessCountThenHeight(bi, bj *CachedBlock) bool { if bi.accesses == bj.accesses { return LessByHeight(bi, bj) } return LessByAccessCount(bi, bj) }
go
func LessByAccessCountThenHeight(bi, bj *CachedBlock) bool { if bi.accesses == bj.accesses { return LessByHeight(bi, bj) } return LessByAccessCount(bi, bj) }
[ "func", "LessByAccessCountThenHeight", "(", "bi", ",", "bj", "*", "CachedBlock", ")", "bool", "{", "if", "bi", ".", "accesses", "==", "bj", ".", "accesses", "{", "return", "LessByHeight", "(", "bi", ",", "bj", ")", "\n", "}", "\n", "return", "LessByAccessCount", "(", "bi", ",", "bj", ")", "\n", "}" ]
// LessByAccessCountThenHeight compares access count with LessByAccessCount if // the blocks have different accessTime values, otherwise it compares height // with LessByHeight.
[ "LessByAccessCountThenHeight", "compares", "access", "count", "with", "LessByAccessCount", "if", "the", "blocks", "have", "different", "accessTime", "values", "otherwise", "it", "compares", "height", "with", "LessByHeight", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L550-L555
train
decred/dcrdata
api/types/apicache.go
MakeLessByAccessTimeThenCount
func MakeLessByAccessTimeThenCount(millisecondsBinned int64) func(bi, bj *CachedBlock) bool { millisecondThreshold := time.Duration(millisecondsBinned) * time.Millisecond return func(bi, bj *CachedBlock) bool { // higher priority is more recent (larger) access time epochDiff := (bi.accessTime - bj.accessTime) / int64(millisecondThreshold) if epochDiff == 0 { return LessByAccessCount(bi, bj) } // time diff is large enough, return direction (negative means i<j) return LessByAccessTime(bi, bj) // epochDiff < 0 } }
go
func MakeLessByAccessTimeThenCount(millisecondsBinned int64) func(bi, bj *CachedBlock) bool { millisecondThreshold := time.Duration(millisecondsBinned) * time.Millisecond return func(bi, bj *CachedBlock) bool { // higher priority is more recent (larger) access time epochDiff := (bi.accessTime - bj.accessTime) / int64(millisecondThreshold) if epochDiff == 0 { return LessByAccessCount(bi, bj) } // time diff is large enough, return direction (negative means i<j) return LessByAccessTime(bi, bj) // epochDiff < 0 } }
[ "func", "MakeLessByAccessTimeThenCount", "(", "millisecondsBinned", "int64", ")", "func", "(", "bi", ",", "bj", "*", "CachedBlock", ")", "bool", "{", "millisecondThreshold", ":=", "time", ".", "Duration", "(", "millisecondsBinned", ")", "*", "time", ".", "Millisecond", "\n", "return", "func", "(", "bi", ",", "bj", "*", "CachedBlock", ")", "bool", "{", "// higher priority is more recent (larger) access time", "epochDiff", ":=", "(", "bi", ".", "accessTime", "-", "bj", ".", "accessTime", ")", "/", "int64", "(", "millisecondThreshold", ")", "\n", "if", "epochDiff", "==", "0", "{", "return", "LessByAccessCount", "(", "bi", ",", "bj", ")", "\n", "}", "\n", "// time diff is large enough, return direction (negative means i<j)", "return", "LessByAccessTime", "(", "bi", ",", "bj", ")", "// epochDiff < 0", "\n", "}", "\n", "}" ]
// MakeLessByAccessTimeThenCount will create a CachedBlock comparison function // given the specified time resolution in milliseconds. Two access times less than // the given time apart are considered the same time, and access count is used // to break the tie.
[ "MakeLessByAccessTimeThenCount", "will", "create", "a", "CachedBlock", "comparison", "function", "given", "the", "specified", "time", "resolution", "in", "milliseconds", ".", "Two", "access", "times", "less", "than", "the", "given", "time", "apart", "are", "considered", "the", "same", "time", "and", "access", "count", "is", "used", "to", "break", "the", "tie", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L561-L572
train
decred/dcrdata
api/types/apicache.go
UpdateBlock
func (pq *BlockPriorityQueue) UpdateBlock(b *CachedBlock, summary *BlockDataBasic, stakeInfo *StakeInfoExtended) { if b != nil { heightAdded, hash, mismatch := checkBlockHeightHash(&cachedBlockData{ blockSummary: summary, stakeInfo: stakeInfo, }) if mismatch { fmt.Println("Cannot UpdateBlock!") return } heightRemoved := b.height b.height = heightAdded b.hash = hash b.summary = summary b.stakeInfo = stakeInfo b.accesses = 0 b.Access() heap.Fix(pq, b.heapIdx) pq.RescanMinMaxForUpdate(heightAdded, heightRemoved) pq.lastAccess = time.Unix(0, b.accessTime) } }
go
func (pq *BlockPriorityQueue) UpdateBlock(b *CachedBlock, summary *BlockDataBasic, stakeInfo *StakeInfoExtended) { if b != nil { heightAdded, hash, mismatch := checkBlockHeightHash(&cachedBlockData{ blockSummary: summary, stakeInfo: stakeInfo, }) if mismatch { fmt.Println("Cannot UpdateBlock!") return } heightRemoved := b.height b.height = heightAdded b.hash = hash b.summary = summary b.stakeInfo = stakeInfo b.accesses = 0 b.Access() heap.Fix(pq, b.heapIdx) pq.RescanMinMaxForUpdate(heightAdded, heightRemoved) pq.lastAccess = time.Unix(0, b.accessTime) } }
[ "func", "(", "pq", "*", "BlockPriorityQueue", ")", "UpdateBlock", "(", "b", "*", "CachedBlock", ",", "summary", "*", "BlockDataBasic", ",", "stakeInfo", "*", "StakeInfoExtended", ")", "{", "if", "b", "!=", "nil", "{", "heightAdded", ",", "hash", ",", "mismatch", ":=", "checkBlockHeightHash", "(", "&", "cachedBlockData", "{", "blockSummary", ":", "summary", ",", "stakeInfo", ":", "stakeInfo", ",", "}", ")", "\n", "if", "mismatch", "{", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "heightRemoved", ":=", "b", ".", "height", "\n\n", "b", ".", "height", "=", "heightAdded", "\n", "b", ".", "hash", "=", "hash", "\n", "b", ".", "summary", "=", "summary", "\n", "b", ".", "stakeInfo", "=", "stakeInfo", "\n", "b", ".", "accesses", "=", "0", "\n", "b", ".", "Access", "(", ")", "\n", "heap", ".", "Fix", "(", "pq", ",", "b", ".", "heapIdx", ")", "\n", "pq", ".", "RescanMinMaxForUpdate", "(", "heightAdded", ",", "heightRemoved", ")", "\n", "pq", ".", "lastAccess", "=", "time", ".", "Unix", "(", "0", ",", "b", ".", "accessTime", ")", "\n", "}", "\n", "}" ]
// UpdateBlock will update the specified CachedBlock, which must be in the // queue. This function is NOT thread-safe.
[ "UpdateBlock", "will", "update", "the", "specified", "CachedBlock", "which", "must", "be", "in", "the", "queue", ".", "This", "function", "is", "NOT", "thread", "-", "safe", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L723-L745
train
decred/dcrdata
api/types/apicache.go
RemoveBlock
func (pq *BlockPriorityQueue) RemoveBlock(b *CachedBlock) { pq.mtx.Lock() defer pq.mtx.Unlock() if b != nil && b.heapIdx > 0 && b.heapIdx < pq.Len() { // only remove the block it it is really in the queue if pq.bh[b.heapIdx].hash == b.hash { pq.RemoveIndex(b.heapIdx) return } fmt.Printf("Tried to remove a block that was NOT in the PQ. Hash: %v, Height: %d", b.hash, b.height) } }
go
func (pq *BlockPriorityQueue) RemoveBlock(b *CachedBlock) { pq.mtx.Lock() defer pq.mtx.Unlock() if b != nil && b.heapIdx > 0 && b.heapIdx < pq.Len() { // only remove the block it it is really in the queue if pq.bh[b.heapIdx].hash == b.hash { pq.RemoveIndex(b.heapIdx) return } fmt.Printf("Tried to remove a block that was NOT in the PQ. Hash: %v, Height: %d", b.hash, b.height) } }
[ "func", "(", "pq", "*", "BlockPriorityQueue", ")", "RemoveBlock", "(", "b", "*", "CachedBlock", ")", "{", "pq", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "pq", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "if", "b", "!=", "nil", "&&", "b", ".", "heapIdx", ">", "0", "&&", "b", ".", "heapIdx", "<", "pq", ".", "Len", "(", ")", "{", "// only remove the block it it is really in the queue", "if", "pq", ".", "bh", "[", "b", ".", "heapIdx", "]", ".", "hash", "==", "b", ".", "hash", "{", "pq", ".", "RemoveIndex", "(", "b", ".", "heapIdx", ")", "\n", "return", "\n", "}", "\n", "fmt", ".", "Printf", "(", "\"", "\"", ",", "b", ".", "hash", ",", "b", ".", "height", ")", "\n", "}", "\n", "}" ]
// RemoveBlock removes the specified CachedBlock from the queue. Remember to // remove it from the actual block cache!
[ "RemoveBlock", "removes", "the", "specified", "CachedBlock", "from", "the", "queue", ".", "Remember", "to", "remove", "it", "from", "the", "actual", "block", "cache!" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L812-L825
train
decred/dcrdata
api/types/apicache.go
RemoveIndex
func (pq *BlockPriorityQueue) RemoveIndex(idx int) { removedHeight := pq.bh[idx].height heap.Remove(pq, idx) pq.RescanMinMaxForRemove(removedHeight) }
go
func (pq *BlockPriorityQueue) RemoveIndex(idx int) { removedHeight := pq.bh[idx].height heap.Remove(pq, idx) pq.RescanMinMaxForRemove(removedHeight) }
[ "func", "(", "pq", "*", "BlockPriorityQueue", ")", "RemoveIndex", "(", "idx", "int", ")", "{", "removedHeight", ":=", "pq", ".", "bh", "[", "idx", "]", ".", "height", "\n", "heap", ".", "Remove", "(", "pq", ",", "idx", ")", "\n", "pq", ".", "RescanMinMaxForRemove", "(", "removedHeight", ")", "\n", "}" ]
// RemoveIndex removes the CachedBlock at the specified position in the heap. // This function is NOT thread-safe.
[ "RemoveIndex", "removes", "the", "CachedBlock", "at", "the", "specified", "position", "in", "the", "heap", ".", "This", "function", "is", "NOT", "thread", "-", "safe", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apicache.go#L829-L833
train
decred/dcrdata
mempool/collector.go
NewMempoolDataCollector
func NewMempoolDataCollector(dcrdChainSvr *rpcclient.Client, params *chaincfg.Params) *MempoolDataCollector { return &MempoolDataCollector{ dcrdChainSvr: dcrdChainSvr, activeChain: params, } }
go
func NewMempoolDataCollector(dcrdChainSvr *rpcclient.Client, params *chaincfg.Params) *MempoolDataCollector { return &MempoolDataCollector{ dcrdChainSvr: dcrdChainSvr, activeChain: params, } }
[ "func", "NewMempoolDataCollector", "(", "dcrdChainSvr", "*", "rpcclient", ".", "Client", ",", "params", "*", "chaincfg", ".", "Params", ")", "*", "MempoolDataCollector", "{", "return", "&", "MempoolDataCollector", "{", "dcrdChainSvr", ":", "dcrdChainSvr", ",", "activeChain", ":", "params", ",", "}", "\n", "}" ]
// NewMempoolDataCollector creates a new MempoolDataCollector.
[ "NewMempoolDataCollector", "creates", "a", "new", "MempoolDataCollector", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/mempool/collector.go#L37-L42
train
decred/dcrdata
config.go
normalizeNetworkAddress
func normalizeNetworkAddress(a, defaultHost, defaultPort string) (string, error) { if strings.Contains(a, "://") { return a, fmt.Errorf("Address %s contains a protocol identifier, which is not allowed", a) } if a == "" { return defaultHost + ":" + defaultPort, nil } host, port, err := net.SplitHostPort(a) if err != nil { if strings.Contains(err.Error(), "missing port in address") { normalized := a + ":" + defaultPort host, port, err = net.SplitHostPort(normalized) if err != nil { return a, fmt.Errorf("Unable to address %s after port resolution: %v", normalized, err) } } else { return a, fmt.Errorf("Unable to normalize address %s: %v", a, err) } } if host == "" { host = defaultHost } if port == "" { port = defaultPort } return host + ":" + port, nil }
go
func normalizeNetworkAddress(a, defaultHost, defaultPort string) (string, error) { if strings.Contains(a, "://") { return a, fmt.Errorf("Address %s contains a protocol identifier, which is not allowed", a) } if a == "" { return defaultHost + ":" + defaultPort, nil } host, port, err := net.SplitHostPort(a) if err != nil { if strings.Contains(err.Error(), "missing port in address") { normalized := a + ":" + defaultPort host, port, err = net.SplitHostPort(normalized) if err != nil { return a, fmt.Errorf("Unable to address %s after port resolution: %v", normalized, err) } } else { return a, fmt.Errorf("Unable to normalize address %s: %v", a, err) } } if host == "" { host = defaultHost } if port == "" { port = defaultPort } return host + ":" + port, nil }
[ "func", "normalizeNetworkAddress", "(", "a", ",", "defaultHost", ",", "defaultPort", "string", ")", "(", "string", ",", "error", ")", "{", "if", "strings", ".", "Contains", "(", "a", ",", "\"", "\"", ")", "{", "return", "a", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "a", ")", "\n", "}", "\n", "if", "a", "==", "\"", "\"", "{", "return", "defaultHost", "+", "\"", "\"", "+", "defaultPort", ",", "nil", "\n", "}", "\n", "host", ",", "port", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "a", ")", "\n", "if", "err", "!=", "nil", "{", "if", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "{", "normalized", ":=", "a", "+", "\"", "\"", "+", "defaultPort", "\n", "host", ",", "port", ",", "err", "=", "net", ".", "SplitHostPort", "(", "normalized", ")", "\n", "if", "err", "!=", "nil", "{", "return", "a", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "normalized", ",", "err", ")", "\n", "}", "\n", "}", "else", "{", "return", "a", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "a", ",", "err", ")", "\n", "}", "\n", "}", "\n", "if", "host", "==", "\"", "\"", "{", "host", "=", "defaultHost", "\n", "}", "\n", "if", "port", "==", "\"", "\"", "{", "port", "=", "defaultPort", "\n", "}", "\n", "return", "host", "+", "\"", "\"", "+", "port", ",", "nil", "\n", "}" ]
// normalizeNetworkAddress checks for a valid local network address format and // adds default host and port if not present. Invalidates addresses that include // a protocol identifier.
[ "normalizeNetworkAddress", "checks", "for", "a", "valid", "local", "network", "address", "format", "and", "adds", "default", "host", "and", "port", "if", "not", "present", ".", "Invalidates", "addresses", "that", "include", "a", "protocol", "identifier", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/config.go#L263-L289
train
decred/dcrdata
config.go
validLogLevel
func validLogLevel(logLevel string) bool { _, ok := slog.LevelFromString(logLevel) return ok }
go
func validLogLevel(logLevel string) bool { _, ok := slog.LevelFromString(logLevel) return ok }
[ "func", "validLogLevel", "(", "logLevel", "string", ")", "bool", "{", "_", ",", "ok", ":=", "slog", ".", "LevelFromString", "(", "logLevel", ")", "\n", "return", "ok", "\n", "}" ]
// validLogLevel returns whether or not logLevel is a valid debug log level.
[ "validLogLevel", "returns", "whether", "or", "not", "logLevel", "is", "a", "valid", "debug", "log", "level", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/config.go#L292-L295
train
decred/dcrdata
config.go
netName
func netName(chainParams *netparams.Params) string { // The following switch is to ensure this code is not built for testnet2, as // TestNet2 was removed entirely for dcrd 1.3.0. Compile check! switch chainParams.Net { case wire.TestNet3, wire.MainNet, wire.SimNet: default: log.Warnf("Unknown network: %s", chainParams.Name) } return chainParams.Name }
go
func netName(chainParams *netparams.Params) string { // The following switch is to ensure this code is not built for testnet2, as // TestNet2 was removed entirely for dcrd 1.3.0. Compile check! switch chainParams.Net { case wire.TestNet3, wire.MainNet, wire.SimNet: default: log.Warnf("Unknown network: %s", chainParams.Name) } return chainParams.Name }
[ "func", "netName", "(", "chainParams", "*", "netparams", ".", "Params", ")", "string", "{", "// The following switch is to ensure this code is not built for testnet2, as", "// TestNet2 was removed entirely for dcrd 1.3.0. Compile check!", "switch", "chainParams", ".", "Net", "{", "case", "wire", ".", "TestNet3", ",", "wire", ".", "MainNet", ",", "wire", ".", "SimNet", ":", "default", ":", "log", ".", "Warnf", "(", "\"", "\"", ",", "chainParams", ".", "Name", ")", "\n", "}", "\n", "return", "chainParams", ".", "Name", "\n", "}" ]
// netName returns the name used when referring to a decred network. TestNet3 // correctly returns "testnet3", but not TestNet2. This function may be removed // after testnet2 is ancient history.
[ "netName", "returns", "the", "name", "used", "when", "referring", "to", "a", "decred", "network", ".", "TestNet3", "correctly", "returns", "testnet3", "but", "not", "TestNet2", ".", "This", "function", "may", "be", "removed", "after", "testnet2", "is", "ancient", "history", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/config.go#L663-L672
train
decred/dcrdata
db/dbtypes/conversion.go
MsgBlockToDBBlock
func MsgBlockToDBBlock(msgBlock *wire.MsgBlock, chainParams *chaincfg.Params, chainWork string) *Block { // Create the dbtypes.Block structure blockHeader := msgBlock.Header // convert each transaction hash to a hex string txHashes := msgBlock.TxHashes() txHashStrs := make([]string, 0, len(txHashes)) for i := range txHashes { txHashStrs = append(txHashStrs, txHashes[i].String()) } stxHashes := msgBlock.STxHashes() stxHashStrs := make([]string, 0, len(stxHashes)) for i := range stxHashes { stxHashStrs = append(stxHashStrs, stxHashes[i].String()) } // Assemble the block return &Block{ Hash: blockHeader.BlockHash().String(), Size: uint32(msgBlock.SerializeSize()), Height: blockHeader.Height, Version: uint32(blockHeader.Version), NumTx: uint32(len(msgBlock.Transactions) + len(msgBlock.STransactions)), // nil []int64 for TxDbIDs NumRegTx: uint32(len(msgBlock.Transactions)), Tx: txHashStrs, NumStakeTx: uint32(len(msgBlock.STransactions)), STx: stxHashStrs, Time: NewTimeDef(blockHeader.Timestamp), Nonce: uint64(blockHeader.Nonce), VoteBits: blockHeader.VoteBits, Voters: blockHeader.Voters, FreshStake: blockHeader.FreshStake, Revocations: blockHeader.Revocations, PoolSize: blockHeader.PoolSize, Bits: blockHeader.Bits, SBits: uint64(blockHeader.SBits), Difficulty: txhelpers.GetDifficultyRatio(blockHeader.Bits, chainParams), StakeVersion: blockHeader.StakeVersion, PreviousHash: blockHeader.PrevBlock.String(), ChainWork: chainWork, } }
go
func MsgBlockToDBBlock(msgBlock *wire.MsgBlock, chainParams *chaincfg.Params, chainWork string) *Block { // Create the dbtypes.Block structure blockHeader := msgBlock.Header // convert each transaction hash to a hex string txHashes := msgBlock.TxHashes() txHashStrs := make([]string, 0, len(txHashes)) for i := range txHashes { txHashStrs = append(txHashStrs, txHashes[i].String()) } stxHashes := msgBlock.STxHashes() stxHashStrs := make([]string, 0, len(stxHashes)) for i := range stxHashes { stxHashStrs = append(stxHashStrs, stxHashes[i].String()) } // Assemble the block return &Block{ Hash: blockHeader.BlockHash().String(), Size: uint32(msgBlock.SerializeSize()), Height: blockHeader.Height, Version: uint32(blockHeader.Version), NumTx: uint32(len(msgBlock.Transactions) + len(msgBlock.STransactions)), // nil []int64 for TxDbIDs NumRegTx: uint32(len(msgBlock.Transactions)), Tx: txHashStrs, NumStakeTx: uint32(len(msgBlock.STransactions)), STx: stxHashStrs, Time: NewTimeDef(blockHeader.Timestamp), Nonce: uint64(blockHeader.Nonce), VoteBits: blockHeader.VoteBits, Voters: blockHeader.Voters, FreshStake: blockHeader.FreshStake, Revocations: blockHeader.Revocations, PoolSize: blockHeader.PoolSize, Bits: blockHeader.Bits, SBits: uint64(blockHeader.SBits), Difficulty: txhelpers.GetDifficultyRatio(blockHeader.Bits, chainParams), StakeVersion: blockHeader.StakeVersion, PreviousHash: blockHeader.PrevBlock.String(), ChainWork: chainWork, } }
[ "func", "MsgBlockToDBBlock", "(", "msgBlock", "*", "wire", ".", "MsgBlock", ",", "chainParams", "*", "chaincfg", ".", "Params", ",", "chainWork", "string", ")", "*", "Block", "{", "// Create the dbtypes.Block structure", "blockHeader", ":=", "msgBlock", ".", "Header", "\n\n", "// convert each transaction hash to a hex string", "txHashes", ":=", "msgBlock", ".", "TxHashes", "(", ")", "\n", "txHashStrs", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "txHashes", ")", ")", "\n", "for", "i", ":=", "range", "txHashes", "{", "txHashStrs", "=", "append", "(", "txHashStrs", ",", "txHashes", "[", "i", "]", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "stxHashes", ":=", "msgBlock", ".", "STxHashes", "(", ")", "\n", "stxHashStrs", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "stxHashes", ")", ")", "\n", "for", "i", ":=", "range", "stxHashes", "{", "stxHashStrs", "=", "append", "(", "stxHashStrs", ",", "stxHashes", "[", "i", "]", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "// Assemble the block", "return", "&", "Block", "{", "Hash", ":", "blockHeader", ".", "BlockHash", "(", ")", ".", "String", "(", ")", ",", "Size", ":", "uint32", "(", "msgBlock", ".", "SerializeSize", "(", ")", ")", ",", "Height", ":", "blockHeader", ".", "Height", ",", "Version", ":", "uint32", "(", "blockHeader", ".", "Version", ")", ",", "NumTx", ":", "uint32", "(", "len", "(", "msgBlock", ".", "Transactions", ")", "+", "len", "(", "msgBlock", ".", "STransactions", ")", ")", ",", "// nil []int64 for TxDbIDs", "NumRegTx", ":", "uint32", "(", "len", "(", "msgBlock", ".", "Transactions", ")", ")", ",", "Tx", ":", "txHashStrs", ",", "NumStakeTx", ":", "uint32", "(", "len", "(", "msgBlock", ".", "STransactions", ")", ")", ",", "STx", ":", "stxHashStrs", ",", "Time", ":", "NewTimeDef", "(", "blockHeader", ".", "Timestamp", ")", ",", "Nonce", ":", "uint64", "(", "blockHeader", ".", "Nonce", ")", ",", "VoteBits", ":", "blockHeader", ".", "VoteBits", ",", "Voters", ":", "blockHeader", ".", "Voters", ",", "FreshStake", ":", "blockHeader", ".", "FreshStake", ",", "Revocations", ":", "blockHeader", ".", "Revocations", ",", "PoolSize", ":", "blockHeader", ".", "PoolSize", ",", "Bits", ":", "blockHeader", ".", "Bits", ",", "SBits", ":", "uint64", "(", "blockHeader", ".", "SBits", ")", ",", "Difficulty", ":", "txhelpers", ".", "GetDifficultyRatio", "(", "blockHeader", ".", "Bits", ",", "chainParams", ")", ",", "StakeVersion", ":", "blockHeader", ".", "StakeVersion", ",", "PreviousHash", ":", "blockHeader", ".", "PrevBlock", ".", "String", "(", ")", ",", "ChainWork", ":", "chainWork", ",", "}", "\n", "}" ]
// MsgBlockToDBBlock creates a dbtypes.Block from a wire.MsgBlock
[ "MsgBlockToDBBlock", "creates", "a", "dbtypes", ".", "Block", "from", "a", "wire", ".", "MsgBlock" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/conversion.go#L13-L56
train
decred/dcrdata
db/dbtypes/conversion.go
TimeBasedGroupingToInterval
func TimeBasedGroupingToInterval(grouping TimeBasedGrouping) (float64, error) { var hr = 3600.0 // days per month value is obtained by 365/12 var daysPerMonth = 30.416666666666668 switch grouping { case AllGrouping: return 1, nil case DayGrouping: return hr * 24, nil case WeekGrouping: return hr * 24 * 7, nil case MonthGrouping: return hr * 24 * daysPerMonth, nil case YearGrouping: return hr * 24 * daysPerMonth * 12, nil default: return -1, fmt.Errorf(`unknown grouping "%d"`, grouping) } }
go
func TimeBasedGroupingToInterval(grouping TimeBasedGrouping) (float64, error) { var hr = 3600.0 // days per month value is obtained by 365/12 var daysPerMonth = 30.416666666666668 switch grouping { case AllGrouping: return 1, nil case DayGrouping: return hr * 24, nil case WeekGrouping: return hr * 24 * 7, nil case MonthGrouping: return hr * 24 * daysPerMonth, nil case YearGrouping: return hr * 24 * daysPerMonth * 12, nil default: return -1, fmt.Errorf(`unknown grouping "%d"`, grouping) } }
[ "func", "TimeBasedGroupingToInterval", "(", "grouping", "TimeBasedGrouping", ")", "(", "float64", ",", "error", ")", "{", "var", "hr", "=", "3600.0", "\n", "// days per month value is obtained by 365/12", "var", "daysPerMonth", "=", "30.416666666666668", "\n", "switch", "grouping", "{", "case", "AllGrouping", ":", "return", "1", ",", "nil", "\n\n", "case", "DayGrouping", ":", "return", "hr", "*", "24", ",", "nil", "\n\n", "case", "WeekGrouping", ":", "return", "hr", "*", "24", "*", "7", ",", "nil", "\n\n", "case", "MonthGrouping", ":", "return", "hr", "*", "24", "*", "daysPerMonth", ",", "nil", "\n\n", "case", "YearGrouping", ":", "return", "hr", "*", "24", "*", "daysPerMonth", "*", "12", ",", "nil", "\n\n", "default", ":", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "`unknown grouping \"%d\"`", ",", "grouping", ")", "\n", "}", "\n", "}" ]
// TimeBasedGroupingToInterval converts the TimeBasedGrouping value to an actual // time value in seconds based on the gregorian calendar except AllGrouping that // returns 1 while the unknownGrouping returns -1 and an error.
[ "TimeBasedGroupingToInterval", "converts", "the", "TimeBasedGrouping", "value", "to", "an", "actual", "time", "value", "in", "seconds", "based", "on", "the", "gregorian", "calendar", "except", "AllGrouping", "that", "returns", "1", "while", "the", "unknownGrouping", "returns", "-", "1", "and", "an", "error", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/conversion.go#L61-L84
train
decred/dcrdata
db/dbtypes/conversion.go
CalculateWindowIndex
func CalculateWindowIndex(height, stakeDiffWindowSize int64) int64 { // A window being a group of blocks whose count is defined by // chainParams.StakeDiffWindowSize, the first window starts from block 1 to // block 144 instead of block 0 to block 143. To obtain the accurate window // index value, we should add 1 to the quotient obtained by dividing the block // height with the chainParams.StakeDiffWindowSize value; if the float precision // is greater than zero. The precision is equal to zero only when the block // height value is divisible by the window size. windowVal := float64(height) / float64(stakeDiffWindowSize) index := int64(windowVal) if windowVal != math.Floor(windowVal) || windowVal == 0 { index++ } return index }
go
func CalculateWindowIndex(height, stakeDiffWindowSize int64) int64 { // A window being a group of blocks whose count is defined by // chainParams.StakeDiffWindowSize, the first window starts from block 1 to // block 144 instead of block 0 to block 143. To obtain the accurate window // index value, we should add 1 to the quotient obtained by dividing the block // height with the chainParams.StakeDiffWindowSize value; if the float precision // is greater than zero. The precision is equal to zero only when the block // height value is divisible by the window size. windowVal := float64(height) / float64(stakeDiffWindowSize) index := int64(windowVal) if windowVal != math.Floor(windowVal) || windowVal == 0 { index++ } return index }
[ "func", "CalculateWindowIndex", "(", "height", ",", "stakeDiffWindowSize", "int64", ")", "int64", "{", "// A window being a group of blocks whose count is defined by", "// chainParams.StakeDiffWindowSize, the first window starts from block 1 to", "// block 144 instead of block 0 to block 143. To obtain the accurate window", "// index value, we should add 1 to the quotient obtained by dividing the block", "// height with the chainParams.StakeDiffWindowSize value; if the float precision", "// is greater than zero. The precision is equal to zero only when the block", "// height value is divisible by the window size.", "windowVal", ":=", "float64", "(", "height", ")", "/", "float64", "(", "stakeDiffWindowSize", ")", "\n", "index", ":=", "int64", "(", "windowVal", ")", "\n", "if", "windowVal", "!=", "math", ".", "Floor", "(", "windowVal", ")", "||", "windowVal", "==", "0", "{", "index", "++", "\n", "}", "\n", "return", "index", "\n", "}" ]
// CalculateWindowIndex calculates the window index from the quotient of a block // height and the chainParams.StakeDiffWindowSize.
[ "CalculateWindowIndex", "calculates", "the", "window", "index", "from", "the", "quotient", "of", "a", "block", "height", "and", "the", "chainParams", ".", "StakeDiffWindowSize", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/conversion.go#L95-L109
train
decred/dcrdata
api/insight/socket.io.go
NewSocketServer
func NewSocketServer(newTxChan chan *NewTx, params *chaincfg.Params) (*SocketServer, error) { server, err := socketio.NewServer(nil) if err != nil { apiLog.Errorf("Could not create socket.io server: %v", err) return nil, err } // Each address subscription uses its own room, which has the same name as // the address. The number of subscribers for each room is tracked. addrs := roomSubscriptionCounter{ RWMutex: new(sync.RWMutex), c: make(map[string]int), } server.On("connection", func(so socketio.Socket) { apiLog.Debug("New socket.io connection") // New connections automatically join the inv and sync rooms. so.Join("inv") so.Join("sync") // Disconnection decrements or deletes the subscriber counter for each // address room to which the client was subscribed. so.On("disconnection", func() { apiLog.Debug("socket.io client disconnected") addrs.Lock() for _, str := range so.Rooms() { if c, ok := addrs.c[str]; ok { if c == 1 { delete(addrs.c, str) } else { addrs.c[str]-- } } } addrs.Unlock() }) // Subscription to a room checks the room name is as expected for an // address (TODO: do this better), joins the room, and increments the // room's subscriber count. so.On("subscribe", func(room string) { if len(room) > 64 || !isAlphaNumeric(room) { return } if addr, err := dcrutil.DecodeAddress(room); err == nil { if addr.IsForNet(params) { so.Join(room) apiLog.Debugf("socket.io client joining room: %s", room) addrs.Lock() addrs.c[room]++ addrs.Unlock() } } }) }) server.On("error", func(_ socketio.Socket, err error) { apiLog.Errorf("Insight socket.io server error: %v", err) }) sockServ := SocketServer{ Server: *server, params: params, watchedAddresses: addrs, } go sockServ.sendNewTx(newTxChan) return &sockServ, nil }
go
func NewSocketServer(newTxChan chan *NewTx, params *chaincfg.Params) (*SocketServer, error) { server, err := socketio.NewServer(nil) if err != nil { apiLog.Errorf("Could not create socket.io server: %v", err) return nil, err } // Each address subscription uses its own room, which has the same name as // the address. The number of subscribers for each room is tracked. addrs := roomSubscriptionCounter{ RWMutex: new(sync.RWMutex), c: make(map[string]int), } server.On("connection", func(so socketio.Socket) { apiLog.Debug("New socket.io connection") // New connections automatically join the inv and sync rooms. so.Join("inv") so.Join("sync") // Disconnection decrements or deletes the subscriber counter for each // address room to which the client was subscribed. so.On("disconnection", func() { apiLog.Debug("socket.io client disconnected") addrs.Lock() for _, str := range so.Rooms() { if c, ok := addrs.c[str]; ok { if c == 1 { delete(addrs.c, str) } else { addrs.c[str]-- } } } addrs.Unlock() }) // Subscription to a room checks the room name is as expected for an // address (TODO: do this better), joins the room, and increments the // room's subscriber count. so.On("subscribe", func(room string) { if len(room) > 64 || !isAlphaNumeric(room) { return } if addr, err := dcrutil.DecodeAddress(room); err == nil { if addr.IsForNet(params) { so.Join(room) apiLog.Debugf("socket.io client joining room: %s", room) addrs.Lock() addrs.c[room]++ addrs.Unlock() } } }) }) server.On("error", func(_ socketio.Socket, err error) { apiLog.Errorf("Insight socket.io server error: %v", err) }) sockServ := SocketServer{ Server: *server, params: params, watchedAddresses: addrs, } go sockServ.sendNewTx(newTxChan) return &sockServ, nil }
[ "func", "NewSocketServer", "(", "newTxChan", "chan", "*", "NewTx", ",", "params", "*", "chaincfg", ".", "Params", ")", "(", "*", "SocketServer", ",", "error", ")", "{", "server", ",", "err", ":=", "socketio", ".", "NewServer", "(", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "apiLog", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Each address subscription uses its own room, which has the same name as", "// the address. The number of subscribers for each room is tracked.", "addrs", ":=", "roomSubscriptionCounter", "{", "RWMutex", ":", "new", "(", "sync", ".", "RWMutex", ")", ",", "c", ":", "make", "(", "map", "[", "string", "]", "int", ")", ",", "}", "\n\n", "server", ".", "On", "(", "\"", "\"", ",", "func", "(", "so", "socketio", ".", "Socket", ")", "{", "apiLog", ".", "Debug", "(", "\"", "\"", ")", "\n", "// New connections automatically join the inv and sync rooms.", "so", ".", "Join", "(", "\"", "\"", ")", "\n", "so", ".", "Join", "(", "\"", "\"", ")", "\n\n", "// Disconnection decrements or deletes the subscriber counter for each", "// address room to which the client was subscribed.", "so", ".", "On", "(", "\"", "\"", ",", "func", "(", ")", "{", "apiLog", ".", "Debug", "(", "\"", "\"", ")", "\n", "addrs", ".", "Lock", "(", ")", "\n", "for", "_", ",", "str", ":=", "range", "so", ".", "Rooms", "(", ")", "{", "if", "c", ",", "ok", ":=", "addrs", ".", "c", "[", "str", "]", ";", "ok", "{", "if", "c", "==", "1", "{", "delete", "(", "addrs", ".", "c", ",", "str", ")", "\n", "}", "else", "{", "addrs", ".", "c", "[", "str", "]", "--", "\n", "}", "\n", "}", "\n", "}", "\n", "addrs", ".", "Unlock", "(", ")", "\n", "}", ")", "\n\n", "// Subscription to a room checks the room name is as expected for an", "// address (TODO: do this better), joins the room, and increments the", "// room's subscriber count.", "so", ".", "On", "(", "\"", "\"", ",", "func", "(", "room", "string", ")", "{", "if", "len", "(", "room", ")", ">", "64", "||", "!", "isAlphaNumeric", "(", "room", ")", "{", "return", "\n", "}", "\n", "if", "addr", ",", "err", ":=", "dcrutil", ".", "DecodeAddress", "(", "room", ")", ";", "err", "==", "nil", "{", "if", "addr", ".", "IsForNet", "(", "params", ")", "{", "so", ".", "Join", "(", "room", ")", "\n", "apiLog", ".", "Debugf", "(", "\"", "\"", ",", "room", ")", "\n\n", "addrs", ".", "Lock", "(", ")", "\n", "addrs", ".", "c", "[", "room", "]", "++", "\n", "addrs", ".", "Unlock", "(", ")", "\n", "}", "\n", "}", "\n", "}", ")", "\n", "}", ")", "\n\n", "server", ".", "On", "(", "\"", "\"", ",", "func", "(", "_", "socketio", ".", "Socket", ",", "err", "error", ")", "{", "apiLog", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", ")", "\n\n", "sockServ", ":=", "SocketServer", "{", "Server", ":", "*", "server", ",", "params", ":", "params", ",", "watchedAddresses", ":", "addrs", ",", "}", "\n", "go", "sockServ", ".", "sendNewTx", "(", "newTxChan", ")", "\n", "return", "&", "sockServ", ",", "nil", "\n", "}" ]
// NewSocketServer constructs a new SocketServer, registering handlers for the // "connection", "disconnection", and "subscribe" events.
[ "NewSocketServer", "constructs", "a", "new", "SocketServer", "registering", "handlers", "for", "the", "connection", "disconnection", "and", "subscribe", "events", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/insight/socket.io.go#L70-L138
train
decred/dcrdata
api/insight/socket.io.go
Store
func (soc *SocketServer) Store(blockData *blockdata.BlockData, msgBlock *wire.MsgBlock) error { apiLog.Debugf("Sending new websocket block %s", blockData.Header.Hash) soc.BroadcastTo("inv", "block", blockData.Header.Hash) // Since the coinbase transaction is generated by the miner, it will never // hit mempool. It must be processed now, with the new block. coinbaseTx := msgBlock.Transactions[0] coinbaseHash := coinbaseTx.TxHash().String() // Check each output's pkScript for subscribed addresses. for _, out := range coinbaseTx.TxOut { _, scriptAddrs, _, err := txscript.ExtractPkScriptAddrs( out.Version, out.PkScript, soc.params) if err != nil { apiLog.Warnf("failed to decode pkScript: %v", err) continue } if len(scriptAddrs) == 0 { continue } soc.watchedAddresses.RLock() for _, address := range scriptAddrs { addr := address.String() if _, ok := soc.watchedAddresses.c[addr]; ok { apiLog.Debugf(`Broadcasting "%s" in "%s" to subscribed clients.`, addr, coinbaseHash) soc.BroadcastTo(addr, addr, coinbaseHash) } } soc.watchedAddresses.RUnlock() } return nil }
go
func (soc *SocketServer) Store(blockData *blockdata.BlockData, msgBlock *wire.MsgBlock) error { apiLog.Debugf("Sending new websocket block %s", blockData.Header.Hash) soc.BroadcastTo("inv", "block", blockData.Header.Hash) // Since the coinbase transaction is generated by the miner, it will never // hit mempool. It must be processed now, with the new block. coinbaseTx := msgBlock.Transactions[0] coinbaseHash := coinbaseTx.TxHash().String() // Check each output's pkScript for subscribed addresses. for _, out := range coinbaseTx.TxOut { _, scriptAddrs, _, err := txscript.ExtractPkScriptAddrs( out.Version, out.PkScript, soc.params) if err != nil { apiLog.Warnf("failed to decode pkScript: %v", err) continue } if len(scriptAddrs) == 0 { continue } soc.watchedAddresses.RLock() for _, address := range scriptAddrs { addr := address.String() if _, ok := soc.watchedAddresses.c[addr]; ok { apiLog.Debugf(`Broadcasting "%s" in "%s" to subscribed clients.`, addr, coinbaseHash) soc.BroadcastTo(addr, addr, coinbaseHash) } } soc.watchedAddresses.RUnlock() } return nil }
[ "func", "(", "soc", "*", "SocketServer", ")", "Store", "(", "blockData", "*", "blockdata", ".", "BlockData", ",", "msgBlock", "*", "wire", ".", "MsgBlock", ")", "error", "{", "apiLog", ".", "Debugf", "(", "\"", "\"", ",", "blockData", ".", "Header", ".", "Hash", ")", "\n", "soc", ".", "BroadcastTo", "(", "\"", "\"", ",", "\"", "\"", ",", "blockData", ".", "Header", ".", "Hash", ")", "\n\n", "// Since the coinbase transaction is generated by the miner, it will never", "// hit mempool. It must be processed now, with the new block.", "coinbaseTx", ":=", "msgBlock", ".", "Transactions", "[", "0", "]", "\n", "coinbaseHash", ":=", "coinbaseTx", ".", "TxHash", "(", ")", ".", "String", "(", ")", "\n", "// Check each output's pkScript for subscribed addresses.", "for", "_", ",", "out", ":=", "range", "coinbaseTx", ".", "TxOut", "{", "_", ",", "scriptAddrs", ",", "_", ",", "err", ":=", "txscript", ".", "ExtractPkScriptAddrs", "(", "out", ".", "Version", ",", "out", ".", "PkScript", ",", "soc", ".", "params", ")", "\n", "if", "err", "!=", "nil", "{", "apiLog", ".", "Warnf", "(", "\"", "\"", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "if", "len", "(", "scriptAddrs", ")", "==", "0", "{", "continue", "\n", "}", "\n\n", "soc", ".", "watchedAddresses", ".", "RLock", "(", ")", "\n", "for", "_", ",", "address", ":=", "range", "scriptAddrs", "{", "addr", ":=", "address", ".", "String", "(", ")", "\n", "if", "_", ",", "ok", ":=", "soc", ".", "watchedAddresses", ".", "c", "[", "addr", "]", ";", "ok", "{", "apiLog", ".", "Debugf", "(", "`Broadcasting \"%s\" in \"%s\" to subscribed clients.`", ",", "addr", ",", "coinbaseHash", ")", "\n", "soc", ".", "BroadcastTo", "(", "addr", ",", "addr", ",", "coinbaseHash", ")", "\n", "}", "\n", "}", "\n", "soc", ".", "watchedAddresses", ".", "RUnlock", "(", ")", "\n\n", "}", "\n", "return", "nil", "\n", "}" ]
// Store broadcasts the lastest block hash to the the inv room
[ "Store", "broadcasts", "the", "lastest", "block", "hash", "to", "the", "the", "inv", "room" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/insight/socket.io.go#L141-L175
train
decred/dcrdata
explorer/explorerroutes.go
netName
func netName(chainParams *chaincfg.Params) string { if chainParams == nil { return "invalid" } if strings.HasPrefix(strings.ToLower(chainParams.Name), "testnet") { return "Testnet" } return strings.Title(chainParams.Name) }
go
func netName(chainParams *chaincfg.Params) string { if chainParams == nil { return "invalid" } if strings.HasPrefix(strings.ToLower(chainParams.Name), "testnet") { return "Testnet" } return strings.Title(chainParams.Name) }
[ "func", "netName", "(", "chainParams", "*", "chaincfg", ".", "Params", ")", "string", "{", "if", "chainParams", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "strings", ".", "ToLower", "(", "chainParams", ".", "Name", ")", ",", "\"", "\"", ")", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "strings", ".", "Title", "(", "chainParams", ".", "Name", ")", "\n", "}" ]
// netName returns the name used when referring to a decred network.
[ "netName", "returns", "the", "name", "used", "when", "referring", "to", "a", "decred", "network", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/explorerroutes.go#L109-L117
train
decred/dcrdata
explorer/explorerroutes.go
StatusPage
func (exp *explorerUI) StatusPage(w http.ResponseWriter, code, message, additionalInfo string, sType expStatus) { str, err := exp.templates.execTemplateToString("status", struct { *CommonPageData StatusType expStatus Code string Message string AdditionalInfo string }{ CommonPageData: exp.commonData(dummyRequest), StatusType: sType, Code: code, Message: message, AdditionalInfo: additionalInfo, }) if err != nil { log.Errorf("Template execute failure: %v", err) str = "Something went very wrong if you can see this, try refreshing" } w.Header().Set("Content-Type", "text/html") switch sType { case ExpStatusDBTimeout: w.WriteHeader(http.StatusServiceUnavailable) case ExpStatusNotFound: w.WriteHeader(http.StatusNotFound) case ExpStatusFutureBlock: w.WriteHeader(http.StatusOK) case ExpStatusError: w.WriteHeader(http.StatusInternalServerError) // When blockchain sync is running, status 202 is used to imply that the // other requests apart from serving the status sync page have been received // and accepted but cannot be processed now till the sync is complete. case ExpStatusSyncing: w.WriteHeader(http.StatusAccepted) case ExpStatusNotSupported: w.WriteHeader(http.StatusUnprocessableEntity) case ExpStatusBadRequest: w.WriteHeader(http.StatusBadRequest) default: w.WriteHeader(http.StatusServiceUnavailable) } io.WriteString(w, str) }
go
func (exp *explorerUI) StatusPage(w http.ResponseWriter, code, message, additionalInfo string, sType expStatus) { str, err := exp.templates.execTemplateToString("status", struct { *CommonPageData StatusType expStatus Code string Message string AdditionalInfo string }{ CommonPageData: exp.commonData(dummyRequest), StatusType: sType, Code: code, Message: message, AdditionalInfo: additionalInfo, }) if err != nil { log.Errorf("Template execute failure: %v", err) str = "Something went very wrong if you can see this, try refreshing" } w.Header().Set("Content-Type", "text/html") switch sType { case ExpStatusDBTimeout: w.WriteHeader(http.StatusServiceUnavailable) case ExpStatusNotFound: w.WriteHeader(http.StatusNotFound) case ExpStatusFutureBlock: w.WriteHeader(http.StatusOK) case ExpStatusError: w.WriteHeader(http.StatusInternalServerError) // When blockchain sync is running, status 202 is used to imply that the // other requests apart from serving the status sync page have been received // and accepted but cannot be processed now till the sync is complete. case ExpStatusSyncing: w.WriteHeader(http.StatusAccepted) case ExpStatusNotSupported: w.WriteHeader(http.StatusUnprocessableEntity) case ExpStatusBadRequest: w.WriteHeader(http.StatusBadRequest) default: w.WriteHeader(http.StatusServiceUnavailable) } io.WriteString(w, str) }
[ "func", "(", "exp", "*", "explorerUI", ")", "StatusPage", "(", "w", "http", ".", "ResponseWriter", ",", "code", ",", "message", ",", "additionalInfo", "string", ",", "sType", "expStatus", ")", "{", "str", ",", "err", ":=", "exp", ".", "templates", ".", "execTemplateToString", "(", "\"", "\"", ",", "struct", "{", "*", "CommonPageData", "\n", "StatusType", "expStatus", "\n", "Code", "string", "\n", "Message", "string", "\n", "AdditionalInfo", "string", "\n", "}", "{", "CommonPageData", ":", "exp", ".", "commonData", "(", "dummyRequest", ")", ",", "StatusType", ":", "sType", ",", "Code", ":", "code", ",", "Message", ":", "message", ",", "AdditionalInfo", ":", "additionalInfo", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "str", "=", "\"", "\"", "\n", "}", "\n\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "switch", "sType", "{", "case", "ExpStatusDBTimeout", ":", "w", ".", "WriteHeader", "(", "http", ".", "StatusServiceUnavailable", ")", "\n", "case", "ExpStatusNotFound", ":", "w", ".", "WriteHeader", "(", "http", ".", "StatusNotFound", ")", "\n", "case", "ExpStatusFutureBlock", ":", "w", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n", "case", "ExpStatusError", ":", "w", ".", "WriteHeader", "(", "http", ".", "StatusInternalServerError", ")", "\n", "// When blockchain sync is running, status 202 is used to imply that the", "// other requests apart from serving the status sync page have been received", "// and accepted but cannot be processed now till the sync is complete.", "case", "ExpStatusSyncing", ":", "w", ".", "WriteHeader", "(", "http", ".", "StatusAccepted", ")", "\n", "case", "ExpStatusNotSupported", ":", "w", ".", "WriteHeader", "(", "http", ".", "StatusUnprocessableEntity", ")", "\n", "case", "ExpStatusBadRequest", ":", "w", ".", "WriteHeader", "(", "http", ".", "StatusBadRequest", ")", "\n", "default", ":", "w", ".", "WriteHeader", "(", "http", ".", "StatusServiceUnavailable", ")", "\n", "}", "\n", "io", ".", "WriteString", "(", "w", ",", "str", ")", "\n", "}" ]
// StatusPage provides a page for displaying status messages and exception // handling without redirecting. Be sure to return after calling StatusPage if // this completes the processing of the calling http handler.
[ "StatusPage", "provides", "a", "page", "for", "displaying", "status", "messages", "and", "exception", "handling", "without", "redirecting", ".", "Be", "sure", "to", "return", "after", "calling", "StatusPage", "if", "this", "completes", "the", "processing", "of", "the", "calling", "http", "handler", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/explorerroutes.go#L1541-L1583
train
decred/dcrdata
explorer/explorerroutes.go
NotFound
func (exp *explorerUI) NotFound(w http.ResponseWriter, r *http.Request) { exp.StatusPage(w, "Page not found.", "Cannot find page: "+r.URL.Path, "", ExpStatusNotFound) }
go
func (exp *explorerUI) NotFound(w http.ResponseWriter, r *http.Request) { exp.StatusPage(w, "Page not found.", "Cannot find page: "+r.URL.Path, "", ExpStatusNotFound) }
[ "func", "(", "exp", "*", "explorerUI", ")", "NotFound", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "exp", ".", "StatusPage", "(", "w", ",", "\"", "\"", ",", "\"", "\"", "+", "r", ".", "URL", ".", "Path", ",", "\"", "\"", ",", "ExpStatusNotFound", ")", "\n", "}" ]
// NotFound wraps StatusPage to display a 404 page.
[ "NotFound", "wraps", "StatusPage", "to", "display", "a", "404", "page", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/explorerroutes.go#L1586-L1588
train
decred/dcrdata
explorer/explorerroutes.go
HandleApiRequestsOnSync
func (exp *explorerUI) HandleApiRequestsOnSync(w http.ResponseWriter, r *http.Request) { var complete int dataFetched := SyncStatus() syncStatus := "in progress" if len(dataFetched) == complete { syncStatus = "complete" } for _, v := range dataFetched { if v.PercentComplete == 100 { complete++ } } stageRunning := complete + 1 if stageRunning > len(dataFetched) { stageRunning = len(dataFetched) } data, err := json.Marshal(struct { Message string `json:"message"` Stage int `json:"stage"` Stages []SyncStatusInfo `json:"stages"` }{ fmt.Sprintf("blockchain sync is %s.", syncStatus), stageRunning, dataFetched, }) str := string(data) if err != nil { str = fmt.Sprintf("error occurred while processing the API response: %v", err) } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusServiceUnavailable) io.WriteString(w, str) }
go
func (exp *explorerUI) HandleApiRequestsOnSync(w http.ResponseWriter, r *http.Request) { var complete int dataFetched := SyncStatus() syncStatus := "in progress" if len(dataFetched) == complete { syncStatus = "complete" } for _, v := range dataFetched { if v.PercentComplete == 100 { complete++ } } stageRunning := complete + 1 if stageRunning > len(dataFetched) { stageRunning = len(dataFetched) } data, err := json.Marshal(struct { Message string `json:"message"` Stage int `json:"stage"` Stages []SyncStatusInfo `json:"stages"` }{ fmt.Sprintf("blockchain sync is %s.", syncStatus), stageRunning, dataFetched, }) str := string(data) if err != nil { str = fmt.Sprintf("error occurred while processing the API response: %v", err) } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusServiceUnavailable) io.WriteString(w, str) }
[ "func", "(", "exp", "*", "explorerUI", ")", "HandleApiRequestsOnSync", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "var", "complete", "int", "\n", "dataFetched", ":=", "SyncStatus", "(", ")", "\n\n", "syncStatus", ":=", "\"", "\"", "\n", "if", "len", "(", "dataFetched", ")", "==", "complete", "{", "syncStatus", "=", "\"", "\"", "\n", "}", "\n\n", "for", "_", ",", "v", ":=", "range", "dataFetched", "{", "if", "v", ".", "PercentComplete", "==", "100", "{", "complete", "++", "\n", "}", "\n", "}", "\n", "stageRunning", ":=", "complete", "+", "1", "\n", "if", "stageRunning", ">", "len", "(", "dataFetched", ")", "{", "stageRunning", "=", "len", "(", "dataFetched", ")", "\n", "}", "\n\n", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "struct", "{", "Message", "string", "`json:\"message\"`", "\n", "Stage", "int", "`json:\"stage\"`", "\n", "Stages", "[", "]", "SyncStatusInfo", "`json:\"stages\"`", "\n", "}", "{", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "syncStatus", ")", ",", "stageRunning", ",", "dataFetched", ",", "}", ")", "\n\n", "str", ":=", "string", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "str", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusServiceUnavailable", ")", "\n", "io", ".", "WriteString", "(", "w", ",", "str", ")", "\n", "}" ]
// HandleApiRequestsOnSync handles all API request when the sync status pages is // running.
[ "HandleApiRequestsOnSync", "handles", "all", "API", "request", "when", "the", "sync", "status", "pages", "is", "running", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/explorerroutes.go#L1866-L1903
train
decred/dcrdata
explorer/explorerroutes.go
commonData
func (exp *explorerUI) commonData(r *http.Request) *CommonPageData { tip, err := exp.blockData.GetTip() if err != nil { log.Errorf("Failed to get the chain tip from the database.: %v", err) return nil } darkMode, err := r.Cookie(darkModeCoookie) if err != nil && err != http.ErrNoCookie { log.Errorf("Cookie dcrdataDarkBG retrieval error: %v", err) } return &CommonPageData{ Tip: tip, Version: exp.Version, ChainParams: exp.ChainParams, BlockTimeUnix: int64(exp.ChainParams.TargetTimePerBlock.Seconds()), DevAddress: exp.pageData.HomeInfo.DevAddress, NetName: exp.NetName, Links: explorerLinks, Cookies: Cookies{ DarkMode: darkMode != nil && darkMode.Value == "1", }, RequestURI: r.URL.RequestURI(), } }
go
func (exp *explorerUI) commonData(r *http.Request) *CommonPageData { tip, err := exp.blockData.GetTip() if err != nil { log.Errorf("Failed to get the chain tip from the database.: %v", err) return nil } darkMode, err := r.Cookie(darkModeCoookie) if err != nil && err != http.ErrNoCookie { log.Errorf("Cookie dcrdataDarkBG retrieval error: %v", err) } return &CommonPageData{ Tip: tip, Version: exp.Version, ChainParams: exp.ChainParams, BlockTimeUnix: int64(exp.ChainParams.TargetTimePerBlock.Seconds()), DevAddress: exp.pageData.HomeInfo.DevAddress, NetName: exp.NetName, Links: explorerLinks, Cookies: Cookies{ DarkMode: darkMode != nil && darkMode.Value == "1", }, RequestURI: r.URL.RequestURI(), } }
[ "func", "(", "exp", "*", "explorerUI", ")", "commonData", "(", "r", "*", "http", ".", "Request", ")", "*", "CommonPageData", "{", "tip", ",", "err", ":=", "exp", ".", "blockData", ".", "GetTip", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n", "darkMode", ",", "err", ":=", "r", ".", "Cookie", "(", "darkModeCoookie", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "http", ".", "ErrNoCookie", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "&", "CommonPageData", "{", "Tip", ":", "tip", ",", "Version", ":", "exp", ".", "Version", ",", "ChainParams", ":", "exp", ".", "ChainParams", ",", "BlockTimeUnix", ":", "int64", "(", "exp", ".", "ChainParams", ".", "TargetTimePerBlock", ".", "Seconds", "(", ")", ")", ",", "DevAddress", ":", "exp", ".", "pageData", ".", "HomeInfo", ".", "DevAddress", ",", "NetName", ":", "exp", ".", "NetName", ",", "Links", ":", "explorerLinks", ",", "Cookies", ":", "Cookies", "{", "DarkMode", ":", "darkMode", "!=", "nil", "&&", "darkMode", ".", "Value", "==", "\"", "\"", ",", "}", ",", "RequestURI", ":", "r", ".", "URL", ".", "RequestURI", "(", ")", ",", "}", "\n", "}" ]
// commonData grabs the common page data that is available to every page. // This is particularly useful for extras.tmpl, parts of which // are used on every page
[ "commonData", "grabs", "the", "common", "page", "data", "that", "is", "available", "to", "every", "page", ".", "This", "is", "particularly", "useful", "for", "extras", ".", "tmpl", "parts", "of", "which", "are", "used", "on", "every", "page" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/explorerroutes.go#L2015-L2038
train
decred/dcrdata
explorer/explorermiddleware.go
SyncStatusPageIntercept
func (exp *explorerUI) SyncStatusPageIntercept(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if exp.ShowingSyncStatusPage() { exp.StatusPage(w, "Database Update Running. Please Wait.", "Blockchain sync is running. Please wait.", "", ExpStatusSyncing) return } // Otherwise, proceed to the next http handler. next.ServeHTTP(w, r) }) }
go
func (exp *explorerUI) SyncStatusPageIntercept(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if exp.ShowingSyncStatusPage() { exp.StatusPage(w, "Database Update Running. Please Wait.", "Blockchain sync is running. Please wait.", "", ExpStatusSyncing) return } // Otherwise, proceed to the next http handler. next.ServeHTTP(w, r) }) }
[ "func", "(", "exp", "*", "explorerUI", ")", "SyncStatusPageIntercept", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "exp", ".", "ShowingSyncStatusPage", "(", ")", "{", "exp", ".", "StatusPage", "(", "w", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "ExpStatusSyncing", ")", "\n", "return", "\n", "}", "\n", "// Otherwise, proceed to the next http handler.", "next", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", ")", "\n", "}" ]
// SyncStatusPageIntercept serves only the syncing status page until it is // deactivated when ShowingSyncStatusPage is set to false. This page is served // for all the possible routes supported until the background syncing is done.
[ "SyncStatusPageIntercept", "serves", "only", "the", "syncing", "status", "page", "until", "it", "is", "deactivated", "when", "ShowingSyncStatusPage", "is", "set", "to", "false", ".", "This", "page", "is", "served", "for", "all", "the", "possible", "routes", "supported", "until", "the", "background", "syncing", "is", "done", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/explorermiddleware.go#L88-L98
train
decred/dcrdata
explorer/explorermiddleware.go
SyncStatusAPIIntercept
func (exp *explorerUI) SyncStatusAPIIntercept(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if exp.ShowingSyncStatusPage() { exp.HandleApiRequestsOnSync(w, r) return } // Otherwise, proceed to the next http handler. next.ServeHTTP(w, r) }) }
go
func (exp *explorerUI) SyncStatusAPIIntercept(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if exp.ShowingSyncStatusPage() { exp.HandleApiRequestsOnSync(w, r) return } // Otherwise, proceed to the next http handler. next.ServeHTTP(w, r) }) }
[ "func", "(", "exp", "*", "explorerUI", ")", "SyncStatusAPIIntercept", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "exp", ".", "ShowingSyncStatusPage", "(", ")", "{", "exp", ".", "HandleApiRequestsOnSync", "(", "w", ",", "r", ")", "\n", "return", "\n", "}", "\n", "// Otherwise, proceed to the next http handler.", "next", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", ")", "\n", "}" ]
// SyncStatusAPIIntercept returns a json response back instead of a web page // when display sync status is active for the api endpoints supported.
[ "SyncStatusAPIIntercept", "returns", "a", "json", "response", "back", "instead", "of", "a", "web", "page", "when", "display", "sync", "status", "is", "active", "for", "the", "api", "endpoints", "supported", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/explorermiddleware.go#L102-L111
train
decred/dcrdata
explorer/explorermiddleware.go
SyncStatusFileIntercept
func (exp *explorerUI) SyncStatusFileIntercept(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if exp.ShowingSyncStatusPage() { http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable) return } // Otherwise, proceed to the next http handler. next.ServeHTTP(w, r) }) }
go
func (exp *explorerUI) SyncStatusFileIntercept(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if exp.ShowingSyncStatusPage() { http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable) return } // Otherwise, proceed to the next http handler. next.ServeHTTP(w, r) }) }
[ "func", "(", "exp", "*", "explorerUI", ")", "SyncStatusFileIntercept", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "exp", ".", "ShowingSyncStatusPage", "(", ")", "{", "http", ".", "Error", "(", "w", ",", "http", ".", "StatusText", "(", "http", ".", "StatusServiceUnavailable", ")", ",", "http", ".", "StatusServiceUnavailable", ")", "\n", "return", "\n", "}", "\n", "// Otherwise, proceed to the next http handler.", "next", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", ")", "\n", "}" ]
// SyncStatusFileIntercept triggers an HTTP error if a file is requested for // download before the DB is synced.
[ "SyncStatusFileIntercept", "triggers", "an", "HTTP", "error", "if", "a", "file", "is", "requested", "for", "download", "before", "the", "DB", "is", "synced", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/explorermiddleware.go#L115-L124
train
decred/dcrdata
explorer/explorermiddleware.go
TransactionHashCtx
func TransactionHashCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { txid := chi.URLParam(r, "txid") ctx := context.WithValue(r.Context(), ctxTxHash, txid) next.ServeHTTP(w, r.WithContext(ctx)) }) }
go
func TransactionHashCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { txid := chi.URLParam(r, "txid") ctx := context.WithValue(r.Context(), ctxTxHash, txid) next.ServeHTTP(w, r.WithContext(ctx)) }) }
[ "func", "TransactionHashCtx", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "txid", ":=", "chi", ".", "URLParam", "(", "r", ",", "\"", "\"", ")", "\n", "ctx", ":=", "context", ".", "WithValue", "(", "r", ".", "Context", "(", ")", ",", "ctxTxHash", ",", "txid", ")", "\n", "next", ".", "ServeHTTP", "(", "w", ",", "r", ".", "WithContext", "(", "ctx", ")", ")", "\n", "}", ")", "\n", "}" ]
// TransactionHashCtx embeds "txid" into the request context
[ "TransactionHashCtx", "embeds", "txid", "into", "the", "request", "context" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/explorermiddleware.go#L164-L170
train
decred/dcrdata
explorer/explorermiddleware.go
TransactionIoIndexCtx
func TransactionIoIndexCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { inout := chi.URLParam(r, "inout") inoutid := chi.URLParam(r, "inoutid") ctx := context.WithValue(r.Context(), ctxTxInOut, inout) ctx = context.WithValue(ctx, ctxTxInOutId, inoutid) next.ServeHTTP(w, r.WithContext(ctx)) }) }
go
func TransactionIoIndexCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { inout := chi.URLParam(r, "inout") inoutid := chi.URLParam(r, "inoutid") ctx := context.WithValue(r.Context(), ctxTxInOut, inout) ctx = context.WithValue(ctx, ctxTxInOutId, inoutid) next.ServeHTTP(w, r.WithContext(ctx)) }) }
[ "func", "TransactionIoIndexCtx", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "inout", ":=", "chi", ".", "URLParam", "(", "r", ",", "\"", "\"", ")", "\n", "inoutid", ":=", "chi", ".", "URLParam", "(", "r", ",", "\"", "\"", ")", "\n", "ctx", ":=", "context", ".", "WithValue", "(", "r", ".", "Context", "(", ")", ",", "ctxTxInOut", ",", "inout", ")", "\n", "ctx", "=", "context", ".", "WithValue", "(", "ctx", ",", "ctxTxInOutId", ",", "inoutid", ")", "\n", "next", ".", "ServeHTTP", "(", "w", ",", "r", ".", "WithContext", "(", "ctx", ")", ")", "\n", "}", ")", "\n", "}" ]
// TransactionIoIndexCtx embeds "inout" and "inoutid" into the request context
[ "TransactionIoIndexCtx", "embeds", "inout", "and", "inoutid", "into", "the", "request", "context" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/explorermiddleware.go#L173-L181
train
decred/dcrdata
explorer/explorermiddleware.go
ProposalPathCtx
func ProposalPathCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { proposalRefID := chi.URLParam(r, "proposalrefid") ctx := context.WithValue(r.Context(), ctxProposalRefID, proposalRefID) next.ServeHTTP(w, r.WithContext(ctx)) }) }
go
func ProposalPathCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { proposalRefID := chi.URLParam(r, "proposalrefid") ctx := context.WithValue(r.Context(), ctxProposalRefID, proposalRefID) next.ServeHTTP(w, r.WithContext(ctx)) }) }
[ "func", "ProposalPathCtx", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "proposalRefID", ":=", "chi", ".", "URLParam", "(", "r", ",", "\"", "\"", ")", "\n", "ctx", ":=", "context", ".", "WithValue", "(", "r", ".", "Context", "(", ")", ",", "ctxProposalRefID", ",", "proposalRefID", ")", "\n", "next", ".", "ServeHTTP", "(", "w", ",", "r", ".", "WithContext", "(", "ctx", ")", ")", "\n", "}", ")", "\n", "}" ]
// ProposalPathCtx embeds "proposalrefID" into the request context
[ "ProposalPathCtx", "embeds", "proposalrefID", "into", "the", "request", "context" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/explorermiddleware.go#L202-L208
train
decred/dcrdata
explorer/explorermiddleware.go
MenuFormParser
func MenuFormParser(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.FormValue(darkModeFormKey) != "" { cookie, err := r.Cookie(darkModeCoookie) if err != nil && err != http.ErrNoCookie { log.Errorf("Cookie dcrdataDarkBG retrieval error: %v", err) } else { if err == http.ErrNoCookie { cookie = &http.Cookie{ Name: darkModeCoookie, Value: "1", MaxAge: 0, } } else { cookie.Value = "0" cookie.MaxAge = -1 } http.SetCookie(w, cookie) requestURI := r.FormValue(requestURIFormKey) if requestURI == "" { requestURI = "/" } http.Redirect(w, r, requestURI, http.StatusFound) return } } next.ServeHTTP(w, r) }) }
go
func MenuFormParser(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.FormValue(darkModeFormKey) != "" { cookie, err := r.Cookie(darkModeCoookie) if err != nil && err != http.ErrNoCookie { log.Errorf("Cookie dcrdataDarkBG retrieval error: %v", err) } else { if err == http.ErrNoCookie { cookie = &http.Cookie{ Name: darkModeCoookie, Value: "1", MaxAge: 0, } } else { cookie.Value = "0" cookie.MaxAge = -1 } http.SetCookie(w, cookie) requestURI := r.FormValue(requestURIFormKey) if requestURI == "" { requestURI = "/" } http.Redirect(w, r, requestURI, http.StatusFound) return } } next.ServeHTTP(w, r) }) }
[ "func", "MenuFormParser", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "r", ".", "FormValue", "(", "darkModeFormKey", ")", "!=", "\"", "\"", "{", "cookie", ",", "err", ":=", "r", ".", "Cookie", "(", "darkModeCoookie", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "http", ".", "ErrNoCookie", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "else", "{", "if", "err", "==", "http", ".", "ErrNoCookie", "{", "cookie", "=", "&", "http", ".", "Cookie", "{", "Name", ":", "darkModeCoookie", ",", "Value", ":", "\"", "\"", ",", "MaxAge", ":", "0", ",", "}", "\n", "}", "else", "{", "cookie", ".", "Value", "=", "\"", "\"", "\n", "cookie", ".", "MaxAge", "=", "-", "1", "\n", "}", "\n", "http", ".", "SetCookie", "(", "w", ",", "cookie", ")", "\n", "requestURI", ":=", "r", ".", "FormValue", "(", "requestURIFormKey", ")", "\n", "if", "requestURI", "==", "\"", "\"", "{", "requestURI", "=", "\"", "\"", "\n", "}", "\n", "http", ".", "Redirect", "(", "w", ",", "r", ",", "requestURI", ",", "http", ".", "StatusFound", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "next", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", ")", "\n", "}" ]
// MenuFormParser parses a form submission from the navigation menu.
[ "MenuFormParser", "parses", "a", "form", "submission", "from", "the", "navigation", "menu", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/explorermiddleware.go#L211-L239
train