Esempio n. 1
0
func getLoad() string {

	switch runtime.GOOS {
	case "windows": // ...
		return "Windows"
	case "linux": // ...
		cmd := exec.Command("cat", "/proc/loadavg")
		bs, err := cmd.Output()
		if err != nil {
			return "top error"
		}
		offset := bytes.IndexRune(bs, '\n')
		if offset < 1 {
			offset = len(bs)
		}
		return string(bs[:offset])
	case "freebsd": // ...
		return "freebsd"
	case "darwin": // ...
		cmd := exec.Command("sysctl", "-n", "vm.loadavg")
		bs, err := cmd.Output()
		if err != nil {
			return "top error"
		}
		offset := bytes.IndexRune(bs, '\n')
		if offset < 1 {
			offset = len(bs)
		}
		return string(bs[:offset])
	}
	return "dunno!"

}
Esempio n. 2
0
func statLeds(oC *tCommand) {
	const kLeds = "/sys/class/leds/"
	aList, _ := ioutil.ReadDir(kLeds)
	const kFields = "%-15s%-11s%-10s%-10s%s\n"

lRestart:
	oC.buf = []byte(fmt.Sprintf(kFields, "Device", "Brightness", "Delay_on", "Delay_off", "Trigger"))

	for _, a := range aList {
		aBright, _ := ioutil.ReadFile(kLeds + a.Name() + "/brightness")
		aTriggr, _ := ioutil.ReadFile(kLeds + a.Name() + "/trigger")
		aBright = aBright[:len(aBright)-1]
		aTriggr = aTriggr[bytes.IndexRune(aTriggr, '[')+1 : bytes.IndexRune(aTriggr, ']')]
		var aDelayOn, aDelayOff []byte
		if bytes.Equal(aTriggr, []byte("timer")) {
			aDelayOn, _ = ioutil.ReadFile(kLeds + a.Name() + "/delay_on")
			aDelayOff, _ = ioutil.ReadFile(kLeds + a.Name() + "/delay_off")
			if len(aDelayOn) == 0 || len(aDelayOff) == 0 {
				goto lRestart
			}
			aDelayOn = aDelayOn[:len(aDelayOn)-1]
			aDelayOff = aDelayOff[:len(aDelayOff)-1]
		} else {
			aDelayOn = []byte("--")
			aDelayOff = aDelayOn
		}
		oC.buf = append(oC.buf, fmt.Sprintf(kFields, a.Name(), aBright, aDelayOn, aDelayOff, aTriggr)...)
	}
	if sDebug {
		fmt.Println(oC.name)
	}
}
Esempio n. 3
0
func ExampleIndexRune() {
	fmt.Println(bytes.IndexRune([]byte("chicken"), 'k'))
	fmt.Println(bytes.IndexRune([]byte("chicken"), 'd'))
	// Output:
	// 4
	// -1
}
Esempio n. 4
0
/**
 * Lexer::NonMatchOneOrMore
 */
func (l *lexer) NonMatchOneOrMore(match []byte) bool {
	var r rune
	if r = l.PeekRune(0); r != RuneEOF && bytes.IndexRune(match, r) == -1 {
		l.NextRune()
		for r = l.PeekRune(0); r != RuneEOF && bytes.IndexRune(match, r) == -1; r = l.PeekRune(0) {
			l.NextRune()
		}
		return true
	}
	return false
}
Esempio n. 5
0
// Lexer::MatchOneOrMoreBytes
func (l *lex) MatchOneOrMoreBytes(match []byte) bool {
	var r rune
	if r = l.PeekRune(0); r != RuneEOF && bytes.IndexRune(match, r) >= 0 {
		l.NextRune()
		for r = l.PeekRune(0); r != RuneEOF && bytes.IndexRune(match, r) >= 0; r = l.PeekRune(0) {
			l.NextRune()
		}
		return true
	}
	return false
}
Esempio n. 6
0
func ReadConfig() (accesskey string, secret string, err error) {
	homedir := os.Getenv("HOME")
	if homedir == "" {
		u, err := user.Current()
		if err != nil {
			return "", "", err
		}
		homedir = u.HomeDir
	}
	cfg, err := ioutil.ReadFile(homedir + "/.s3cfg")
	if err != nil {
		return
	}

	for off := 0; off != -1; off = bytes.IndexRune(cfg, '\n') {
		line := cfg[:off]
		cfg = cfg[off+1:]
		tokens := bytes.SplitN(line, []byte(" = "), 2)
		if len(tokens) != 2 {
			continue
		}
		switch string(tokens[0]) {
		case "access_key":
			accesskey = string(tokens[1])
		case "secret_key":
			secret = string(tokens[1])
		}
	}
	return
}
Esempio n. 7
0
// Fire implements logrus.Hook interface
func (h *Hook) Fire(entry *logrus.Entry) error {
	p := bytes.TrimSpace([]byte(entry.Message))
	short := bytes.NewBuffer(p)
	full := ""
	if i := bytes.IndexRune(p, '\n'); i > 0 {
		full = short.String()
		short.Truncate(i)
	}
	extra := map[string]interface{}{}
	// merge entry.Data & extra & facility
	for k, v := range entry.Data {
		extra["_"+k] = v // prefix with _ will be treated as an additional field
	}
	for k, v := range h.extra {
		extra["_"+k] = v // prefix with _ will be treated as an additional field
	}
	extra["_facility"] = h.facility

	m := &gelf.Message{
		Version:  "1.1",
		Host:     h.hostname,
		Short:    short.String(),
		Full:     full,
		TimeUnix: float64(now().UnixNano()) / 1e9,
		Level:    int32(entry.Level),
		Extra:    extra,
	}
	return h.w.WriteMessage(m)
}
Esempio n. 8
0
func assertionFilter(r rune) rune {
	// wish that base64.go exported this publicly:
	if bytes.IndexRune([]byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_~.="), r) < 0 {
		return rune(-1)
	}
	return r
}
Esempio n. 9
0
func (d Dictionary) translateWithoutSametypesequence(data []byte) (items []*TranslationItem) {
	var dataPos int
	dataSize := len(data)

	for {
		t := data[dataPos]

		dataPos++

		switch t {
		case 'm', 'l', 'g', 't', 'x', 'y', 'k', 'w', 'h', 'r':
			end := bytes.IndexRune(data[dataPos:], '\000')

			if end < 0 { // last item
				items = append(items, &TranslationItem{Type: rune(t), Data: data[dataPos:dataSize]})
				dataPos = dataSize
			} else {
				items = append(items, &TranslationItem{Type: rune(t), Data: data[dataPos : dataPos+end+1]})
				dataPos += end + 1
			}
		case 'W', 'P':
			size := binary.BigEndian.Uint32(data[dataPos : dataPos+4])
			items = append(items, &TranslationItem{Type: rune(t), Data: data[dataPos+4 : dataPos+int(size)+5]})
			dataPos += int(size) + 5
		}

		if dataPos >= dataSize {
			break
		}
	}

	return
}
Esempio n. 10
0
// Lexer::MatchOneBytes
func (l *lex) MatchOneBytes(match []byte) bool {
	if r := l.PeekRune(0); r != RuneEOF && bytes.IndexRune(match, r) >= 0 {
		l.NextRune()
		return true
	}
	return false
}
// Modifies `s` in-place.
func ScrambleBytes(s []byte) []byte {
	isArray := len(s) >= 2 && s[0] == '{' && s[len(s)-1] == '}'

	hash := sha256.New()
	// Hard-coding this constant wins less than 3% in BenchmarkScrambleBytes
	const sumLength = 32 // SHA256/8
	hash.Write(Salt)
	hash.Write(s)
	sumBytes := hash.Sum(nil)

	reader := bytes.NewReader(s)
	var r rune
	var err error
	for i := 0; ; i++ {
		r, _, err = reader.ReadRune()
		if err != nil {
			s = s[:i]
			break
		}
		if !isArray || bytes.IndexRune(bytesKeep, r) == -1 {
			// Do not insert, so should not obstruct reader.
			s[i] = bytesOutputAlphabet[(sumBytes[i%sumLength]+byte(r))%bytesOutputAlphabetLength]
		} else {
			// Possibly shift bytes to beginning of s.
			s[i] = byte(r)
		}
	}
	return s
}
Esempio n. 12
0
/**
 * lex is the starting StateFn for lexing the input into tokens
 */
func lex(l lexer.Lexer) lexer.StateFn {
	// EOF
	if l.MatchEOF() {
		l.EmitEOF()
		return nil // We're done here
	}

	// Skip whitespace
	if l.MatchOneOrMoreBytes(bytesWhitespace) {
		l.IgnoreToken()
	}

	// Single-char token?
	if i := bytes.IndexRune(singleChars, l.PeekRune(0)); i >= 0 {
		l.NextRune()
		l.EmitToken(singleTokens[i])
		return lex
	}

	// Quote
	if l.MatchOneRune('"') {
		l.EmitToken(T_OPEN_QUOTE)
		return lexQuotedString

		// Unquoted String
	} else if l.MatchOneBytes(bytesAlpha) && l.MatchZeroOrMoreBytes(bytesAlphaNum) {
		l.EmitTokenWithBytes(T_UNQUOTED_STRING)

		// Number:  /-?(0|([1-9][0-9]*))(\.[0-9]+)?([eE][-+]?[0-9]+)?/
	} else if m := matcher.New(l); m.
		MatchZeroOrOneRune('-').                     // -?      // Leading '-' (optional)
		And().Begin().                               // (       // Begin Integer (required)
		MatchOneRune('0').                           // 0       //   0 is stand alone, unsigned
		Or().Begin().                                // |(      //   Begin non-zero
		MatchOneBytes(bytes1to9).                    // [1-9]   //     First digit - No leading 0's (required)
		And().MatchZeroOrMoreBytes(bytesDigits).     // [0-9]*  //     Extra digits (optional)
		End().MatchOne().                            // )       //   End non-zero
		End().MatchOne().                            // )       // End Integer
		And().Begin().                               // (       // Begin Fraction (optional)
		MatchOneRune('.').                           // \.      //   Decimal '.' (required)
		And().MatchOneOrMoreBytes(bytesDigits).      // [0-9]+  //   Digits (required)
		End().MatchZeroOrOne().                      // )?      // End Fraction
		And().Begin().                               // (       // Begin Exponent (optional)
		MatchOneBytes([]byte{'e', 'E'}).             // [eE]    //   'e' | 'E' (required)
		And().MatchZeroOrOneBytes([]byte{'-', '+'}). // [-+]?   //   Sign (optional)
		And().MatchOneOrMoreBytes(bytesDigits).      // [0-9]+  //   Digits (required)
		End().MatchZeroOrOne().                      //  )?     // End Exponent
		Result() {
		l.EmitTokenWithBytes(T_NUMBER)
		return lex

		// Unknown
	} else {
		l.NextRune() // Consume unknown rune
		l.EmitTokenWithBytes(T_UNKNOWN)
	}

	// See you again soon!
	return lex
}
Esempio n. 13
0
func (d Dictionary) translateWithSametypesequence(data []byte) (items []*TranslationItem) {
	seq := d.info.Options["sametypesequence"]

	seqLen := len(seq)

	var dataPos int
	dataSize := len(data)

	for i, t := range seq {
		switch t {
		case 'm', 'l', 'g', 't', 'x', 'y', 'k', 'w', 'h', 'r':
			// if last seq item
			if i == seqLen-1 {
				items = append(items, &TranslationItem{Type: t, Data: data[dataPos:dataSize]})
			} else {
				end := bytes.IndexRune(data[dataPos:], '\000')
				items = append(items, &TranslationItem{Type: t, Data: data[dataPos : dataPos+end+1]})
				dataPos += end + 1
			}
		case 'W', 'P':
			if i == seqLen-1 {
				items = append(items, &TranslationItem{Type: t, Data: data[dataPos:dataSize]})
			} else {
				size := binary.BigEndian.Uint32(data[dataPos : dataPos+4])
				items = append(items, &TranslationItem{Type: t, Data: data[dataPos+4 : dataPos+int(size)+5]})
				dataPos += int(size) + 5
			}
		}
	}

	return
}
Esempio n. 14
0
func indexRune(s []byte, r rune) {
	if i := bytes.IndexRune(s, r); i == -1 {
		log.Printf("Rune %d does NOT appear in %s", r, s)
	} else {
		log.Printf("Rune %d appears at index %d in %s", r, i, s)
	}
}
Esempio n. 15
0
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Header().Add(wwwAuthenticate, fmt.Sprintf("Basic realm=\"%s\"", *realm))

	_, data, err := splitAuth(r.Header.Get(authorization))
	if err != nil {
		w.WriteHeader(401)
		return
	}

	t := time.Now()
	k := string(data)
	e, ex := cache[k]
	if ex && e.valid && t.Before(e.until) {
		w.WriteHeader(200)
		return
	}

	i := bytes.IndexRune(data, ':')
	if i < 0 {
		w.WriteHeader(401)
		return
	}
	username, password := string(data[:i]), string(data[i+1:])
	valid, err := s.authenticate(username, password)
	if valid {
		cache[k] = &entry{valid: true, until: t.Add(*ttl)}
		w.WriteHeader(200)
	} else {
		w.WriteHeader(401)
	}
}
Esempio n. 16
0
func copyBinary(sourceName, targetName, sourceDir, targetDir string) error {
	source := filepath.Join(sourceDir, sourceName)
	dest := filepath.Join(targetDir, targetName)
	if _, err := os.Stat(source); err != nil {
		if os.IsNotExist(err) {
			return fmt.Errorf("missing file %s", source)
		}
		return err
	}
	if err := CopyFile(source, dest, 0755); err != nil {
		return err
	}
	if b, err := ioutil.ReadFile(source + ".sha256"); err == nil {
		if i := bytes.IndexRune(b, ' '); i > 0 {
			b = b[:i]
		}
		expectedHash := make([]byte, hex.DecodedLen(len(b)))
		if _, err := hex.Decode(expectedHash, b); err != nil {
			return err
		}
		if err := hashCheck(dest, expectedHash, sha256.New()); err != nil {
			return err
		}
	}

	return nil
}
Esempio n. 17
0
func (dec *Decoder) Decode(msg *Message) error {
	r, rsize, err := dec.ReadRune()
	if err != nil {
		return err
	}

	if r == 0xFFFD && rsize == 3 {
		// the payload has multiple messages,
		// let's consume the first.
		// read frame length
		data := dec.Bytes()
		index := bytes.IndexRune(data, 0xFFFD)
		if index <= 0 {
			return errors.New("frame length is empty or missing")
		}
		length := positiveInt(data[:index])
		if length < 0 {
			return errors.New("frame length is not a positive integer")
		}
		data = data[index+rsize:]
		if len(data) < length {
			return errors.New("frame length is overflowing")
		}
		dec.Next(index + rsize + length)
		return decodePacket(data[:length], msg)
	}

	// rollback and read single entirely
	dec.UnreadRune()

	data := dec.Bytes()
	dec.Reset()
	return decodePacket(data, msg)
	return err
}
Esempio n. 18
0
/**
 * Lexer::NonMatchOne
 */
func (l *lexer) NonMatchOne(match []byte) bool {
	if r := l.PeekRune(0); r != RuneEOF && bytes.IndexRune(match, r) == -1 {
		l.NextRune()
		return true
	}
	return false
}
Esempio n. 19
0
// Parse parses the given array of bytes and returns key-value map.
func (p *LineParser) Parse(b []byte) (map[string][]byte, error) {
	m := make(map[string][]byte)
	for i := 0; i < len(b); {
		nextDelim := bytes.IndexRune(b[i:], p.Delimiter)
		if nextDelim < 0 {
			return nil, errors.New("failed to parse, the delimiter is not found")
		}
		key := b[i : i+nextDelim]
		i += nextDelim + 1

		nextLn := bytes.IndexByte(b[i:], '\n')
		if nextLn < 0 {
			return nil, errors.New("failed to parse, the end of line is not found")
		}
		val := b[i : i+nextLn]
		if p.TrimSpaces {
			val = bytes.TrimSpace(val)
		}
		if p.TrimQuotes {
			val = bytes.TrimFunc(val, isQuotationMark)
		}
		m[string(key)] = val
		i += nextLn + 1
	}
	return m, nil
}
Esempio n. 20
0
File: lex.go Progetto: postfix/rdf
// acceptRunMin consumes a run of runes from the valid set, returning
// true if a minimum number of runes where consumed.
func (l *lexer) acceptRunMin(valid []byte, num int) bool {
	c := 0
	for bytes.IndexRune(valid, l.next()) >= 0 {
		c++
	}
	l.backup()
	return c >= num
}
Esempio n. 21
0
func main() {
	s := []byte("你好世界")
	index := bytes.IndexRune(s, '好')
	if index >= 0 {
		fmt.Println(index)
		fmt.Println(string(s[index:]))
	}
}
Esempio n. 22
0
func detectJSONIndent(jsonContent []byte) (indent string) {
	if len(jsonContent) > 2 && jsonContent[0] == '{' && jsonContent[1] == '\n' {
		quoteIndex := bytes.IndexRune(jsonContent[1:], '"')
		if quoteIndex > 0 {
			indent = string(jsonContent[2 : quoteIndex+1])
		}
	}
	return
}
Esempio n. 23
0
func getHostname() {

	cmd := exec.Command("hostname")
	bs, err := cmd.Output()
	if err != nil {
	}
	offset := bytes.IndexRune(bs, '.')
	if offset < 1 {
		offset = len(bs)
	}
	hostname = bs[:offset]
	offset = bytes.IndexRune(hostname, '\n')
	if offset < 1 {
		offset = len(hostname)
	}
	hostname = hostname[:offset]

}
Esempio n. 24
0
File: win.go Progetto: aoeu/acme
func (w *win) typing(q0, q1 int) {
	if *debug {
		defer func(p, e int) {
			w.Addr("#%d", w.eAddr)
			text, err := w.ReadAll("data")
			if err != nil {
				panic(err)
			}
			w.Addr("#%d", w.pAddr)
			log.Printf("typing pAddr before: %d, pAddr after: %d, eAddr before: %d, eAddr after: %d [%s]\n", p, w.pAddr, e, w.eAddr, text)
		}(w.pAddr, w.eAddr)
	}

	if q0 < w.pAddr {
		d("typing before prompt")
		w.pAddr += q1 - q0
	}
	if q0 < w.eAddr {
		d("typing before entry")
		w.eAddr += q1 - q0
		return
	}
	if q0 < w.pAddr {
		return
	}

	defer w.Addr("#%d", w.pAddr)

	w.Addr("#%d", w.eAddr)
	text, err := w.ReadAll("data")
	if err != nil {
		panic("Failed to read from window: " + err.Error())
	}

	// If the last character after the prompt isn't a newline then
	// wait.  This fixes a bug where Send sends two typing
	// events, the sent text and a new line.  The text won't
	// be issued to w.send() until the final newline is received.
	// Otherwise the first insert event messes up the
	// addresses and the subsequent event (with the newline)
	// appears to have inserted a newline before pAddr.
	if r, _ := utf8.DecodeLastRune(text); r != '\n' {
		return
	}
	for {
		i := bytes.IndexRune(text, '\n')
		if i < 0 {
			break
		}

		t := string(text[:i+1])
		w.Addr("#%d,#%d", w.pAddr, w.eAddr+utf8.RuneCountInString(t))
		w.send(t)
		text = text[i+1:]
	}
}
Esempio n. 25
0
// sendEntry sends an entry to graylog synchronously
func (hook *GraylogHook) sendEntry(entry graylogEntry) {
	host, err := os.Hostname()
	if err != nil {
		host = "localhost"
	}

	w := hook.gelfLogger

	// remove trailing and leading whitespace
	p := bytes.TrimSpace([]byte(entry.Message))

	// If there are newlines in the message, use the first line
	// for the short message and set the full message to the
	// original input.  If the input has no newlines, stick the
	// whole thing in Short.
	short := p
	full := []byte("")
	if i := bytes.IndexRune(p, '\n'); i > 0 {
		short = p[:i]
		full = p
	}

	level := int32(entry.Level) + 2 // logrus levels are lower than syslog by 2

	// Don't modify entry.Data directly, as the entry will used after this hook was fired
	extra := map[string]interface{}{}
	// Merge extra fields
	for k, v := range hook.Extra {
		k = fmt.Sprintf("_%s", k) // "[...] every field you send and prefix with a _ (underscore) will be treated as an additional field."
		extra[k] = v
	}
	for k, v := range entry.Data {
		if !hook.blacklist[k] {
			k = fmt.Sprintf("_%s", k) // "[...] every field you send and prefix with a _ (underscore) will be treated as an additional field."
			extra[k] = v
		}
	}

	m := Message{
		Version:  "1.1",
		Host:     host,
		Short:    string(short),
		Full:     string(full),
		TimeUnix: float64(time.Now().UnixNano()/1000000) / 1000.,
		Level:    level,
		Facility: hook.Facility,
		File:     entry.file,
		Line:     entry.line,
		Extra:    extra,
	}

	if err := w.WriteMessage(&m); err != nil {
		fmt.Println(err)
	}

}
Esempio n. 26
0
func buildRoof(b [][]byte) [][]byte {

	//Height adjust
	add := 0
	for i := 0; i < len(b)-2; i += 2 {
		for k := 0; bytes.IndexRune(b[i][k:], '+') >= 0; k += 1 {
			k += bytes.IndexRune(b[i][k:], '+') + 1
			tmp := bytes.IndexRune(b[i][k+1:], '+')
			if tmp/2-i+1 > add {
				add = tmp/2 - i + 1
			}
			k += tmp + 1
		}
	}

	pad := make([][]byte, add)
	for i := 0; i < add; i++ {
		pad[i] = bytes.Repeat([]byte{' '}, len(b[0]))
	}
	b = append(pad, b...)

	for i := len(b) - 2; i > 0; i-- {
		for j, v := range b[i] {
			switch {
			case v == '+' && j == 0:
				b[i-1][j+1] = '/'
			case v == '+' && j == len(b[i]):
				b[i-1][j-1] = '\\'
			case v == '+' && b[i][j-1] == '-':
				b[i-1][j-1] = '\\'
			case v == '+' && b[i][j+1] == '-':
				b[i-1][j+1] = '/'
			case v == '/' && b[i][j+2] == '\\':
				b[i-1][j+1] = 'A'
			case v == '/' && b[i][j+2] != '\\':
				b[i-1][j+1] = '/'
			case v == '\\' && b[i][j-2] != '/':
				b[i-1][j-1] = '\\'
			}
		}
	}
	return b
}
Esempio n. 27
0
func commandToInt(result []byte) int {
	index := bytes.IndexRune(result, 10)
	result2 := result[0:index]
	resultString := string(result2)
	resultInt, err := strconv.Atoi(resultString)
	if err != nil {
		log.Print(err.String())
	}
	return resultInt
}
Esempio n. 28
0
func parseMailmapLine(line []byte, offset int) (name string, email string, right int) {
	var left int

	left = bytes.IndexRune(line[offset:], '<')
	if left < 0 {
		return
	}

	right = bytes.IndexRune(line[offset+left:], '>')
	if right < 0 {
		return
	}
	// Account for the fact we got the index of a sub-slice
	right = left + right

	name = string(bytes.TrimSpace(line[:offset+left]))
	email = string(bytes.TrimSpace(line[offset+left+1 : offset+right]))

	return
}
Esempio n. 29
0
// Checks whether two strings are anagrams.  (Note: does not work with runes.)
func AreAnagrams(s1 string, s2 string) bool {
	s1bytes := []byte(s1)
	for _, char := range s2 {
		i := bytes.IndexRune(s1bytes, char)
		if i == -1 {
			return false
		}
		s1bytes = append(s1bytes[:i], s1bytes[i+1:]...)
	}
	return len(s1bytes) == 0
}
Esempio n. 30
0
func parseMailmapLine(line []byte, offset int) (name string, email string, right int) {
	var left int

	left = bytes.IndexRune(line[offset:], '<')
	if left < 0 {
		return
	}

	right = bytes.IndexRune(line[offset:], '>')
	if right < 0 {
		return
	}

	name = string(bytes.TrimSpace(line[offset : offset+left]))
	email = string(bytes.TrimSpace(line[offset+left+1 : offset+right]))

	// Turn a 0-based index into a length and account for offset
	right = right + offset + 1

	return
}