예제 #1
0
// Parse an individual line from Linux's /proc/net/dev.
func (nic *NICSampler) parseLine(line string) (err error) {
	var dev string
	var rx_byte, rx_pkt, rx_err, rx_drop uint64
	var rx_fifo, rx_frame, rx_comp, rx_mcast uint64
	var tx_byte, tx_pkt, tx_err, tx_drop uint64
	var tx_fifo, tx_coll, tx_carr, tx_comp uint64

	if strings.Contains(line, "|") {
		return
	}
	_, err = fmt.Sscanln(line,
		&dev,
		&rx_byte, &rx_pkt, &rx_err, &rx_drop,
		&rx_fifo, &rx_frame, &rx_comp, &rx_mcast,
		&tx_byte, &tx_pkt, &tx_err, &tx_drop,
		&tx_fifo, &tx_coll, &tx_carr, &tx_comp)
	if err != nil {
		return
	}
	dev = dev[0 : len(dev)-1]
	if strings.HasPrefix(dev, "lo") {
		return
	}
	nic.sink.Write("net",
		dev,
		rx_byte, rx_pkt, rx_err, rx_drop,
		tx_byte, tx_pkt, tx_err, tx_drop)
	return
}
func (fakeUi *FakeUi) Scanln(args ...interface{}) (int, error) {
	fakeUi.Args = args

	fmt.Sscanln(fakeUi.UserInput, args[0])

	return fakeUi.ScanlnRc, fakeUi.ScanlnErr
}
예제 #3
0
// Who owns the lockfile?
func (l Lockfile) GetOwner() (*os.Process, error) {
	name := string(l)

	// Ok, see, if we have a stale lockfile here
	content, err := ioutil.ReadFile(name)
	if err != nil {
		return nil, err
	}

	var pid int
	_, err = fmt.Sscanln(string(content), &pid)
	if err != nil {
		return nil, ErrInvalidPid
	}

	// try hard for pids. If no pid, the lockfile is junk anyway and we delete it.
	if pid > 0 {
		p, err := os.FindProcess(pid)
		if err != nil {
			return nil, err
		}
		return p, isProcessAlive(p)
	} else {
		return nil, ErrInvalidPid
	}
	panic("Not reached")
}
예제 #4
0
// boxFromString returns the box defined by a string of the form "x y w h id".
func boxFromString(in string) (b box, err error) {
	_, err = fmt.Sscanln(in, &b.x, &b.y, &b.w, &b.l, &b.id)
	if b == emptybox {
		return b, errEmpty
	}
	if b.w == 0 && b.l == 0 {
		return b, errZeroBox
	}
	return
}
예제 #5
0
// Parse Linux's /proc/uptime output.
func (uptime *UptimeSampler) parseLine(line string) (err error) {
	var up, idle float64

	_, err = fmt.Sscanln(line, &up, &idle)
	if err != nil {
		return
	}
	uptime.sink.Write("uptime", uint64(up))
	return
}
예제 #6
0
func main() {
	str := "34  343  245"
	var a, b, c int
	fmt.Sscan(str, &a, &b, &c)
	fmt.Println(a, b, c)
	fmt.Sscanf(str, "%d %d %d", &a, &b, &c)
	fmt.Println(a, b, c)
	fmt.Sscanln(str, &a, &b, &c)
	fmt.Println(a, b, c)
}
예제 #7
0
func readLockfile(path string) (pid int, err error) {
	d, err := ioutil.ReadFile(path)
	if os.IsNotExist(err) {
		return 0, nil
	}
	if err != nil {
		return 0, err
	}
	if _, err := fmt.Sscanln(string(d), &pid); err != nil {
		return 0, ErrReadingLockfile
	}
	return pid, nil
}
예제 #8
0
func main() {
	cgreader.RunStaticProgram(
		"../../input/ascii_4.txt",
		"../../output/ascii_4.txt",
		true,
		func(input <-chan string, output chan string) {
			var width, height int
			var text string

			fmt.Sscanln(<-input, &width)
			fmt.Sscanln(<-input, &height)
			fmt.Sscanln(<-input, &text)

			text = strings.ToUpper(text)

			ascii := make([]string, height)
			for i := 0; i < height; i++ {
				ascii[i] = <-input
			}

			lines := make([]string, height)
			for _, char := range text {
				character := int(char) - 65
				if character < 0 || character > 26 {
					character = 26
				}
				for i := range lines {
					position := character * width
					lines[i] += ascii[i][position : position+width]
				}
			}

			for _, line := range lines {
				output <- fmt.Sprintln(line)
			}
		})
}
예제 #9
0
// Update from /proc/stst
func (s *procStat) Update() (st procStat, err error) {
	data, err := readFile(filepath.Join(PROC_DIR, "stat"))
	if err != nil {
		log.Println(err)
		return
	}
	var ig string
	fmt.Sscanln(string(data), &ig, &s.User, &s.Nice, &s.Sys, &s.Idle, &s.Iowait, &s.Irq, &s.Softirq)
	st = *s
	// Cpu Count
	re, _ := regexp.Compile("\ncpu[0-9]")
	s.Ncpu = len(re.FindAllString(string(data), 100))
	s.timeStamp = time.Now()
	return
}
예제 #10
0
파일: io.go 프로젝트: voltron42/rpgPractice
func main() {
	reader := bufio.NewReader(os.Stdin)
	fmt.Print("Enter text: ")
	text, _ := reader.ReadString('\n')
	fmt.Println(text)

	fmt.Println("Enter text: ")
	text2 := ""
	fmt.Scanln(text2)
	fmt.Println(text2)

	ln := ""
	fmt.Sscanln("%v", ln)
	fmt.Println(ln)
}
예제 #11
0
func scanPidLine(content []byte) (int, error) {
	if len(content) == 0 {
		return 0, ErrInvalidPid
	}

	var pid int
	if _, err := fmt.Sscanln(string(content), &pid); err != nil {
		return 0, ErrInvalidPid
	}

	if pid <= 0 {
		return 0, ErrInvalidPid
	}
	return pid, nil
}
예제 #12
0
파일: value.go 프로젝트: earneet/elvish
// toRat converts a Value to rat. A str can be converted to a rat if it can be
// parsed. A rat is returned as-is. Other types of values cannot be converted.
func toRat(v Value) (rat, error) {
	switch v := v.(type) {
	case rat:
		return v, nil
	case str:
		r := big.Rat{}
		_, err := fmt.Sscanln(string(v), &r)
		if err != nil {
			return rat{}, fmt.Errorf("%s cannot be parsed as rat", v.Repr())
		}
		return rat{&r}, nil
	default:
		return rat{}, errOnlyStrOrRat
	}
}
예제 #13
0
func str() {
	var a int
	var b int

	log.Printf("a: %d, b: %d", a, b)
	fmt.Sscan("20\n20", &a, &b)
	log.Printf("a: %d, b: %d", a, b)

	fmt.Sscanf("(15, 30)", "(%d, %d)", &a, &b)
	log.Printf("a: %d, b: %d", a, b)

	// Will not go past the newline, only scans a
	fmt.Sscanln("10\n10", &a, &b)
	log.Printf("a: %d, b: %d", a, b)
}
예제 #14
0
// Returns system uptime as time.Duration.
func getSystemUptime() (uptime time.Duration, err error) {
	buf, err := ioutil.ReadFile("/proc/uptime")
	if err != nil {
		return uptime, err
	}
	var up, idle float64
	n, err := fmt.Sscanln(string(buf), &up, &idle)
	if err != nil {
		return uptime, err
	}
	if n != 2 {
		return uptime, errors.New("failed parsing /proc/uptime")
	}
	uptime = time.Duration(up) * time.Second

	return uptime, nil
}
예제 #15
0
func main() {
	scanner := bufio.NewScanner(os.Stdin)

	timetable := readTimetable(scanner)

	var departureStation, arrivalStation, departureTime uint32
	for scanner.Scan() {
		if len(scanner.Text()) == 0 {
			os.Exit(0)
		} else {
			_, err := fmt.Sscanln(scanner.Text(), &departureStation, &arrivalStation, &departureTime)
			if err != nil {
				panic(err)
			}
			timetable.compute(departureStation, arrivalStation, departureTime)
		}
	}
}
예제 #16
0
// Who owns the lockfile?
func (l Lockfile) GetOwner() (*os.Process, error) {
	name := string(l)

	// Ok, see, if we have a stale lockfile here
	content, err := ioutil.ReadFile(name)
	if err != nil {
		return nil, err
	}

	var pid int
	_, err = fmt.Sscanln(string(content), &pid)
	if err != nil {
		return nil, err
	}

	// try hard for pids. If no pid, the lockfile is junk anyway and we delete it.
	if pid > 0 {
		p, err := os.FindProcess(pid)
		if err != nil {
			return nil, err
		}
		err = p.Signal(os.Signal(syscall.Signal(0)))
		if err == nil {
			return p, nil
		}
		errno, ok := err.(syscall.Errno)
		if !ok {
			return nil, err
		}

		switch errno {
		case syscall.ESRCH:
			return nil, ErrDeadOwner
		case syscall.EPERM:
			return p, nil
		default:
			return nil, err
		}
	} else {
		return nil, ErrInvalidPid
	}
	panic("Not reached")
}
func main() {
	reader := bufio.NewReader(os.Stdin)
	tString, _ := reader.ReadString('\n')
	t, _ := strconv.Atoi(tString)

	for i := 0; i < t; i++ {
		nString, _ := reader.ReadString('\n')
		n, _ := strconv.Atoi(nString)
	}
	fmt.Println("Enter text: ")
	text2 := ""
	fmt.Scanln(text2)
	fmt.Println(text2)

	ln := ""
	fmt.Sscanln("%v", ln)
	fmt.Println(ln)
	fmt.Println("Hello World!")
}
예제 #18
0
func SPrintScanPrac12() {
	var num1 int
	var num2 float32
	var s string

	input1 := "1\n1.1\nHello"
	n, _ := fmt.Sscan(input1, &num1, &num2, &s)
	fmt.Println("입력 개수 : ", n)
	fmt.Println(num1, num2, s)

	input2 := "1 1.1 Hello"
	n, _ = fmt.Sscanln(input2, &num1, &num2, &s)
	fmt.Println("입력 개개 : ", n)
	fmt.Println(num1, num2, s)

	input3 := "1,1.1,Hello"
	n, _ = fmt.Sscanf(input3, "%d,%f,%s", &num1, &num2, &s)
	fmt.Println("입력 갯수 : ", n)
	fmt.Println(num1, num2, s)
}
예제 #19
0
// Read in the offsets for an IP from a file. File name == IP address.
func GetOffset(addr string) (HostOffset, os.Error) {
	data, err := ioutil.ReadFile(addr)
	o := HostOffset{}

	if err != nil {
		return o, err
	}

	str := string(data)

	_, err = fmt.Sscanln(str,
		&o.Year.Op, &o.Year.Value,
		&o.Month.Op, &o.Month.Value,
		&o.Day.Op, &o.Day.Value,
		&o.Hour.Op, &o.Hour.Value,
		&o.Minute.Op, &o.Minute.Value,
		&o.Second.Op, &o.Second.Value)

	return o, err
}
예제 #20
0
func main() {
	var num1 int
	var num2 float32
	var s string

	input1 := "1\n1.1\nHello"
	n, _ := fmt.Sscan(input1, &num1, &num2, &s) // 공백, 개행 문자로 구분된 문자열에서 입력을 받음
	fmt.Println("입력 개수:", n)                    // 입력 개수: 3
	fmt.Println(num1, num2, s)                  // 1 1.1 Hello

	input2 := "1 1.1 Hello"
	n, _ = fmt.Sscanln(input2, &num1, &num2, &s) // 공백으로 구분된 문자열에서 입력을 받음
	fmt.Println("입력 개수:", n)                     // 입력 개수: 3
	fmt.Println(num1, num2, s)                   // 1 1.1 Hello

	input3 := "1,1.1,Hello"
	n, _ = fmt.Sscanf(input3, "%d,%f,%s", &num1, &num2, &s) // 문자열에서 형식을 지정하여 입력을 받음
	fmt.Println("입력 개수:", n)                                // 입력 개수: 3
	fmt.Println(num1, num2, s)                              // 1 1.1 Hello
}
예제 #21
0
파일: sprint.go 프로젝트: kangaukju/golang
func main() {
	var s1, s2, s3 string

	s1 = fmt.Sprint(1, 1.1, "Kinow")
	fmt.Println(s1)

	s2 = fmt.Sprintln(1, 1.1, "Kinow")
	fmt.Println(s2)

	s3 = fmt.Sprintf("%d %f %s\n", 1, 1.1, "Kinow")
	fmt.Println(s3)

	var num1 int
	var num2 float32
	var s string

	input1 := "1\n1.1\nHello"
	n, _ := fmt.Sscan(input1, &num1, &num2, &s)

	fmt.Println("입력개수:", n)
	fmt.Println(num1, num2, s)

	num1 = 0
	num2 = 0
	s = ""

	input2 := "1 1.1 Hello"
	n, _ = fmt.Sscanln(input2, &num1, &num2, &s)
	fmt.Println("입력개수:", n)
	fmt.Println(num1, num2, s)

	num1 = 0
	num2 = 0
	s = ""

	input3 := "1,1.1,Hello World"
	n, _ = fmt.Sscanf(input3, "%d,%f,%s", &num1, &num2, &s)
	fmt.Println("입력개수:", n)
	fmt.Println(num1, num2, s)
}
예제 #22
0
파일: main.go 프로젝트: putterson/uxobot
func getHumanMove(board *Board, lastmove Move) (move Move) {
	move = NoMove()
	var b, c int
	for {
		fmt.Printf(colourString("[move]>"))
		var input, _ = Stdin.ReadString('\n')
		var _, err = fmt.Sscanln(input, &b, &c)
		if err == nil {
			if b > 0 && b < 10 && c > 0 && c < 10 {
				move = move_notation(b, c)
				//fmt.Printf("x:%d y:%d\n",move.x,move.y)
				for _, vm := range genHumanChildren(board, lastmove) {
					if move == vm {
						return
					}
				}
			}
			// if there were no matching moves
			fmt.Println("Please make a valid move, or type help.")
		} else if strings.Contains(input, "help") {
			fmt.Println("There should be some help here...")
			fmt.Println("Valid moves are of the form \"1 9\" ie. a board number followed by a cell number (1-9)")
		} else if strings.Contains(input, "quit") || strings.Contains(input, "exit") {
			return move
		} else if strings.Contains(input, "evalb") {
			var i int
			for i = 1; i < 10; i++ {
				move = move_to_subboard(move_notation(i, i))
				fmt.Printf("Score of board %d is: %d\n",
					i,
					evalSubBoard(board, move.x, move.y))
			}
		} else if strings.Contains(input, "evala") {
			fmt.Printf("Score of whole board is: %d\n", evalBoard(board))
		} else {
			fmt.Println("Enter a valid command or type help.")
		}
	}
}
예제 #23
0
func LoadUrls(fname string) (urls []string, err error) {

	f, err := os.Open(fname)
	if err != nil {
		if e, ok := err.(*os.PathError); ok && e.Err == syscall.ENOENT {
			return nil, syscall.ENOENT
		}
		return
	}
	defer f.Close()

	br := bufio.NewReaderSize(f, 4096)
	for {
		line, isPrefix, err2 := br.ReadLine()
		err = err2
		if err != nil || isPrefix {
			if err == io.EOF {
				err = nil
				break
			}
			return
		}
		line1 := string(line) + "\n"
		var url string
		_, err = fmt.Sscanln(line1, &url)
		if err != nil {
			return
		}
		urlUnescape, err2 := tab.Unescape(url)
		err = err2
		if err != nil {
			return
		}
		urls = append(urls, urlUnescape)
	}

	return
}
예제 #24
0
func readTimetable(scanner *bufio.Scanner) Timetable {
	timetable := make([]Connection, 0)

	for scanner.Scan() {
		if len(scanner.Text()) == 0 {
			break
		} else {
			connection := Connection{}
			_, err := fmt.Sscanln(
				scanner.Text(),
				&connection.departureStation,
				&connection.arrivalStation,
				&connection.departureTime,
				&connection.arrivalTime)
			if err != nil {
				panic(err)
			}
			timetable = append(timetable, connection)
		}
	}

	return timetable
}
예제 #25
0
func (r *truckReader) Next() (*truck, error) {
	if r.err != nil {
		return nil, r.err
	}

	t := &truck{}
	for {
		if r.scn.Scan() == false {
			r.err = r.scn.Err()
			if r.err == nil {
				r.err = io.EOF
			}
			return nil, r.err
		}

		if strings.HasPrefix(r.scn.Text(), "truck") {
			var truck string
			_, r.err = fmt.Sscanln(r.scn.Text(), &truck, &t.id)
			if r.err != nil {
				return nil, r.err
			}
			continue
		}

		if r.scn.Text() == "endtruck" {
			break
		}

		var p pallet
		p, r.err = palletFromString(r.scn.Text())
		if r.err != nil {
			return nil, r.err
		}
		t.pallets = append(t.pallets, p)
	}
	return t, r.err
}
예제 #26
0
파일: fmt.go 프로젝트: bmatsuo/go-dfmt
func Sscanln(str string, a ...interface{}) (n int, err error) {
	return fmt.Sscanln(str, a...)
}
예제 #27
0
func StringScanLine(stringToScan string, arguments ...interface{}) (numberOfBytesRead int, errorValue error) {
	return fmt.Sscanln(stringToScan, arguments...)
}
예제 #28
0
func (model *Model) DeserializeFromFile(file *os.File) {

	section := 0

	scanner := bufio.NewScanner(file)

	for scanner.Scan() {

		line := scanner.Text()
		if line == "" {
			continue
		}

		if strings.Contains(line, "TotalEvents") {

			var junk string
			var te uint
			_, err := fmt.Sscanln(line, &junk, &te)
			if err == nil {
				fmt.Printf("[Aviso] Model contains %d events\n", te)
			} else {
				log.Fatal(err)
			}
			model.totalEvents = te

			if section != 0 {

				log.Fatal("[AVISO] Error Deserializing Model - Saw TotalEvents when section was not 0")

			} else {

				section = 1
				continue

			}

		}

		if strings.Contains(line, "NumFailures") {

			var junk string
			_, err := fmt.Sscanln(line, &junk, &(model.numFailures))
			if err == nil {
				fmt.Printf("[AVISO] Model contained %d Failures\n", model.numFailures)
			} else {
				log.Fatal(err)
			}

			if section != 1 {

				log.Fatal("[AVISO] Error Deserializing Model - Saw NumFailurs when section was not 1")

			} else {

				section = 2
				continue

			}

		}

		if strings.Contains(line, "failurePairs") {

			if section != 2 {

				log.Fatal("[AVISO] Error Deserializing Model - Saw failurePairs when section was not 2")

			} else {

				section = 3
				continue

			}

		}

		if strings.Contains(line, "endOfModel") {

			if section != 3 {

				log.Fatal("[AVISO] Error Deserializing Model - Saw endOfModel when section was not 3")

			} else {

				file.Close()
				return

			}

		}

		/*Not a section header.  We're in a section*/
		if section == 2 {

			var first, second string
			var freqs []uint
			var strs []string = strings.Split(line, " ")
			first = strs[0]
			second = strs[1]
			for i := range strs {

				if i == 0 || i == 1 {

					continue

				}

				s, _ := strconv.Atoi(strs[i])
				freqs = append(freqs, uint(s))

			}

			/*section 2 is the correct pairs section*/
			model.addCorrectPairWithFreqs(first, second, freqs)

		}

		/*Not a section header.  We're in a section*/
		if section == 3 {

			var first, second string
			var class, freq uint
			/*section 2 is the correct pairs section*/
			ret, err := fmt.Sscanln(line, &class, &first, &second, &freq)
			if err != nil {
				log.Fatal(err)
			}
			if ret == 4 {
				model.addPairToModel(class, first, second, freq)
			}

		}

	}

}
예제 #29
0
파일: srt.go 프로젝트: suapapa/go_subtitle
// ReadSrt read srt format subtitle from data slice
func ReadSrt(r io.Reader) (Book, error) {
	var book Book
	var script Script

	const (
		StateIdx = iota
		StateTs
		StateScript
	)
	state := StateIdx

	scanner := bufio.NewScanner(r)
	for scanner.Scan() {
		line := scanner.Text()

		switch state {
		case StateIdx:
			/* log.Println("StateIdx") */
			_, err := fmt.Sscanln(line, &script.Idx)
			if err != nil {
				log.Fatalf("failed to parse index! in \"%s\" : %s",
					line, err)
			}
			state = StateTs

		case StateTs:
			/* log.Println("StateTs") */
			var sH, sM, sS, sMs int
			var eH, eM, eS, eMs int
			_, err := fmt.Sscanf(line,
				"%d:%d:%d,%d --> %d:%d:%d,%d",
				&sH, &sM, &sS, &sMs,
				&eH, &eM, &eS, &eMs)
			if err != nil {
				log.Fatalln("failed to parse timestamp!")
			}

			startMs := sMs + sS*1000 + sM*60*1000 + sH*60*60*1000
			script.Start = time.Duration(startMs) * time.Millisecond

			endMs := eMs + eS*1000 + eM*60*1000 + eH*60*60*1000
			script.End = time.Duration(endMs) * time.Millisecond

			script.Text = ""
			/* log.Println("script = ", script) */
			state = StateScript

		case StateScript:
			/* log.Println("StateScript") */
			if line == "" {
				/* log.Println("script = ", script) */
				book = append(book, script)
				state = StateIdx
			} else {
				if script.Text != "" {
					script.Text += "\n"
				}
				script.Text += line
			}
		}

	}
	if err := scanner.Err(); err != nil {
		return nil, err
	}

	/* log.Println("book = ", book) */
	return book, nil
}