当前位置: 首页>>代码示例>>Golang>>正文


Golang strings.Fields函数代码示例

本文整理汇总了Golang中strings.Fields函数的典型用法代码示例。如果您正苦于以下问题:Golang Fields函数的具体用法?Golang Fields怎么用?Golang Fields使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Fields函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: read

// Reads a log file.
func (c *combiner) read(fileName string) error {
	fh, err := os.Open(fileName)
	if err != nil {
		return err
	}
	defer fh.Close()

	scanner := bufio.NewScanner(fh)
	for j := 0; scanner.Scan(); j++ {
		line := scanner.Text()
		if j == 0 {
			fields := strings.Fields(string(line))
			if len(c.headers) == 0 {
				c.ts = fields[0]
				c.headers = fields[1:]
			} else if len(c.headers) > len(fields[1:]) {
				c.headers = fields[1:]
			}
		} else if j > 1 {
			fields := strings.Fields(line)
			ts, _ := strconv.ParseInt(fields[0], 10, 64)
			c.entries[int(ts)] = fields[1:]
		}
	}
	// check for scanner errors
	return nil
}
开发者ID:roundbrackets,项目名称:quiz,代码行数:28,代码来源:combine.go

示例2: Get

func (pfs *ProcFS) Get(k string) {
	var uf = path.Join(procfsdir, "uptime")
	switch k {
	case PROCFS_SELF:
		var selfdir = path.Join(procfsdir, "self")
		if !exists(selfdir) {
			return
		}
		fi, _ := os.Readlink(selfdir)
		pfs.Self = fi
	case PROCFS_UPTIME:
		str, err := ioutil.ReadFile(uf)
		if err == nil {
			ss := strings.Fields(string(str))
			if len(ss) >= 2 {
				it, _ := strconv.ParseFloat(ss[0], 64)
				pfs.Uptime = int(it)
			}
		}
	case PROCFS_IDLETIME:
		str, err := ioutil.ReadFile(uf)
		if err == nil {
			ss := strings.Fields(string(str))
			if len(ss) >= 2 {
				it, _ := strconv.ParseFloat(ss[1], 64)
				pfs.Idletime = int(it)
			}
		}
	case PROCFS_MOUNTS:
		pfs.Mounts = getMounts(path.Join(procfsdir, "mounts"))
	}
}
开发者ID:bytbox,项目名称:procfs.go,代码行数:32,代码来源:procfs.go

示例3: ReadSNMP

func ReadSNMP(path string) (*Snmp, error) {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}

	lines := strings.Split(string(data), "\n")

	// Maps a netstat metric to its value (i.e. SyncookiesSent --> 0)
	statMap := make(map[string]string)

	// patterns
	// TcpExt: SyncookiesSent SyncookiesRecv SyncookiesFailed... <-- header
	// TcpExt: 0 0 1764... <-- values
	for i := 1; i < len(lines); i = i + 2 {
		headers := strings.Fields(lines[i-1][strings.Index(lines[i-1], ":")+1:])
		values := strings.Fields(lines[i][strings.Index(lines[i], ":")+1:])
		for j, header := range headers {
			statMap[header] = values[j]
		}
	}

	out := Snmp{}
	elem := reflect.ValueOf(&out.TCP).Elem()
	typeOfElem := elem.Type()

	for i := 0; i < elem.NumField(); i++ {
		if val, ok := statMap[typeOfElem.Field(i).Name]; ok {
			parsedVal, _ := strconv.ParseUint(val, 10, 64)
			elem.Field(i).SetUint(parsedVal)
		}
	}

	return &out, nil
}
开发者ID:bountylabs,项目名称:goprocinfo,代码行数:35,代码来源:snmp.go

示例4: Parse

// Parse parses a Makefile into a *Makefile struct.
//
// TODO(sqs): super hacky.
func Parse(data []byte) (*Makefile, error) {
	var mf Makefile

	lines := bytes.Split(data, []byte{'\n'})
	var rule *BasicRule
	for lineno, lineBytes := range lines {
		line := string(lineBytes)
		if strings.HasPrefix(line, "\t") {
			if rule == nil {
				return nil, fmt.Errorf("line %d: indented recipe not inside a rule", lineno)
			}
			recipe := strings.TrimPrefix(line, "\t")
			recipe = ExpandAutoVars(rule, recipe)
			rule.RecipeCmds = append(rule.RecipeCmds, recipe)
		} else if strings.Contains(line, ":") {
			sep := strings.Index(line, ":")
			targets := strings.Fields(line[:sep])
			if len(targets) > 1 {
				return nil, errMultipleTargetsUnsupported(lineno)
			}
			target := targets[0]
			prereqs := strings.Fields(line[sep+1:])
			prereqs = uniqAndSort(prereqs)
			rule = &BasicRule{TargetFile: target, PrereqFiles: prereqs}
			mf.Rules = append(mf.Rules, rule)
		} else {
			rule = nil
		}
	}

	return &mf, nil
}
开发者ID:alexsaveliev,项目名称:makex,代码行数:35,代码来源:parser.go

示例5: GetStudent

func GetStudent(d *goquery.Document, rollno int) (s Student, ok bool) {
	//sanity on document
	// if v := d.Find(".titlehead").Children().Text(); v != "JEE (Advanced) - 2013 Result" {
	// 	return Student{}, false
	// }
	dtext := strings.Trim(d.Text(), " ")
	dfields := strings.Fields(dtext)
	for _, v := range dfields {
		s.Plaintext += v + " "
	}
	s.Plaintext = strings.Trim(s.Plaintext, " ")
	if isInvalid(dtext) {
		return s, false
	}
	ok = true
	s.Rollno = rollno
	s.Region = s.Rollno / 10000
	if !isSelected(dtext) {
		return
	}
	s.Selected = true
	s.Rank, _ = strconv.Atoi(d.Find(".style7").First().Text())
	text, _ := d.Find(".titlehead").First().Parent().Next().Children().Children().First().Html()
	tokens := strings.Split(text, "<br/>")
	nameToks := strings.Fields(tokens[1])
	nameToks = nameToks[2:len(nameToks)]
	for _, v := range nameToks {
		s.Name += v + " "
	}
	s.Name = strings.Trim(s.Name, " ")
	s.Q = GetQuota(dtext)
	return
}
开发者ID:korroktheslavemaster,项目名称:jee,代码行数:33,代码来源:parser.go

示例6: TestEventsImageUntagDelete

func TestEventsImageUntagDelete(t *testing.T) {
	name := "testimageevents"
	defer deleteImages(name)
	_, err := buildImage(name,
		`FROM scratch
		MAINTAINER "docker"`,
		true)
	if err != nil {
		t.Fatal(err)
	}
	if err := deleteImages(name); err != nil {
		t.Fatal(err)
	}
	eventsCmd := exec.Command(dockerBinary, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(t).Unix()))
	out, exitCode, err := runCommandWithOutput(eventsCmd)
	if exitCode != 0 || err != nil {
		t.Fatalf("Failed to get events with exit code %d: %s", exitCode, err)
	}
	events := strings.Split(out, "\n")

	events = events[:len(events)-1]
	if len(events) < 2 {
		t.Fatalf("Missing expected event")
	}
	untagEvent := strings.Fields(events[len(events)-2])
	deleteEvent := strings.Fields(events[len(events)-1])
	if untagEvent[len(untagEvent)-1] != "untag" {
		t.Fatalf("untag should be untag, not %#v", untagEvent)
	}
	if deleteEvent[len(deleteEvent)-1] != "delete" {
		t.Fatalf("delete should be delete, not %#v", deleteEvent)
	}
	logDone("events - image untag, delete is logged")
}
开发者ID:nicholaskh,项目名称:docker,代码行数:34,代码来源:docker_cli_events_test.go

示例7: TestEventsContainerEvents

func TestEventsContainerEvents(t *testing.T) {
	dockerCmd(t, "run", "--rm", "busybox", "true")
	eventsCmd := exec.Command(dockerBinary, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(t).Unix()))
	out, exitCode, err := runCommandWithOutput(eventsCmd)
	if exitCode != 0 || err != nil {
		t.Fatalf("Failed to get events with exit code %d: %s", exitCode, err)
	}
	events := strings.Split(out, "\n")
	events = events[:len(events)-1]
	if len(events) < 4 {
		t.Fatalf("Missing expected event")
	}
	createEvent := strings.Fields(events[len(events)-4])
	startEvent := strings.Fields(events[len(events)-3])
	dieEvent := strings.Fields(events[len(events)-2])
	destroyEvent := strings.Fields(events[len(events)-1])
	if createEvent[len(createEvent)-1] != "create" {
		t.Fatalf("event should be create, not %#v", createEvent)
	}
	if startEvent[len(startEvent)-1] != "start" {
		t.Fatalf("event should be start, not %#v", startEvent)
	}
	if dieEvent[len(dieEvent)-1] != "die" {
		t.Fatalf("event should be die, not %#v", dieEvent)
	}
	if destroyEvent[len(destroyEvent)-1] != "destroy" {
		t.Fatalf("event should be destroy, not %#v", destroyEvent)
	}

	logDone("events - container create, start, die, destroy is logged")
}
开发者ID:nicholaskh,项目名称:docker,代码行数:31,代码来源:docker_cli_events_test.go

示例8: getRootfsDM

func getRootfsDM(containerID string) (string, error) {
	var (
		rootfs string
		major  string
		minor  string
	)
	out, err := exec.Command("ls", "-lh", "/dev/mapper").CombinedOutput()
	if err != nil {
		return "", err
	}
	for _, line := range strings.Split(string(out), "\n") {
		fields := strings.Fields(line)
		if strings.Contains(line, containerID) {
			if len(fields) < 10 {
				return "", fmt.Errorf("Failed to get /dev/mapper info")
			}
			rootfs = filepath.Base(fields[10])
			break
		}
	}

	out, err = exec.Command("ls", "-lh", filepath.Join("/dev", rootfs)).CombinedOutput()
	if err != nil {
		return "", err
	}
	fields := strings.Fields(string(out))
	if len(fields) < 5 {
		return "", fmt.Errorf("Failed to get /dev/%s info", rootfs)
	}
	major = strings.Replace(fields[4], ",", "", -1)
	minor = fields[5]
	return fmt.Sprintf("%s:%s", major, minor), nil
}
开发者ID:TencentSA,项目名称:kubernetes-0.5,代码行数:33,代码来源:blkio.go

示例9: readBondingStats

func readBondingStats(root string) (status map[string][2]int, err error) {
	status = map[string][2]int{}
	masters, err := ioutil.ReadFile(path.Join(root, "bonding_masters"))
	if err != nil {
		return nil, err
	}
	for _, master := range strings.Fields(string(masters)) {
		slaves, err := ioutil.ReadFile(path.Join(root, master, "bonding", "slaves"))
		if err != nil {
			return nil, err
		}
		sstat := [2]int{0, 0}
		for _, slave := range strings.Fields(string(slaves)) {
			state, err := ioutil.ReadFile(path.Join(root, master, fmt.Sprintf("lower_%s", slave), "operstate"))
			if os.IsNotExist(err) {
				// some older? kernels use slave_ prefix
				state, err = ioutil.ReadFile(path.Join(root, master, fmt.Sprintf("slave_%s", slave), "operstate"))
			}
			if err != nil {
				return nil, err
			}
			sstat[0]++
			if strings.TrimSpace(string(state)) == "up" {
				sstat[1]++
			}
		}
		status[master] = sstat
	}
	return status, err
}
开发者ID:prometheus,项目名称:node_exporter,代码行数:30,代码来源:bonding_linux.go

示例10: parseIrcLine

func parseIrcLine(line string) (prefix, command string, args []string) {
	if line == "" {
		logger.Printf("cannot parse %q", line)
		return
	}
	var hasPrefix bool
	if line[0] == ':' {
		hasPrefix = true
	}
	var items []string
	colon := strings.Index(line[1:], ":")
	if colon >= 0 {
		// long arg
		items = strings.Fields(line[:colon+1])
		items = append(items, line[colon+2:])
	} else {
		items = strings.Fields(line)
	}
	if len(items) < 2 {
		logger.Printf("cannot parse %q", line)
		return
	}
	if hasPrefix {
		return items[0][1:], items[1], items[2:]
	}
	return "", items[0], items[1:]
}
开发者ID:lyuyun,项目名称:loggregator,代码行数:27,代码来源:irc.go

示例11: Get

func (self *ProcMem) Get(pid int) error {
	contents, err := readProcFile(pid, "statm")
	if err != nil {
		return err
	}

	fields := strings.Fields(string(contents))

	size, _ := strtoull(fields[0])
	self.Size = size << 12

	rss, _ := strtoull(fields[1])
	self.Resident = rss << 12

	share, _ := strtoull(fields[2])
	self.Share = share << 12

	contents, err = readProcFile(pid, "stat")
	if err != nil {
		return err
	}

	fields = strings.Fields(string(contents))

	self.MinorFaults, _ = strtoull(fields[10])
	self.MajorFaults, _ = strtoull(fields[12])
	self.PageFaults = self.MinorFaults + self.MajorFaults

	return nil
}
开发者ID:rasputnik,项目名称:gosigar,代码行数:30,代码来源:sigar_linux.go

示例12: discover

func (v *ViPR) discover(cli *http.Client, url string) (map[string]string, error) {

	user := env(v.Username, "VIPR_USERNAME", "Admin")
	password := env(v.Password, "VIPR_PASSWORD", "ADMINISTRATOR")

	request, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	request.SetBasicAuth(user, password)

	resp, err := cli.Do(request)
	if resp == nil || err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	doc, err := goquery.NewDocumentFromResponse(resp)
	if doc == nil || err != nil {
		return nil, err
	}

	results := make(map[string]string)

	// mac address is hidden in javascript and non changeable
	doc.Find("td").Each(func(i int, s *goquery.Selection) {
		p := strings.Fields(s.Text())
		if len(p) > 0 && s.Next() != nil {
			r := strings.Fields(strings.Replace(s.Next().Text(), "\"", "", -1))
			if strings.HasPrefix(s.Text(), "Dataradio") {
				results["version"] = strings.Join(p, " ")
			}
			if strings.HasPrefix(s.Text(), "MAC") {
				if _, ok := results["macaddr"]; !ok && len(r) > 10 {
					results["macaddr"] = strings.Join(r[5:10], ":")
				}
			}
			if strings.HasPrefix(s.Text(), "RSSI") {
				if len(r) > 1 {
					results["signal"] = r[0]
				}
			}

			switch strings.Join(p, " ") {
			case "Modem Firmware Version":
				results["firmware"] = strings.Replace(strings.Replace(strings.Join(r, " "), "(", "", -1), ")", "", -1)
			case "Station Name":
				results["name"] = strings.Join(r, " ")
			case "Unit Status":
				results["status"] = strings.Join(r, " ")
			case "DC Input Voltage":
				results["supply"] = strings.Join(r, " ")
			case "Transceiver Temperature":
				results["temperature"] = strings.Join(r, " ")
			}
		}
	})

	return results, nil
}
开发者ID:ozym,项目名称:dmc,代码行数:60,代码来源:vipr.go

示例13: TestEventsPause

func TestEventsPause(t *testing.T) {
	out, _, _ := cmd(t, "images", "-q")
	image := strings.Split(out, "\n")[0]
	cmd(t, "run", "-d", "--name", "testeventpause", image, "sleep", "2")
	cmd(t, "pause", "testeventpause")
	cmd(t, "unpause", "testeventpause")
	eventsCmd := exec.Command(dockerBinary, "events", "--since=0", fmt.Sprintf("--until=%d", time.Now().Unix()))
	out, _, _ = runCommandWithOutput(eventsCmd)
	events := strings.Split(out, "\n")
	if len(events) <= 1 {
		t.Fatalf("Missing expected event")
	}

	pauseEvent := strings.Fields(events[len(events)-3])
	unpauseEvent := strings.Fields(events[len(events)-2])

	if pauseEvent[len(pauseEvent)-1] != "pause" {
		t.Fatalf("event should be pause, not %#v", pauseEvent)
	}
	if unpauseEvent[len(unpauseEvent)-1] != "unpause" {
		t.Fatalf("event should be pause, not %#v", unpauseEvent)
	}

	logDone("events - pause/unpause is logged")
}
开发者ID:baoruxing,项目名称:docker,代码行数:25,代码来源:docker_cli_events_test.go

示例14: Command

func Command(cmd string) []string {
	command := []byte(strings.ToLower(cmd))
	if what_time.Match(command) {
		current_time := time.LocalTime()
		formatted_time := current_time.Format(time.Kitchen)
		return []string{formatted_time}
	} else if who_are_you.Match(command) {
		return []string{"I am Gopher, I'm here to help."}
	} else if cmd == "gopher quit" {
		os.Exit(0)
	} else if matches := gist.FindSubmatch(command); matches != nil {
		for _, match := range matches {
			fmt.Printf("Match: %s\n", string(match))
		}

		if len(matches) > 1 {
			gist_id, err := strconv.Atoui(string(matches[1]))
			if err != nil {
				fmt.Printf("Could not parse the gist_id: %s\n", string(matches[1]))
				return []string{}
			}
			gist_file := strings.TrimSpace(string(matches[2]))
			fmt.Printf("Gist file: %s\n", gist_file)
			gist_content := GetGist(gist_id, gist_file)
			fmt.Printf("Gist Content: %s\n", gist_content)
			return gist_content
		}
		return []string{}
	} else if matches := hoogle.FindSubmatch([]byte(cmd)); matches != nil {
		return Hoogle(strings.Fields(string(matches[1])))
	} else if matches := man_page.FindSubmatch([]byte(cmd)); matches != nil {
		return Manpage(strings.Fields(string(matches[1])))
	}
	return []string{"Dunno what you are asking me. WTF dude?"}
}
开发者ID:wjlroe,项目名称:gocampfire,代码行数:35,代码来源:commands.go

示例15: TestPullAllTagsFromCentralRegistry

// TestPullAllTagsFromCentralRegistry pulls using `all-tags` for a given image and verifies that it
// results in more images than a naked pull.
func (s *DockerHubPullSuite) TestPullAllTagsFromCentralRegistry(c *check.C) {
	testRequires(c, DaemonIsLinux)
	s.Cmd(c, "pull", "busybox")
	outImageCmd := s.Cmd(c, "images", "busybox")
	splitOutImageCmd := strings.Split(strings.TrimSpace(outImageCmd), "\n")
	c.Assert(splitOutImageCmd, checker.HasLen, 2, check.Commentf("expected a single entry in images\n%v", outImageCmd))

	s.Cmd(c, "pull", "--all-tags=true", "busybox")
	outImageAllTagCmd := s.Cmd(c, "images", "busybox")
	if linesCount := strings.Count(outImageAllTagCmd, "\n"); linesCount <= 2 {
		c.Fatalf("pulling all tags should provide more images, got %d", linesCount-1)
	}

	// Verify that the line for 'busybox:latest' is left unchanged.
	var latestLine string
	for _, line := range strings.Split(outImageAllTagCmd, "\n") {
		if strings.HasPrefix(line, "busybox") && strings.Contains(line, "latest") {
			latestLine = line
			break
		}
	}
	c.Assert(latestLine, checker.Not(checker.Equals), "", check.Commentf("no entry for busybox:latest found after pulling all tags"))
	splitLatest := strings.Fields(latestLine)
	splitCurrent := strings.Fields(splitOutImageCmd[1])
	c.Assert(splitLatest, checker.DeepEquals, splitCurrent, check.Commentf("busybox:latest was changed after pulling all tags"))
}
开发者ID:rzzdy,项目名称:docker,代码行数:28,代码来源:docker_cli_pull_test.go


注:本文中的strings.Fields函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。