本文整理汇总了Golang中strconv.ParseInt函数的典型用法代码示例。如果您正苦于以下问题:Golang ParseInt函数的具体用法?Golang ParseInt怎么用?Golang ParseInt使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ParseInt函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: extractISO8601Duration
func extractISO8601Duration(
iso_8601_duration string,
) (
minutes_duration,
seconds_duration time.Duration,
err error,
) {
err = fmt.Errorf(`No duration can be extracted`)
re := regexp.MustCompile(ISO_8601_DURATION_REGEX)
if re.MatchString(iso_8601_duration) {
matched_groups := re.FindAllStringSubmatch(iso_8601_duration, 1)
if len(matched_groups) > 0 {
groups := matched_groups[0]
if d, d_err := strconv.ParseInt(groups[1], 10, 64); d_err == nil {
minutes_duration = time.Minute * time.Duration(d)
err = nil
} else {
err = d_err
}
if err == nil {
if d, d_err := strconv.ParseInt(groups[2], 10, 64); d_err == nil {
seconds_duration = time.Second * time.Duration(d)
err = nil
} else {
err = d_err
}
}
}
}
return
}
示例2: main
func main() {
//With ParseFloat, this 64 tells how many bits of precision to parse.
f, _ := strconv.ParseFloat("1.234", 64)
fmt.Println(f)
//For ParseInt, the 0 means infer the base from the string. 64 requires that the result fit in 64 bits.
i, _ := strconv.ParseInt("123", 0, 64)
fmt.Println(i)
//ParseInt will recognize hex-formatted numbers.
d, _ := strconv.ParseInt("0x1c8", 0, 64)
fmt.Println(d)
//A ParseUint is also available.
u, _ := strconv.ParseUint("789", 0, 64)
fmt.Println(u)
//Atoi is a convenience function for basic base-10 int parsing.
k, _ := strconv.Atoi("135")
fmt.Println(k)
//Parse functions return an error on bad input.
_, e := strconv.Atoi("wat")
fmt.Println(e)
}
示例3: parsePAXTime
// parsePAXTime takes a string of the form %d.%d as described in
// the PAX specification.
func parsePAXTime(t string) (time.Time, error) {
buf := []byte(t)
pos := bytes.IndexByte(buf, '.')
var seconds, nanoseconds int64
var err error
if pos == -1 {
seconds, err = strconv.ParseInt(t, 10, 0)
if err != nil {
return time.Time{}, err
}
} else {
seconds, err = strconv.ParseInt(string(buf[:pos]), 10, 0)
if err != nil {
return time.Time{}, err
}
nano_buf := string(buf[pos+1:])
// Pad as needed before converting to a decimal.
// For example .030 -> .030000000 -> 30000000 nanoseconds
if len(nano_buf) < maxNanoSecondIntSize {
// Right pad
nano_buf += strings.Repeat("0", maxNanoSecondIntSize-len(nano_buf))
} else if len(nano_buf) > maxNanoSecondIntSize {
// Right truncate
nano_buf = nano_buf[:maxNanoSecondIntSize]
}
nanoseconds, err = strconv.ParseInt(string(nano_buf), 10, 0)
if err != nil {
return time.Time{}, err
}
}
ts := time.Unix(seconds, nanoseconds)
return ts, nil
}
示例4: evalStatusline
func evalStatusline(statusline string) (active, total, size int64, err error) {
matches := statuslineRE.FindStringSubmatch(statusline)
// +1 to make it more obvious that the whole string containing the info is also returned as matches[0].
if len(matches) < 3+1 {
return 0, 0, 0, fmt.Errorf("too few matches found in statusline: %s", statusline)
} else {
if len(matches) > 3+1 {
return 0, 0, 0, fmt.Errorf("too many matches found in statusline: %s", statusline)
}
}
size, err = strconv.ParseInt(matches[1], 10, 64)
if err != nil {
return 0, 0, 0, fmt.Errorf("%s in statusline: %s", err, statusline)
}
total, err = strconv.ParseInt(matches[2], 10, 64)
if err != nil {
return 0, 0, 0, fmt.Errorf("%s in statusline: %s", err, statusline)
}
active, err = strconv.ParseInt(matches[3], 10, 64)
if err != nil {
return 0, 0, 0, fmt.Errorf("%s in statusline: %s", err, statusline)
}
return active, total, size, nil
}
示例5: TrendsRootIndex
// Generates JSON for root list of trends
func TrendsRootIndex(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
location := vars["location"]
source := r.URL.Query().Get("source")
limitParam := r.URL.Query().Get("limit")
limit, _ := strconv.ParseInt(limitParam, 10, 0)
if limit < 1 {
limit = 10
}
intervalParam := r.URL.Query().Get("interval")
interval, _ := strconv.ParseInt(intervalParam, 10, 0)
fromParam := r.URL.Query().Get("from")
toParam := r.URL.Query().Get("to")
t := time.Now()
if fromParam == "" {
from := t.Add(-24 * time.Hour)
fromParam = from.Format("200601021504")
}
if toParam == "" {
toParam = t.Format("200601021504")
}
if interval < 1 {
interval = 2
}
sortedCounts, _ := WordCountRootCollection(location, source, fromParam, toParam, int(interval), int(limit))
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Methods", "GET")
w.Header().Add("Access-Control-Allow-Headers", "Content-Type, api_key, Authorization")
json.NewEncoder(w).Encode(sortedCounts)
}
示例6: libSubstr
func libSubstr(th *eval.Thread, in []eval.Value, out []eval.Value) {
s := in[0].String()
start, err := strconv.ParseInt(in[1].String(), 10, 32)
var res string
if err != nil {
panic(err)
}
end, err := strconv.ParseInt(in[2].String(), 10, 32)
if err != nil {
panic(err)
}
if int(start) < 0 {
newStart := len(s) + int(start)
res := s[newStart:len(s)]
out[0] = eval.ToValue(res)
return
}
if len(s) < int(end) {
res = s[start:]
out[0] = eval.ToValue(res)
return
}
res = s[start:end]
out[0] = eval.ToValue(res)
}
示例7: Group
// Group selects a group.
func (c *Client) Group(name string) (rv nntp.Group, err error) {
var msg string
_, msg, err = c.Command("GROUP "+name, 211)
if err != nil {
return
}
// count first last name
parts := strings.Split(msg, " ")
if len(parts) != 4 {
err = errors.New("Don't know how to parse result: " + msg)
}
rv.Count, err = strconv.ParseInt(parts[0], 10, 64)
if err != nil {
return
}
rv.Low, err = strconv.ParseInt(parts[1], 10, 64)
if err != nil {
return
}
rv.High, err = strconv.ParseInt(parts[2], 10, 64)
if err != nil {
return
}
rv.Name = parts[3]
return
}
示例8: List
// List groups
func (c *Client) List(sub string) (rv []nntp.Group, err error) {
_, _, err = c.Command("LIST "+sub, 215)
if err != nil {
return
}
var groupLines []string
groupLines, err = c.conn.ReadDotLines()
if err != nil {
return
}
rv = make([]nntp.Group, 0, len(groupLines))
for _, l := range groupLines {
parts := strings.Split(l, " ")
high, errh := strconv.ParseInt(parts[1], 10, 64)
low, errl := strconv.ParseInt(parts[2], 10, 64)
if errh == nil && errl == nil {
rv = append(rv, nntp.Group{
Name: parts[0],
High: high,
Low: low,
Posting: parsePosting(parts[3]),
})
}
}
return
}
示例9: PermInt
func PermInt(str string) int {
var res = 0
if str[0] == '0' {
if len(str) == 1 {
res = 0
} else if str[1] == 'x' {
// this is hex number
i64, err := strconv.ParseInt(str[2:], 16, 0)
if err == nil {
res = int(i64)
}
} else {
// this is a octal number
i64, err := strconv.ParseInt(str[2:], 8, 0)
if err == nil {
res = int(i64)
}
}
} else {
res, _ = strconv.Atoi(str)
}
if res > 511 {
res = 511
}
return res
}
示例10: buildSlaveInfoStruct
// buildSlaveInfoStruct builods the struct for a slave from the Redis slaves command
func (r *Redis) buildSlaveInfoStruct(info map[string]string) (master SlaveInfo, err error) {
s := reflect.ValueOf(&master).Elem()
typeOfT := s.Type()
for i := 0; i < s.NumField(); i++ {
p := typeOfT.Field(i)
f := s.Field(i)
tag := p.Tag.Get("redis")
if f.Type().Name() == "int" {
val, err := strconv.ParseInt(info[tag], 10, 64)
if err != nil {
println("Unable to convert to data from sentinel server:", info[tag], err)
} else {
f.SetInt(val)
}
}
if f.Type().Name() == "string" {
f.SetString(info[tag])
}
if f.Type().Name() == "bool" {
// This handles primarily the xxx_xx style fields in the return data from redis
if info[tag] != "" {
val, err := strconv.ParseInt(info[tag], 10, 64)
if err != nil {
println("[bool] Unable to convert to data from sentinel server:", info[tag], err)
fmt.Println("Error:", err)
} else {
if val > 0 {
f.SetBool(true)
}
}
}
}
}
return
}
示例11: deleteBuildCommentHandler
func deleteBuildCommentHandler(w http.ResponseWriter, r *http.Request) {
defer timer.New("deleteBuildCommentHandler").Stop()
if !userHasEditRights(r) {
util.ReportError(w, r, fmt.Errorf("User does not have edit rights."), "User does not have edit rights.")
return
}
w.Header().Set("Content-Type", "application/json")
cache, err := getCommitCache(w, r)
if err != nil {
return
}
buildId, err := strconv.ParseInt(mux.Vars(r)["buildId"], 10, 32)
if err != nil {
util.ReportError(w, r, err, fmt.Sprintf("Invalid build id: %v", err))
return
}
commentId, err := strconv.ParseInt(mux.Vars(r)["commentId"], 10, 32)
if err != nil {
util.ReportError(w, r, err, fmt.Sprintf("Invalid comment id: %v", err))
return
}
if err := cache.DeleteBuildComment(int(buildId), int(commentId)); err != nil {
util.ReportError(w, r, err, fmt.Sprintf("Failed to delete comment: %v", err))
return
}
}
示例12: waitForNotification
func waitForNotification(l *pq.Listener) {
for {
select {
case notify := <-l.Notify:
payload := strings.SplitN(notify.Extra, "|", 3)
id, err := strconv.ParseInt(payload[0], 10, 64)
if err != nil {
panic(err)
}
var roomId int64
roomId, err = strconv.ParseInt(payload[1], 10, 64)
if err != nil {
panic(err)
}
msg := models.GetMessage(id)
revel.INFO.Printf("received notification with payload: '%d' '%d' '%s' '%s'\n", msg.Id, msg.RoomId, msg.Text, msg.ImageUrl)
Publish(EVENT_MSG, int64(roomId), *msg)
case <-time.After(200 * time.Millisecond):
go func() {
if err := l.Ping(); err != nil {
panic(err)
}
}()
}
}
}
示例13: parseJavaSamples
// parseJavaSamples parses the samples from a java profile and
// populates the Samples in a profile. Returns the remainder of the
// buffer after the samples.
func parseJavaSamples(pType string, b []byte, p *Profile) ([]byte, map[uint64]*Location, error) {
nextNewLine := bytes.IndexByte(b, byte('\n'))
locs := make(map[uint64]*Location)
for nextNewLine != -1 {
line := string(bytes.TrimSpace(b[0:nextNewLine]))
if line != "" {
sample := javaSampleRx.FindStringSubmatch(line)
if sample == nil {
// Not a valid sample, exit.
return b, locs, nil
}
// Java profiles have data/fields inverted compared to other
// profile types.
value1, value2, addrs := sample[2], sample[1], sample[3]
var sloc []*Location
for _, addr := range parseHexAddresses(addrs) {
loc := locs[addr]
if locs[addr] == nil {
loc = &Location{
Address: addr,
}
p.Location = append(p.Location, loc)
locs[addr] = loc
}
sloc = append(sloc, loc)
}
s := &Sample{
Value: make([]int64, 2),
Location: sloc,
}
var err error
if s.Value[0], err = strconv.ParseInt(value1, 0, 64); err != nil {
return nil, nil, fmt.Errorf("parsing sample %s: %v", line, err)
}
if s.Value[1], err = strconv.ParseInt(value2, 0, 64); err != nil {
return nil, nil, fmt.Errorf("parsing sample %s: %v", line, err)
}
switch pType {
case "heap":
const javaHeapzSamplingRate = 524288 // 512K
s.NumLabel = map[string][]int64{"bytes": []int64{s.Value[1] / s.Value[0]}}
s.Value[0], s.Value[1] = scaleHeapSample(s.Value[0], s.Value[1], javaHeapzSamplingRate)
case "contention":
if period := p.Period; period != 0 {
s.Value[0] = s.Value[0] * p.Period
s.Value[1] = s.Value[1] * p.Period
}
}
p.Sample = append(p.Sample, s)
}
// Grab next line.
b = b[nextNewLine+1:]
nextNewLine = bytes.IndexByte(b, byte('\n'))
}
return b, locs, nil
}
示例14: set
func (r bot) set(p *robots.Payload, cmd utils.Command) error {
name := cmd.Arg(0)
if name == "" {
r.handler.Send(p, "Missing Slack user name. Use `!user set <user-name> [mvn:<mavenlink-id>] [pvt:<pivotal-id>]`")
return nil
}
mvnId := cmd.Param("mvn")
pvtId := cmd.Param("pvt")
user := db.User{Name: name}
if mvnId != "" {
mvnInt, err := strconv.ParseInt(mvnId, 10, 64)
if err != nil {
return err
}
user.MavenlinkId = &mvnInt
}
if pvtId != "" {
pvtInt, err := strconv.ParseInt(pvtId, 10, 64)
if err != nil {
return err
}
user.PivotalId = &pvtInt
}
if err := db.SaveUser(user); err != nil {
return err
}
r.handler.Send(p, "User *"+name+"* saved")
return nil
}
示例15: NewStart
func NewStart(ui terminal.UI, config configuration.Reader, appDisplayer ApplicationDisplayer, appRepo api.ApplicationRepository, appInstancesRepo api.AppInstancesRepository, logRepo api.LogsRepository) (cmd *Start) {
cmd = new(Start)
cmd.ui = ui
cmd.config = config
cmd.appDisplayer = appDisplayer
cmd.appRepo = appRepo
cmd.appInstancesRepo = appInstancesRepo
cmd.logRepo = logRepo
cmd.PingerThrottle = DefaultPingerThrottle
if os.Getenv("CF_STAGING_TIMEOUT") != "" {
duration, err := strconv.ParseInt(os.Getenv("CF_STAGING_TIMEOUT"), 10, 64)
if err != nil {
cmd.ui.Failed("invalid value for env var CF_STAGING_TIMEOUT\n%s", err)
}
cmd.StagingTimeout = time.Duration(duration) * time.Minute
} else {
cmd.StagingTimeout = DefaultStagingTimeout
}
if os.Getenv("CF_STARTUP_TIMEOUT") != "" {
duration, err := strconv.ParseInt(os.Getenv("CF_STARTUP_TIMEOUT"), 10, 64)
if err != nil {
cmd.ui.Failed("invalid value for env var CF_STARTUP_TIMEOUT\n%s", err)
}
cmd.StartupTimeout = time.Duration(duration) * time.Minute
} else {
cmd.StartupTimeout = DefaultStartupTimeout
}
return
}