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


Golang StringVector.Len方法代码示例

本文整理汇总了Golang中container/vector.StringVector.Len方法的典型用法代码示例。如果您正苦于以下问题:Golang StringVector.Len方法的具体用法?Golang StringVector.Len怎么用?Golang StringVector.Len使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在container/vector.StringVector的用法示例。


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

示例1: GenerateTestMain

// GenerateTestMain returns the source code for a test program that will run
// the specified test functions from the specified package.
func GenerateTestMain(packageName string, funcs *set.StringSet) string {
	var funcVec vector.StringVector
	for val := range funcs.Iter() {
		funcVec.Push(val)
	}

	result := ""
	result += "package main\n\n"
	result += "import \"testing\"\n"

	if funcVec.Len() > 0 {
		result += fmt.Sprintf("import \"./%s\"\n\n", packageName)
	}

	result += "var tests = []testing.Test {\n"
	for _, val := range funcVec.Data() {
		result += fmt.Sprintf("\ttesting.Test{\"%s\", %s.%s},\n", val, packageName, val)
	}

	result += "}\n\n"
	result += "func main() {\n"
	result += "\ttesting.Main(tests)\n"
	result += "}\n"

	return result
}
开发者ID:jacobsa,项目名称:igo,代码行数:28,代码来源:generate.go

示例2: Import

func (p *Pipeline) Import(client oauth2_client.OAuth2Client, ds DataStoreService, cs ContactsService, csSettings ContactsServiceSettings, dsocialUserId, meContactId string, allowAdd, allowDelete, allowUpdate bool) (err os.Error) {
	fmt.Printf("[PIPELINE]: Starting importing...\n")
	if !csSettings.AllowRetrieveContactInfo() || !cs.CanImportContactsOrGroups() {
		// do nothing
	} else {
		groupMappings := make(map[string]*list.List)
		contactChangesetIds := new(vector.StringVector)
		groupChangesetIds := new(vector.StringVector)
		if cs.CanRetrieveContacts() {
			err = p.importContacts(client, ds, cs, dsocialUserId, allowAdd, allowDelete, allowUpdate, groupMappings, contactChangesetIds)
		} else if cs.CanRetrieveConnections() {
			err = p.importConnections(client, ds, cs, dsocialUserId, allowAdd, allowDelete, allowUpdate, groupMappings, contactChangesetIds)
		}
		if err == nil && cs.CanRetrieveGroups() {
			err = p.importGroups(client, ds, cs, dsocialUserId, allowAdd, allowDelete, allowUpdate, groupMappings, groupChangesetIds)
		}
		if contactChangesetIds.Len() > 0 || groupChangesetIds.Len() > 0 {
			settings, _ := ds.RetrieveAllContactsServiceSettingsForUser(dsocialUserId)
			err = p.queueContactChangeSetsToApply(ds, cs, csSettings, settings, dsocialUserId, contactChangesetIds)
			if err == nil {
				err = p.queueGroupChangeSetsToApply(ds, cs, csSettings, settings, dsocialUserId, groupChangesetIds)
			}
		}
	}
	fmt.Printf("[PIPELINE]: Done importing.\n")
	return
}
开发者ID:pombredanne,项目名称:dsocial.go,代码行数:27,代码来源:pipeline.go

示例3: ExecutionModelSpec

func ExecutionModelSpec(c nanospec.Context) {

	c.Specify("Specs with children, but without siblings, are executed fully on one run", func() {

		c.Specify("Case: no children", func() {
			runSpecWithContext(DummySpecWithNoChildren, newInitialContext())
			c.Expect(testSpy).Equals("root")
		})
		c.Specify("Case: one child", func() {
			runSpecWithContext(DummySpecWithOneChild, newInitialContext())
			c.Expect(testSpy).Equals("root,a")
		})
		c.Specify("Case: nested children", func() {
			runSpecWithContext(DummySpecWithNestedChildren, newInitialContext())
			c.Expect(testSpy).Equals("root,a,aa")
		})
	})

	c.Specify("Specs with siblings are executed only one sibling at a time", func() {

		c.Specify("Case: on initial run, the 1st child is executed", func() {
			runSpecWithContext(DummySpecWithTwoChildren, newInitialContext())
			c.Expect(testSpy).Equals("root,a")
		})
		c.Specify("Case: explicitly execute the 1st child", func() {
			runSpecWithContext(DummySpecWithTwoChildren, newExplicitContext([]int{0}))
			c.Expect(testSpy).Equals("root,a")
		})
		c.Specify("Case: explicitly execute the 2nd child", func() {
			runSpecWithContext(DummySpecWithTwoChildren, newExplicitContext([]int{1}))
			c.Expect(testSpy).Equals("root,b")
		})
	})

	c.Specify("Specs with nested siblings: eventually all siblings are executed, one at a time, in isolation", func() {
		r := NewRunner()
		r.AddSpec(DummySpecWithMultipleNestedChildren)

		// Execute manually instead of calling Run(), in order to avoid running
		// the specs multi-threadedly, which would mess up the test spy.
		runs := new(vector.StringVector)
		for r.hasScheduledTasks() {
			resetTestSpy()
			r.executeNextScheduledTask()
			runs.Push(testSpy)
		}
		sort.Sort(runs)

		c.Expect(runs.Len()).Equals(5)
		c.Expect(runs.At(0)).Equals("root,a,aa")
		c.Expect(runs.At(1)).Equals("root,a,ab")
		c.Expect(runs.At(2)).Equals("root,b,ba")
		c.Expect(runs.At(3)).Equals("root,b,bb")
		c.Expect(runs.At(4)).Equals("root,b,bc")
	})
}
开发者ID:boggle,项目名称:gospec,代码行数:56,代码来源:execution_model_test.go

示例4: Matches

func (self *Regex) Matches(s string) []string {
	res := new(vector.StringVector)
	self.l.StartString(s)
	for !self.l.Eof() {
		if self.l.Next() == 0 {
			res.Push(self.l.String())
		}
	}
	return []string(*res.Slice(0, res.Len()))
}
开发者ID:darkgray1981,项目名称:bwl,代码行数:10,代码来源:regex.go

示例5: Replace

func (self *Regex) Replace(s string, f func(string) string) string {
	res := new(vector.StringVector)
	buf := bytes.Runes([]byte(s))
	last := 0
	self.l.StartString(s)
	for !self.l.Eof() {
		if self.l.Next() == 0 {
			res.Push(string(buf[last:self.l.Pos()]))
			res.Push(f(self.l.String()))
			last = self.l.Pos() + self.l.Len()
		}
	}
	res.Push(string(buf[last:]))
	return strings.Join([]string(*res.Slice(0, res.Len())), "")
}
开发者ID:darkgray1981,项目名称:bwl,代码行数:15,代码来源:regex.go

示例6: GetDotString

func (p *Trie) GetDotString() string {
	rsrc := rand.NewSource(140209)
	rgen := rand.New(rsrc)

	outStr := "digraph Trie {"
	vec := new(vector.StringVector)

	p.outputDot(vec, 0, -1, rgen)

	cnt := vec.Len()
	for i := 0; i < cnt; i++ {
		outStr = strings.Join([]string{outStr, vec.At(i)}, "\n")
	}

	return strings.Join([]string{outStr, "}"}, "\n")
}
开发者ID:alangenfeld,项目名称:cs639,代码行数:16,代码来源:trie.go

示例7: gtplist_commands

// List all commands, one by each line, sorted alphabetically
func gtplist_commands(obj *GTPObject) *GTPCommand {
	signature := []int{}
	f := func(object *GTPObject, params []interface{}) (result string, quit bool, err Error) {
		result = ""
		var cmdVector vector.StringVector
		for cmdName, _ := range obj.commands {
			cmdVector.Push(cmdName)
		}
		sort.SortStrings(sort.StringArray(cmdVector))
		result += cmdVector[0]
		for i := 1; i < cmdVector.Len(); i++ {
			result += "\n" + cmdVector.At(i)
		}
		return result, false, nil
	}
	return &GTPCommand{Signature: signature,
		Func: f,
	}
}
开发者ID:Sh4pe,项目名称:komoku,代码行数:20,代码来源:gtpcmd.go

示例8: goLoadAsciiArts

// loads ascii arts from data directory
func (self *AsciiArtGallery) goLoadAsciiArts() {
	self.loadedArts = false
	go func() {
		files := vector.StringVector{}
		entries, err := ioutil.ReadDir("data/ascii")
		if err != nil {
			panic("Cannot read files from data/ascii")
		}
		for _, f := range entries {
			if strings.HasSuffix(f.Name(), ".dat") {
				files.Push(path.Join("data/ascii", f.Name()))
			}
		}

		self.arts = make([]IAsciiArt, files.Len())
		self.artfiles = files
		self.loadedArtsChan <- true
	}()
}
开发者ID:gcatlin,项目名称:libtcod-go,代码行数:20,代码来源:asciiart.go

示例9: handleTick

func (exchange *Exchange) handleTick(t int64) {
	removeTheseUnreadyQueues := new(vector.StringVector)
	for toAddress, messageQueue := range exchange.messageQueues {
		for i := 0; i < messageQueue.Len(); i++ {
			msg := messageQueue.At(i).(Message)
			if msg.timeout < t {
				exchange.logf(LogLevelDebug, "> %v %v %v %v", len(msg.Body), msg.TimeoutSeconds, msg.ToAddress, msg.ReplyAddress)
				exchange.logf(LogLevelDebug, "  send timeout")
				messageQueue.Delete(i)
				i--
			}
		}
		if messageQueue.Len() == 0 {
			removeTheseUnreadyQueues.Push(toAddress)
		}
	}
	for i := 0; i < removeTheseUnreadyQueues.Len(); i++ {
		exchange.messageQueues[removeTheseUnreadyQueues.At(i)] = nil, false
	}

	removeTheseReadyStates := new(vector.StringVector)
	for onAddress, readyStateQueue := range exchange.readyStateQueues {
		for i := 0; i < readyStateQueue.Len(); i++ {
			readyState := readyStateQueue.At(i).(*readyState)
			if readyState.timeout < t {
				exchange.logf(LogLevelDebug, "* ready timeout %v", onAddress)
				if !readyState.timeoutReceived {
					readyState.messageChan <- Message{"", "", 0, "", 0}
					readyState.timeoutReceived = true
				}
				readyStateQueue.Delete(i)
				i--
			}
		}
		if readyStateQueue.Len() == 0 {
			removeTheseReadyStates.Push(onAddress)
		}
	}
	for i := 0; i < removeTheseReadyStates.Len(); i++ {
		exchange.readyStateQueues[removeTheseReadyStates.At(i)] = nil, false
	}
}
开发者ID:jmptrader,项目名称:msglite,代码行数:42,代码来源:core.go

示例10: queueGroupChangeSetsToApply

func (p *Pipeline) queueGroupChangeSetsToApply(ds DataStoreService, cs ContactsService, csSettings ContactsServiceSettings, settings []ContactsServiceSettings, dsocialUserId string, changesetIds *vector.StringVector) (err os.Error) {
	if changesetIds == nil || changesetIds.Len() == 0 || settings == nil || len(settings) == 0 {
		return
	}
	thisServiceName := cs.ServiceId()
	thisServiceId := csSettings.Id()
	ids := []string(*changesetIds)
	for _, setting := range settings {
		if setting.Id() == thisServiceId && thisServiceName == setting.ContactsServiceId() {
			// if we import from this service, don't export to it
			continue
		}
		if _, err2 := ds.AddGroupChangeSetsToApply(dsocialUserId, setting.Id(), setting.ContactsServiceId(), ids); err2 != nil {
			if err == nil {
				err = err2
			}
			break
		}
	}
	return
}
开发者ID:pombredanne,项目名称:dsocial.go,代码行数:21,代码来源:pipeline.go

示例11: TestMultiFind

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

	// these are part of the matches for the word 'hyphenation'
	trie.AddString(`hyph`)
	trie.AddString(`hen`)
	trie.AddString(`hena`)
	trie.AddString(`henat`)

	expected := new(vector.StringVector)
	expected.Push(`hyph`)
	found := trie.AllSubstrings(`hyphenation`)
	if found.Len() != expected.Len() {
		t.Errorf("expected %v but found %v", *expected, *found)
	}

	expected.Cut(0, expected.Len())
	expected.Push(`hen`)
	expected.Push(`hena`)
	expected.Push(`henat`)
	found = trie.AllSubstrings(`henation`)
	if found.Len() != expected.Len() {
		t.Errorf("expected %v but found %v", *expected, *found)
	}
}
开发者ID:AlanQuatermain,项目名称:go-trie,代码行数:25,代码来源:trie_test.go

示例12: gtpkomoku_sourceforkn

// As gtpkomoku_sourcen, except that it makes replaces the board with a copy of it in each move. This is used to debug
// Board.Copy()
func gtpkomoku_sourceforkn(obj *GTPObject) *GTPCommand {
	signature := []int{GTPString, GTPInt}
	f := func(object *GTPObject, params []interface{}) (result string, quit bool, err Error) {
		filename, _ := params[0].(string)
		n := int(params[1].(uint))
		file, er := os.Open(filename, os.O_RDONLY, 0)
		if er != nil {
			return fmt.Sprintf("error: '%s'", err), false, NewIOError(er)
		}
		input := bufio.NewReader(file)
		var lines vector.StringVector
		line, er := input.ReadString('\n')
		lines.Push(line)
		for er != os.EOF {
			lines.Push(line)
			line, er = input.ReadString('\n')
		}
		length := lines.Len()
		line = ""
		for i := 0; i < length; i++ {
			line = lines.At(i)
			if length-i <= n {
				line = "#" + line
			}
			fmt.Printf(line)
			obj.ai.environment.Game.Board = obj.ai.environment.Game.Board.Copy()
			lineResult, lineQuit, _ := obj.ExecuteCommand(line)
			fmt.Printf(lineResult)
			if lineQuit {
				return "", true, nil
			}
		}
		fmt.Println("\nend komoku-sourceforkn")
		return "", false, nil
	}
	return &GTPCommand{Signature: signature,
		Func: f,
	}
}
开发者ID:Sh4pe,项目名称:komoku,代码行数:41,代码来源:gtpcmd.go

示例13: ParsePhoneNumber

func ParsePhoneNumber(s string, number *PhoneNumber) {
	slen := len(s)
	if slen == 0 {
		return
	}
	number.FormattedNumber = s
	sv := new(vector.StringVector)
	start := 0
	for i := 0; i < slen; i++ {
		b := s[i]
		switch b {
		case '-', ' ', '.', ')', '_':
			if start < i {
				addIfNonSpaces(sv, s[start:i])
			}
			start = i + 1
		case '(':
			for j := i + 1; j < slen; j++ {
				if s[j] == ')' {
					if start < i {
						addIfNonSpaces(sv, s[start:i])
					}
					addIfNonSpaces(sv, s[i+1:j])
					i = j
					start = j + 1
					break
				}
			}
		case 'x', 'X':
			if start < i {
				lastChar := s[i-1]
				if lastChar == 'e' || lastChar == 'E' {
					continue
				}
				p := strings.TrimSpace(s[start:i])
				if p != "" {
					sv.Push(p)
				}
			}
			number.ExtensionNumber = strings.TrimSpace(s[i+1:])
			start = slen
			i = slen
			break
		case 't', 'T':
			l := i - start
			if l > 2 && strings.ToLower(s[i-2:i+1]) == "ext" {
				if start < i-2 {
					p := strings.TrimSpace(s[start : i-2])
					if p != "" {
						sv.Push(p)
					}
				}
			}
			number.ExtensionNumber = strings.TrimSpace(s[i+1:])
			start = slen
			i = slen
			break
		}
	}
	if start < slen {
		p := strings.TrimSpace(s[start:])
		if p != "" {
			sv.Push(p)
		}
	}
	parts := *sv
	if sv.Len() == 0 {
		return
	}
	at := 0
	l := len(parts)
	if parts[0][0] == '+' {
		// preferred format is +<country code>-<area code>-<local code>
		number.CountryCode = parts[0][1:]
		at++
	} else if len(parts[0]) < 3 {
		// make an assumption that this is a country code
		number.CountryCode = parts[0]
		at++
	}
	if l > at+1 {
		number.AreaCode = parts[at]
		at++
	}
	if l > at {
		number.LocalPhoneNumber = strings.Join(parts[at:], "-")
	}
}
开发者ID:pombredanne,项目名称:dsocial.go,代码行数:88,代码来源:util.go

示例14: applyGroupChangeSets

func (p *Pipeline) applyGroupChangeSets(client oauth2_client.OAuth2Client, ds DataStoreService, cs ContactsService, csSettings ContactsServiceSettings, dsocialUserId, meContactId string) (err os.Error) {
	externalServiceId := csSettings.Id()
	externalServiceName := csSettings.ContactsServiceId()
	externalUserId := csSettings.ExternalUserId()
	applyable, changesets, err := ds.RetrieveGroupChangeSetsToApply(dsocialUserId, externalServiceId, externalServiceName)
	if err != nil {
		return
	}
	fmt.Printf("[PIPELINE]: Will be applying up to %d changesets from %d applyable\n", len(changesets), len(applyable))
	changesetIdsNotApplyable := new(vector.StringVector)
	changesetIdsApplied := new(vector.StringVector)
	for _, toApply := range applyable {
		if err != nil {
			break
		}
		for _, changesetId := range toApply.ChangeSetIds {
			if err != nil {
				break
			}
			changeset, _ := changesets[changesetId]
			if changeset != nil {
				isMe := changeset.RecordId == meContactId
				canCreate, canUpdate, canDelete := cs.CanCreateGroup(isMe), cs.CanUpdateGroup(isMe), cs.CanDeleteGroup(isMe)
				if !canCreate && !canUpdate && !canDelete {
					changesetIdsNotApplyable.Push(changeset.Id)
					continue
				}
				fmt.Printf("[PIPELINE]: handling changeset id %s\n", changeset.Id)
				isCreate, isUpdate, isDelete := false, false, false
				if len(changeset.Changes) > 1 {
					isUpdate = true
				} else if len(changeset.Changes) == 1 {
					switch changeset.Changes[0].ChangeType {
					case dm.CHANGE_TYPE_CREATE:
						isCreate = true
					case dm.CHANGE_TYPE_ADD:
						if changeset.Changes[0].Path == nil || len(changeset.Changes[0].Path) == 0 {
							isCreate = true
						} else {
							isUpdate = true
						}
					case dm.CHANGE_TYPE_UPDATE:
						isUpdate = true
					case dm.CHANGE_TYPE_DELETE:
						if changeset.Changes[0].Path == nil || len(changeset.Changes[0].Path) == 0 {
							isDelete = true
						} else {
							isUpdate = true
						}
					}
				}
				if !(isCreate && canCreate) && !(isUpdate && canUpdate) && !(isDelete && canDelete) {
					changesetIdsNotApplyable.Push(changeset.Id)
					continue
				}
				dsocialGroupId := changeset.RecordId
				if isDelete {
					err = p.handleDeleteGroup(client, ds, cs, dsocialUserId, externalServiceId, externalUserId, dsocialGroupId)
				} else if isCreate {
					err = p.handleCreateGroup(client, ds, cs, dsocialUserId, dsocialGroupId)
				} else {
					// must be update
					err = p.handleUpdateGroup(client, ds, cs, dsocialUserId, externalServiceId, externalUserId, dsocialGroupId, changeset)
				}
				changesetIdsApplied.Push(changeset.Id)
			}
		}
	}
	if err == nil {
		fmt.Printf("[PIPELINE]: Skipped applying %d changesets\n", changesetIdsNotApplyable.Len())
		err = p.markGroupChangeSetsNotApplyable(ds, dsocialUserId, externalServiceId, externalServiceName, []string(*changesetIdsNotApplyable))
		if err == nil {
			err = ds.RemoveContactChangeSetsToApply(dsocialUserId, externalServiceId, externalServiceName, []string(*changesetIdsApplied))
		}
	}
	fmt.Printf("[PIPELINE]: Done applying group changesets\n")
	return
}
开发者ID:pombredanne,项目名称:dsocial.go,代码行数:78,代码来源:pipeline.go

示例15: main

func main() {
	flag.Parse()

	if flag.NArg() != 2 {
		printUsageAndExit()
	}

	command := flag.Arg(0)
	if command != "build" && command != "test" {
		printUsageAndExit()
	}

	// Grab dependency and file information for every local package, starting
	// with the specified one. We consider a package local if it starts with "./".
	requiredFiles := make(map[string]*set.StringSet)
	packageDeps := make(map[string]*set.StringSet)

	specifiedPackage := flag.Arg(1)
	var remainingPackages vector.StringVector
	remainingPackages.Push(specifiedPackage)

	for remainingPackages.Len() > 0 {
		packageName := remainingPackages.Pop()

		// Have we already processed this directory?
		_, alreadyDone := packageDeps[packageName]
		if alreadyDone {
			continue
		}

		dir := "./" + packageName
		dirInfo := build.GetDirectoryInfo(dir)
		if dirInfo.PackageName == "" {
			fmt.Printf("Couldn't find .go files to build in directory: %s\n", dir)
			os.Exit(1)
		}

		// Stash information about this package, and add its local dependencies to
		// the queue.
		requiredFiles[packageName] = dirInfo.Files
		packageDeps[packageName] = dirInfo.Deps

		// If we're testing and this is the package under test, also add its test
		// files and dependencies.
		if packageName == specifiedPackage && command == "test" {
			requiredFiles[packageName].Union(dirInfo.TestFiles)
			packageDeps[packageName].Union(dirInfo.TestDeps)
		}

		for dep := range packageDeps[packageName].Iter() {
			remainingPackages.Push(dep)
		}
	}

	// Order the packages by their dependencies.
	totalOrder := deps.BuildTotalOrder(packageDeps)
	fmt.Println("Found these packages to compile:")
	for _, packageName := range totalOrder {
		fmt.Printf("  %s\n", packageName)
	}

	// Create a directory to hold outputs, deleting the old one first.
	os.RemoveAll("igo-out")
	os.Mkdir("igo-out", 0700)

	// Compile each of the packages in turn.
	for _, currentPackage := range totalOrder {
		fmt.Printf("\nCompiling package: %s\n", currentPackage)
		compileFiles(requiredFiles[currentPackage], currentPackage)
	}

	// If this is a binary, also link it.
	if build.GetDirectoryInfo(specifiedPackage).PackageName == "main" {
		linkBinary(specifiedPackage)
	}

	// If we're testing, create a test runner, build it, and run it.
	if command == "test" {
		const outputFile = "igo-out/test_runner.go"
		testFuncs := build.GetDirectoryInfo(specifiedPackage).TestFuncs
		code := test.GenerateTestMain(specifiedPackage, testFuncs)
		err := ioutil.WriteFile("igo-out/test_runner.go", strings.Bytes(code), 0600)
		if err != nil {
			panic(err)
		}

		var files set.StringSet
		files.Insert("igo-out/test_runner.go")
		compileFiles(&files, "test_runner")
		linkBinary("test_runner")

		if !executeCommand("igo-out/test_runner", []string{}, "") {
			os.Exit(1)
		}
	}
}
开发者ID:jacobsa,项目名称:igo,代码行数:96,代码来源:main.go


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