Count
发布者:admin 发表于:417天前 阅读数:599 评论:0

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

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

示例1: ExampleCount

func ExampleCount() {
    fmt.Println(bytes.Count([]byte("cheese"), []byte("e")))
    fmt.Println(bytes.Count([]byte("five"), []byte(""))) // before & after each rune
    // Output:
    // 3
    // 5
}

开发者ID:achanda,项目名称:go,代码行数:7,代码来源:example_test.go

示例2: solve

func solve(input io.Reader) {
    scanner := bufio.NewScanner(input)
    scanner.Scan()
    A := []byte(scanner.Text())
    scanner.Scan()
    B := []byte(scanner.Text())

    if bytes.Count(A, []byte("1")) != bytes.Count(B, []byte("1")) {
        fmt.Println("-1")
        return
    }

    swaps := 0
    for i := 0; i < len(A); i++ {
        if A[i] != B[i] {
            for j := i + 1; j < len(A); j++ {
                if A[j] != B[j] && B[i] != B[j] {
                    swaps++
                    B[i], B[j] = B[j], B[i]
                    break
                }
            }
        }
    }

    fmt.Println(swaps)
}

开发者ID:kdar,项目名称:challenges,代码行数:27,代码来源:xaero_and_a_binary_gift.go

示例3: init

func init() {
    Unix.DecodeLine = func(p []byte) (depth int, name []byte, err error) {
        var n int
        // TODO(rjeczalik): Count up to first non-box character.
        depth = (bytes.Count(p, boxSpace) + bytes.Count(p, boxHardSpace) +
            bytes.Count(p, boxVertical)) / 4
        if n = bytes.LastIndex(p, boxHorizontal); n == -1 {
            err = errors.New("invalid syntax: " + string(p))
            return
        }
        name = p[n:]
        if n = bytes.Index(name, boxSpace); n == -1 {
            err = errors.New("invalid syntax: " + string(p))
            return
        }
        name = name[n+1:]
        return
    }
    Unix.EncodeState = func(st EncodingState) []byte {
        return box[st]
    }
    Tab.DecodeLine = func(p []byte) (depth int, name []byte, err error) {
        depth = bytes.Count(p, []byte{'\t'})
        name = p[depth:]
        return
    }
    Tab.EncodeState = func(st EncodingState) []byte {
        return []byte{'\t'}
    }
}

开发者ID:rjeczalik,项目名称:fs,代码行数:30,代码来源:tree.go

示例4: TestList

func TestList(t *testing.T) {
    // use buffer instead of Stdout so we can inspect the results
    var b bytes.Buffer
    setOutput(&b)
    defer revertOutput()

    // use custom name so test won't interfere with a real _gen.go
    setCustomName("_gen_test.go")
    defer revertCustomName()

    // remove existing files, start fresh
    os.Remove(customName)

    // standard
    if err := runMain([]string{"gen", "list"}); err != nil {
        t.Error(err)
    }

    // one line for title, 2 standard typewriters
    if lines := bytes.Count(b.Bytes(), []byte("\n")); lines != 3 {
        t.Errorf("standard list should output 3 lines, got %v", lines)
    }

    // clear out the output buffer
    b.Reset()

    // create a custom typewriter import file
    w, err := os.Create(customName)

    if err != nil {
        t.Error(err)
    }

    defer os.Remove(customName)

    p := pkg{
        Name: "main",
        Imports: []string{
            // non-standard typewriter
            `_ "github.com/clipperhouse/gen/typewriters/foowriter"`,
            `_ "github.com/clipperhouse/gen/typewriters/genwriter"`,
            `_ "github.com/clipperhouse/gen/typewriters/container"`,
        },
    }

    if err := tmpl.Execute(w, p); err != nil {
        t.Error(err)
    }

    // custom file now exists
    if err := runMain([]string{"gen", "list"}); err != nil {
        t.Error(err)
    }

    // one line for title, 3 custom typewriters
    if lines := bytes.Count(b.Bytes(), []byte("\n")); lines != 4 {
        t.Errorf("standard list should output 4 lines, got %v", lines)
    }
}

开发者ID:ngaut,项目名称:gen,代码行数:59,代码来源:list_test.go

示例5: slicecount

func slicecount() {
    s := []byte("banana")
    sep1 := []byte("ban")
    sep2 := []byte("na")
    sep3 := []byte("a")

    fmt.Println(bytes.Count(s, sep1))
    fmt.Println(bytes.Count(s, sep2))
    fmt.Println(bytes.Count(s, sep3))

}

开发者ID:qianguozheng,项目名称:datastructure,代码行数:11,代码来源:parentheses.go

示例6: Check

func Check(path string) {
    File, err := os.Open(path)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer File.Close()
    buf := bufio.NewReader(File)
    var num int = 1
    var errornum int = 0
    s := []byte("{{")
    e := []byte("}}")
    for {
        line, _, err := buf.ReadLine()
        if err != nil {
            if err.Error() == "EOF" {
                break
            }
            return
        }
        if bytes.Count(line, s) != bytes.Count(line, e) {
            fmt.Printf("Line%d: %s\n", num, string(line))
            errornum++
            continue
        }
        if bytes.Count(line, []byte("{{.}}")) != 0 {
            fmt.Printf("Line%d: %s\n", num, string(line))
            errornum++
            continue
        }

        for i := 0; i < bytes.Count(line, s); i++ {
            first := bytes.Index(line, s)
            last := bytes.Index(line, e)
            if first == -1 || last == -1 {
                continue
            }
            if bytes.Index(line[first:last], []byte("{{.")) != 0 {
                fmt.Printf("Error Line %d: %s\n", num, string(line))
                errornum++
                break
            }
            line = line[last:]
        }
    }
    if errornum != 0 {
        fmt.Printf("Error num %d From %s\n", errornum, path)
        return
    }
    return
}

开发者ID:czxichen,项目名称:Goprograme,代码行数:51,代码来源:checkconfig.go

示例7: validate

func (d *datagram) validate() (err error) {
    switch {
    case d.offset < 2:
        err = errors.New("Datagram has no opcode")
    case d.opcode() > 6:
        err = errors.New("Invalid opcode")
    default:
        switch d.opcode() {
        case opCodeRRQ, opCodeWRQ:
            switch {
            case len(d.filename()) < 1:
                err = errors.New("No filename provided")
            case d.buf[d.offset-1] != 0x0: // End with NULL
                err = fmt.Errorf("Corrupt %v datagram", d.opcode())
            case bytes.Count(d.buf[2:d.offset], []byte{0x0})%2 != 0: // Number of NULL chars is not even
                err = fmt.Errorf("Corrupt %v datagram", d.opcode())
            default:
                switch d.mode() {
                case ModeNetASCII, ModeOctet:
                    break
                case modeMail:
                    err = errors.New("MAIL transfer mode is unsupported")
                default:
                    err = errors.New("Invalid transfer mode")
                }
            }
        case opCodeACK, opCodeDATA:
            if d.offset < 4 {
                err = errors.New("Corrupt block number")
            }
        case opCodeERROR:
            switch {
            case d.offset < 5:
                err = errors.New("Corrupt ERROR datagram")
            case d.buf[d.offset-1] != 0x0:
                err = errors.New("Corrupt ERROR datagram")
            case bytes.Count(d.buf[4:d.offset], []byte{0x0}) > 1:
                err = errors.New("Corrupt ERROR datagram")
            }
        case opCodeOACK:
            switch {
            case d.buf[d.offset-1] != 0x0:
                err = errors.New("Corrupt OACK datagram")
            case bytes.Count(d.buf[2:d.offset], []byte{0x0})%2 != 0: // Number of NULL chars is not even
                err = errors.New("Corrupt OACK datagram")
            }
        }
    }
    return
}

开发者ID:u-root,项目名称:u-root,代码行数:50,代码来源:datagram.go

示例8: numTCP

func numTCP() (ntcp, nopen, nclose int, err error) {
    lsof, err := exec.Command("lsof", "-n", "-p", strconv.Itoa(os.Getpid())).Output()
    if err != nil {
        return 0, 0, 0, err
    }
    ntcp += bytes.Count(lsof, []byte("TCP"))
    for _, state := range []string{"LISTEN", "SYN_SENT", "SYN_RECEIVED", "ESTABLISHED"} {
        nopen += bytes.Count(lsof, []byte(state))
    }
    for _, state := range []string{"CLOSED", "CLOSE_WAIT", "LAST_ACK", "FIN_WAIT_1", "FIN_WAIT_2", "CLOSING", "TIME_WAIT"} {
        nclose += bytes.Count(lsof, []byte(state))
    }
    return ntcp, nopen, nclose, nil
}

开发者ID:ds2dev,项目名称:gcc,代码行数:14,代码来源:dial_test.go

示例9: shortText

func shortText(t []byte) []byte {
    if t == nil {
        return nil
    }

    // Cut signature.
    i := bytes.LastIndex(t, sigDash)
    j := bytes.LastIndex(t, quote)
    if i > j && bytes.Count(t[i+1:], nl) <= 10 {
        t = t[:i+1]
    }

    // Cut trailing quoted text.
    for {
        rest, last := lastLine(t)
        trim := bytes.TrimSpace(last)
        if len(rest) < len(t) && (len(trim) == 0 || trim[0] == '>') {
            t = rest
            continue
        }
        break
    }

    // Cut 'On foo.*wrote:' line.
    rest, last := lastLine(t)
    if onwrote.Match(last) {
        t = rest
    }

    // Cut trailing blank lines.
    for {
        rest, last := lastLine(t)
        trim := bytes.TrimSpace(last)
        if len(rest) < len(t) && len(trim) == 0 {
            t = rest
            continue
        }
        break
    }

    // Cut signature again.
    i = bytes.LastIndex(t, sigDash)
    j = bytes.LastIndex(t, quote)
    if i > j && bytes.Count(t[i+1:], nl) <= 10 {
        t = t[:i+1]
    }

    return t
}

开发者ID:ReinhardHsu,项目名称:platform,代码行数:49,代码来源:mail.go

示例10: Write

func Write(ch chan []byte, k, v string) error {
    data := []byte(k + "=" + v + "\n")
    if bytes.Count(data, []byte("=")) > 1 || bytes.Count(data, []byte("=")) > 1 {
        return errors.New("Cannot have '=' in stream key or value")
    }
    if bytes.Count(data, []byte("\n")) > 1 || bytes.Count(data, []byte("\n")) > 1 {
        return errors.New("Cannot have newline in stream key or value")
    }
    select {
    case ch <- data:
    default:
        return ErrOverflow
    }
    return nil
}

开发者ID:funkygao,项目名称:govtil,代码行数:15,代码来源:streamz.go

示例11: loadConfig

func loadConfig() *Config {
    var config *Config
    file, err := ioutil.ReadFile("mipples.json")
    if err != nil {
        panic(err)
    }

    if err := json.Unmarshal(file, &config); err != nil {
        syntaxErr, ok := err.(*json.SyntaxError)
        if !ok {
            log.Fatalf("Cannot read config: %s", err)
        }

        // We have a syntax error. Extract out the line number and friends.
        // https://groups.google.com/forum/#!topic/golang-nuts/fizimmXtVfc
        newline := []byte{'\x0a'}

        // Calculate the start/end position of the line where the error is
        start := bytes.LastIndex(file[:syntaxErr.Offset], newline) + 1
        end := len(file)
        if idx := bytes.Index(file[start:], newline); idx >= 0 {
            end = start + idx
        }

        // Count the line number we're on plus the offset in the line
        line := bytes.Count(file[:start], newline) + 1
        pos := int(syntaxErr.Offset) - start - 1

        log.Fatalf("Cannot read config. Error in line %d, char %d: %s\n%s",
            line, pos, syntaxErr, file[start:end])
    }

    return config
}

开发者ID:nemith,项目名称:mipples,代码行数:34,代码来源:config.go

示例12: TestMessagePlainPGPSingleKey

func TestMessagePlainPGPSingleKey(t *testing.T) {

    const caddyFile = `mailout {
                to              [email protected]
                cc              "[email protected]"
                subject         "Encrypted contact 🔑"
                body            testdata/mail_plainTextMessage.txt
                [email protected]       testdata/B06469EE_nopw.pub.asc
            }`

    buf := new(bytes.Buffer)
    srv := testMessageServer(t, caddyFile, buf, 2)
    defer srv.Close()

    data := make(url.Values)
    data.Set("firstname", "Ken")
    data.Set("lastname", "Thompson")
    data.Set("email", "[email protected]")
    data.Set("name", "Ken Thompson")

    testDoPost(t, srv.URL, data)

    assert.Len(t, buf.String(), 2710) // whenever you change the template, change also here
    assert.Contains(t, buf.String(), "Subject: =?UTF-8?q?Encrypted_contact_=F0=9F=94=91?=")
    assert.Contains(t, buf.String(), "Cc: [email protected]")
    assert.Exactly(t, 1, bytes.Count(buf.Bytes(), maillog.MultiMessageSeparator))
    assert.Contains(t, buf.String(), `This shows the content of a text template.`)
    //t.Log(buf.String())
}

开发者ID:SchumacherFM,项目名称:mailout,代码行数:29,代码来源:message_test.go

示例13: processDefine

func (p *parser) processDefine(line []byte) {
    line = concatline(line)
    if glog.V(1) {
        glog.Infof("concatline:%q", line)
    }
    if !p.isEndef(line) {
        if p.inDef != nil {
            p.inDef = append(p.inDef, '\n')
        }
        p.inDef = append(p.inDef, line...)
        if p.inDef == nil {
            p.inDef = []byte{}
        }
        return
    }
    glog.V(1).Infof("multilineAssign %q %q", p.defineVar, p.inDef)
    aast, err := newAssignAST(p, p.defineVar, p.inDef, "=")
    if err != nil {
        p.err = p.srcpos().errorf("assign error %q=%q: %v", p.defineVar, p.inDef, err)
        return
    }
    aast.srcpos = p.srcpos()
    aast.srcpos.lineno -= bytes.Count(p.inDef, []byte{'\n'})
    p.addStatement(aast)
    p.defineVar = nil
    p.inDef = nil
    return
}

开发者ID:kleopatra999,项目名称:kati,代码行数:28,代码来源:parser.go

示例14: parseCover

func parseCover(fn string) []*SourceFile {
    profs, err := parseProfiles(fn)
    if err != nil {
        log.Fatalf("Error parsing coverage: %v", err)
    }

    var rv []*SourceFile
    for _, prof := range profs {
        path, err := findFile(prof.FileName)
        if err != nil {
            log.Fatalf("Can't find %v", err)
        }
        fb, err := ioutil.ReadFile(path)
        if err != nil {
            log.Fatalf("Error reading %v: %v", path, err)
        }
        sf := &SourceFile{
            Name:     prof.FileName,
            Source:   string(fb),
            Coverage: make([]interface{}, 1+bytes.Count(fb, []byte{'\n'})),
        }

        for _, block := range prof.Blocks {
            for i := block.StartLine; i <= block.EndLine; i++ {
                sf.Coverage[i-1] = block.Count
            }
        }

        rv = append(rv, sf)
    }

    return rv
}

开发者ID:jmcvetta,项目名称:goveralls,代码行数:33,代码来源:gocover.go

示例15: TestTrie_compact

func TestTrie_compact(t *testing.T) {
    trie := NewTrie()

    trie.Insert(Prefix("a"), 0)
    trie.Insert(Prefix("ab"), 0)
    trie.Insert(Prefix("abc"), 0)
    trie.Insert(Prefix("abcd"), 0)
    trie.Insert(Prefix("abcde"), 0)
    trie.Insert(Prefix("abcdef"), 0)
    trie.Insert(Prefix("abcdefg"), 0)
    trie.Insert(Prefix("abcdefgi"), 0)
    trie.Insert(Prefix("abcdefgij"), 0)
    trie.Insert(Prefix("abcdefgijk"), 0)

    trie.Delete(Prefix("abcdef"))
    trie.Delete(Prefix("abcde"))
    trie.Delete(Prefix("abcdefg"))

    trie.Delete(Prefix("a"))
    trie.Delete(Prefix("abc"))
    trie.Delete(Prefix("ab"))

    trie.Visit(func(prefix Prefix, item Item) error {
        // 97 ~~ 'a',
        for ch := byte(97); ch <= 107; ch++ {
            if c := bytes.Count(prefix, []byte{ch}); c > 1 {
                t.Errorf("%q appeared in %q %v times", ch, prefix, c)
            }
        }
        return nil
    })
}

开发者ID:98pm,项目名称:docker,代码行数:32,代码来源:patricia_sparse_test.go

示例16: InitialValidationB

// InitialValidationB is like InitialValidation but for byte array inputs.
func InitialValidationB(metric_id []byte, version metricVersion) error {
    if version == Legacy {
        if bytes.Contains(metric_id, doubleDot) {
            return fmt.Errorf("metric '%s' has an empty node", metric_id)
        }
        return ValidateSensibleCharsB(metric_id)
    }
    if version == M20 {
        if bytes.Contains(metric_id, m20Is) {
            return fmt.Errorf("metric '%s' has both = and _is_", metric_id)
        }
        if !bytes.HasPrefix(metric_id, m20UnitPre) && !bytes.Contains(metric_id, m20UnitMid) {
            return fmt.Errorf("metric '%s' has no unit tag", metric_id)
        }
        if !bytes.HasPrefix(metric_id, m20TTPre) && !bytes.Contains(metric_id, m20TTMid) {
            return fmt.Errorf("metric '%s' has no target_type tag", metric_id)
        }
    } else { //version == M20NoEquals
        if bytes.Contains(metric_id, m20NEIS) {
            return fmt.Errorf("metric '%s' has both = and _is_", metric_id)
        }
        if !bytes.HasPrefix(metric_id, m20NEUnitPre) && !bytes.Contains(metric_id, m20NEUnitMid) {
            return fmt.Errorf("metric '%s' has no unit tag", metric_id)
        }
        if !bytes.HasPrefix(metric_id, m20NETTPre) && !bytes.Contains(metric_id, m20NETTMid) {
            return fmt.Errorf("metric '%s' has no target_type tag", metric_id)
        }
    }
    if bytes.Count(metric_id, dot) < 2 {
        return fmt.Errorf("metric '%s': must have at least one tag_k/tag_v pair beyond unit and target_type", metric_id)
    }
    return nil
}

开发者ID:AnderEnder,项目名称:carbon-relay-ng,代码行数:34,代码来源:version.go

示例17: grep

func grep(re *Regexp, b []byte) []int {
    var m []int
    lineno := 1
    for {
        i := re.Match(b, true, true)
        if i < 0 {
            break
        }
        start := bytes.LastIndex(b[:i], nl) + 1
        end := i + 1
        if end > len(b) {
            end = len(b)
        }
        lineno += bytes.Count(b[:start], nl)
        m = append(m, lineno)
        if start < end && b[end-1] == '\n' {
            lineno++
        }
        b = b[end:]
        if len(b) == 0 {
            break
        }
    }
    return m
}

开发者ID:Debian,项目名称:dcs,代码行数:25,代码来源:regexp_test.go

示例18: acceptConn

func (gas *GameServer) acceptConn(c net.Conn) {
    fmt.Println("acceptConn")
    buf := make([]byte, common.BUF_SIZE)
    var data bytes.Buffer
    for {
        n, _ := c.Read(buf)
        if n == 0 {
            fmt.Println("close by peer")
            break
        }
        data.Write(buf[:n])

        cn := bytes.Count(data.Bytes(), []byte{common.DELIMITER})
        for ; cn > 0; cn-- {
            jn, err := data.ReadString(common.DELIMITER)
            fmt.Println(time.Now().String()[:19], jn)
            if err != nil {
                fmt.Println("err", err)
                continue
            }

            var unknow interface{}
            err = json.Unmarshal([]byte(jn), &unknow)
            if err != nil {
                fmt.Println("Unmarshal error")
                continue
            }

            switch unknow.(type) {
            case map[string]interface{}: //?
                gas.dispatchOp(unknow, c)
            }
        }
    }
}

开发者ID:lsaint,项目名称:casino,代码行数:35,代码来源:gameserver.go

示例19: formatPgErr

// need access to the original query contents in order to print it out properly,
// unfortunately.
func formatPgErr(contents *[]byte, pgerr *pq.Error) string {
    pos, _ := strconv.Atoi(pgerr.Position)
    lineNo := bytes.Count((*contents)[:pos], []byte("\n")) + 1
    columnNo := pos - bytes.LastIndex((*contents)[:pos], []byte("\n")) - 1

    return fmt.Sprint("PGERROR: line ", lineNo, " pos ", columnNo, ": ", pgerr.Message, ". ", pgerr.Detail)
}

开发者ID:magicalbanana,项目名称:pgmgr,代码行数:9,代码来源:pgmgr.go

示例20: TestTemplateBytes

//test if the TemplateBytes works
func TestTemplateBytes(t *testing.T) {
    template := NewTemplateBytes([]byte(""))
    content := template.Content()
    if bytes.Count(content, []byte("")) != 1 {
        t.Error("Cannot read the template")
    }
}

开发者ID:xarg,项目名称:taller,代码行数:8,代码来源:taller_test.go