Example #1
0
// Send a closure log message internally
func (log *Logger) intLogc(level int, closure func() string) {
	// Create a vector long enough to not require resizing
	var logto vector.StringVector
	logto.Resize(0, len(log.filterLevels))

	// Determine if any logging will be done
	for filt := range log.filterLevels {
		if level >= log.filterLevels[filt] {
			logto.Push(filt)
		}
	}

	// Only log if a filter requires it
	if len(logto) > 0 {
		// Determine caller func
		pc, _, lineno, ok := runtime.Caller(2)
		src := ""
		if ok {
			src = fmt.Sprintf("%s:%d", runtime.FuncForPC(pc).Name(), lineno)
		}

		// Make the log record from the closure's return
		rec := newLogRecord(level, src, closure())

		// Dispatch the logs
		for _, filt := range logto {
			log.filterLogWriters[filt].LogWrite(rec)
		}
	}
}
Example #2
0
func signatureBase(httpMethod string, base_uri string, params map[string]string) string {
	var buf bytes.Buffer

	buf.WriteString(httpMethod)
	buf.WriteString("&")
	buf.WriteString(URLEscape(base_uri))
	buf.WriteString("&")

	var keys vector.StringVector
	for k, _ := range params {
		keys.Push(k)
	}

	sort.SortStrings(keys)
	for i, k := range keys {
		v := params[k]
		buf.WriteString(URLEscape(k))
		buf.WriteString("%3D")
		buf.WriteString(URLEscape(v))
		//don't include the dangling %26
		if i < len(params)-1 {
			buf.WriteString("%26")
		}
		i++
	}
	return buf.String()
}
Example #3
0
func parseParamsInUnquotedSubstring(s string, name2value map[string]string) (lastKeyword string) {
	var words vector.StringVector

	for {
		index := strings.IndexAny(s, "= \n\r\t")
		if index == -1 {
			break
		}

		word := s[:index]
		if word != "" {
			words.Push(word)
		}
		s = s[index+1:]
	}
	if len(s) > 0 {
		words.Push(s)
	}

	for i := 0; i < len(words)-1; i += 2 {
		name2value[words[i]] = words[i+1]
	}

	if len(words) > 0 && len(words)%2 == 1 {
		lastKeyword = words[len(words)-1]
	}

	return
}
Example #4
0
func (p *Pipeline) importConnections(client oauth2_client.OAuth2Client, ds DataStoreService, cs ContactsService, dsocialUserId string, allowAdd, allowDelete, allowUpdate bool, groupMappings map[string]*list.List, contactChangesetIds *vector.StringVector) (err os.Error) {
	checkGroupsInContacts := cs.ContactInfoIncludesGroups()
	var nextToken NextToken = "blah"
	for connections, useNextToken, err := cs.RetrieveConnections(client, ds, dsocialUserId, nil); (len(connections) > 0 && nextToken != nil) || err != nil; connections, useNextToken, err = cs.RetrieveConnections(client, ds, dsocialUserId, nextToken) {
		if err != nil {
			break
		}
		for _, connection := range connections {
			contact, err := cs.RetrieveContact(client, ds, dsocialUserId, connection.ExternalContactId)
			if err != nil {
				break
			}
			finalContact, changesetId, err := p.contactImport(cs, ds, dsocialUserId, contact, allowAdd, allowDelete, allowUpdate)
			if changesetId != "" {
				contactChangesetIds.Push(changesetId)
			}
			if checkGroupsInContacts && finalContact != nil && finalContact != nil && finalContact.GroupReferences != nil && len(finalContact.GroupReferences) > 0 {
				p.addContactToGroupMappings(groupMappings, finalContact)
			}
			if err != nil {
				break
			}
		}
		nextToken = useNextToken
		if err != nil {
			break
		}
	}
	return
}
Example #5
0
//loops through root and subfolders to locate files with
//extensions specified in settings file
func (this *Settings) iterFiles(f string, pages *vector.StringVector) (err os.Error) {
	file, err := os.OpenFile(f, os.O_RDONLY, 0666)
	if err != nil {
		println(err.String())
		return
	}
	stat, er := file.Stat()
	if er != nil {
		err = er
		return
	}
	if stat.IsDirectory() {
		fmt.Println("iterFiles55555")
		dirs, err := file.Readdir(-1)
		if err != nil {
			return
		}
		for _, d := range dirs {
			this.iterFiles(path.Join(file.Name(), d.Name), pages)
		}
	} else {
		if hasExt(file.Name(), this.Data["extensions"]) {
			err = generate(file.Name())
			fmt.Println("iterFiles_eekkkk")
			if err != nil {
				return
			}
			pages.Push(file.Name())
		}
		file.Close()
	}
	return
}
Example #6
0
// 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
}
Example #7
0
func (p *Trie) outputDot(vec *vector.StringVector, rune int, serial int64, rgen *rand.Rand) {
	this := make([]byte, 10)
	child := make([]byte, 10)

	utf8.EncodeRune(this, rune)

	thisChar := string(this[0])

	if serial == -1 {
		thisChar = "root"
	}

	for childRune, childNode := range p.children {
		utf8.EncodeRune(child, childRune)
		childSerial := rgen.Int63()
		childNodeStr := fmt.Sprintf("\"%s(%d)\"", string(child[0]), childSerial)
		var notation string

		if string(child[0]) == "/" {
			notation = fmt.Sprintf("[label=\"%s\" shape=box color=red]", string(child[0]))
		} else {
			notation = fmt.Sprintf("[label=\"%s\"]", string(child[0]))
		}
		vec.Push(fmt.Sprintf("\t%s %s\n\t\"%s(%d)\" -> \"%s(%d)\"", childNodeStr, notation, thisChar, serial, string(child[0]), childSerial))
		childNode.outputDot(vec, childRune, childSerial, rgen)
	}
}
// ReadDotLines reads a dot-encoding and returns a slice
// containing the decoded lines, with the final \r\n or \n elided from each.
//
// See the documentation for the DotReader method for details about dot-encoding.
func (r *Reader) ReadDotLines() ([]string, os.Error) {
	// We could use ReadDotBytes and then Split it,
	// but reading a line at a time avoids needing a
	// large contiguous block of memory and is simpler.
	var v vector.StringVector
	var err os.Error
	for {
		var line string
		line, err = r.ReadLine()
		if err != nil {
			if err == os.EOF {
				err = io.ErrUnexpectedEOF
			}
			break
		}

		// Dot by itself marks end; otherwise cut one dot.
		if len(line) > 0 && line[0] == '.' {
			if len(line) == 1 {
				break
			}
			line = line[1:]
		}
		v.Push(line)
	}
	return v, err
}
Example #9
0
// Send a log message manually
func (log *Logger) Log(level int, source, message string) {
	// Create a vector long enough to not require resizing
	var logto vector.StringVector
	logto.Resize(0, len(log.filterLevels))

	// Determine if any logging will be done
	for filt := range log.filterLevels {
		if level >= log.filterLevels[filt] {
			logto.Push(filt)
		}
	}

	// Only log if a filter requires it
	if len(logto) > 0 {
		// Make the log record
		rec := newLogRecord(level, source, message)

		// Dispatch the logs
		for _, filt := range logto {
			lw := log.filterLogWriters[filt]
			if lw.Good() {
				lw.LogWrite(rec)
			}
		}
	}
}
Example #10
0
// Reordering, compressing, optimization.
func prepare(ops []op) string {
	var cmds vector.StringVector
	for _, o := range ops {
		cmds.Push(o.cmd)
	}

	return strings.Join([]string(cmds), "")
}
Example #11
0
func BenchmarkMGet(b *testing.B) {
	client.Set("bmg", []byte("hi"))
	var vals vector.StringVector
	for i := 0; i < b.N; i++ {
		vals.Push("bmg")
	}
	client.Mget(vals...)
	client.Del("bmg")
}
Example #12
0
func getSorted(set *StringSet) []string {
	var sorted vector.StringVector
	for val := range set.Iter() {
		sorted.Push(val)
	}

	sort.SortStrings(sorted)
	return sorted.Data()
}
Example #13
0
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")
	})
}
Example #14
0
func removeEmptyStrings(arr []string) []string {
	sv := new(vector.StringVector)
	sv.Resize(0, len(arr))
	for _, s := range arr {
		if s != "" {
			sv.Push(s)
		}
	}
	return *sv
}
Example #15
0
File: regex.go Project: ypb/bwl
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 res.Data()
}
Example #16
0
func resultsJson(results chan string) []byte {
	var ids vector.StringVector
	for id := range results {
		ids.Push(id)
	}
	raw, _ := json.Marshal(map[string]interface{}{
		"results": ids,
	})
	return raw
}
Example #17
0
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()))
}
Example #18
0
// Naive utility url encode method.  Converts a string map into a query string
//
// Returns a string in the format "?param1=value1&param2=value2"
func UrlEncode(urlmap map[string]string) string {
	url := "?"
	var temp vector.StringVector
	var key, value string

	for key, value = range urlmap {
		temp.Push(key + "=" + value)
	}
	url += strings.Join(temp, "&")
	return url
}
Example #19
0
func filter(v *vector.StringVector, f func(string) bool) *vector.StringVector {

	r := new(vector.StringVector)

	for _, s := range *v {
		if f(s) {
			r.Push(s)
		}
	}

	return r
}
Example #20
0
func (connection *Connection) SearchAndFetch(query string) (*vector.StringVector, os.Error) {
	ids, err := connection.Search(query)
	if err != nil {
		return nil, err
	}

	var result vector.StringVector
	for _, id := range *ids {
		result.Push(connection.Fetch(id))
	}

	return &result, nil
}
Example #21
0
func expectContentsEqual(t *testing.T, set *set.StringSet, expected []string) {
	var contents vector.StringVector
	for val := range set.Iter() {
		contents.Push(val)
	}

	sort.SortStrings(contents)
	sort.SortStrings(expected)

	if !reflect.DeepEqual(contents.Data(), expected) {
		t.Errorf("Expected:%v\nGot: %v", expected, contents)
	}
}
Example #22
0
func (client *Client) Hmset(key string, mapping interface{}) os.Error {
	args := new(vector.StringVector)
	args.Push(key)
	err := containerToString(reflect.ValueOf(mapping), args)
	if err != nil {
		return err
	}
	_, err = client.sendCommand("HMSET", *args...)
	if err != nil {
		return err
	}
	return nil
}
Example #23
0
func (p *MatchRule) _ToString() string {
	svec := new(vector.StringVector)

	v := reflect.Indirect(reflect.NewValue(p)).(*reflect.StructValue)
	t := v.Type().(*reflect.StructType)
	for i := 0; i < v.NumField(); i++ {
		str, ok := v.Field(i).Interface().(string)
		if ok && "" != str {
			svec.Push(fmt.Sprintf("%s='%s'", strings.ToLower(t.Field(i).Name), str))
		}
	}

	return strings.Join(svec.Data(), ",")
}
Example #24
0
func containerToString(val reflect.Value, args *vector.StringVector) os.Error {
	switch v := val; v.Kind() {
	case reflect.Ptr:
		return containerToString(reflect.Indirect(v), args)
	case reflect.Interface:
		return containerToString(v.Elem(), args)
	case reflect.Map:
		if v.Type().Key().Kind() != reflect.String {
			return os.NewError("Unsupported type - map key must be a string")
		}
		for _, k := range v.MapKeys() {
			args.Push(k.String())
			s, err := valueToString(v.MapIndex(k))
			if err != nil {
				return err
			}
			args.Push(s)
		}
	case reflect.Struct:
		st := v.Type()
		for i := 0; i < st.NumField(); i++ {
			ft := st.FieldByIndex([]int{i})
			args.Push(ft.Name)
			s, err := valueToString(v.FieldByIndex([]int{i}))
			if err != nil {
				return err
			}
			args.Push(s)
		}
	}
	return nil
}
Example #25
0
func containerToString(val reflect.Value, args *vector.StringVector) os.Error {
	switch v := val.(type) {
	case *reflect.PtrValue:
		return containerToString(reflect.Indirect(v), args)
	case *reflect.InterfaceValue:
		return containerToString(v.Elem(), args)
	case *reflect.MapValue:
		if _, ok := v.Type().(*reflect.MapType).Key().(*reflect.StringType); !ok {
			return os.NewError("Unsupported type - map key must be a string")
		}
		for _, k := range v.Keys() {
			args.Push(k.(*reflect.StringValue).Get())
			s, err := valueToString(v.Elem(k))
			if err != nil {
				return err
			}
			args.Push(s)
		}
	case *reflect.StructValue:
		st := v.Type().(*reflect.StructType)
		for i := 0; i < st.NumField(); i++ {
			ft := st.FieldByIndex([]int{i})
			args.Push(ft.Name)
			s, err := valueToString(v.FieldByIndex([]int{i}))
			if err != nil {
				return err
			}
			args.Push(s)
		}
	}
	return nil
}
Example #26
0
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)
	}
}
Example #27
0
// Fields returns the fields in s.
// Fields are space separated unquoted words
// or quoted with single or double quote.
func fields(s string) ([]string, os.Error) {
	var v vector.StringVector
	i := 0
	for {
		for i < len(s) && (s[i] == ' ' || s[i] == '\t') {
			i++
		}
		if i >= len(s) {
			break
		}
		if s[i] == '"' || s[i] == '\'' {
			q := s[i]
			// quoted string
			var j int
			for j = i + 1; ; j++ {
				if j >= len(s) {
					return nil, textproto.ProtocolError("malformed quoted string")
				}
				if s[j] == '\\' {
					j++
					continue
				}
				if s[j] == q {
					j++
					break
				}
			}
			v.Push(unquote(s[i+1 : j-1]))
			i = j
		} else {
			// atom
			var j int
			for j = i; j < len(s); j++ {
				if s[j] == ' ' || s[j] == '\t' || s[j] == '\\' || s[j] == '"' || s[j] == '\'' {
					break
				}
			}
			v.Push(s[i:j])
			i = j
		}
		if i < len(s) {
			c := s[i]
			if c != ' ' && c != '\t' {
				return nil, textproto.ProtocolError("quotes not on word boundaries")
			}
		}
	}
	return v, nil
}
Example #28
0
// Expand a list of files and directories
func ExpandFiles(files []string) []string {
	flatFiles := new(vector.StringVector)
	for _, filename := range files {
		info, err := os.Stat(filename)
		if err != nil {
			continue
		}
		if info.IsDirectory() {
			flatFiles.AppendVector(listFiles(filename))
		} else {
			flatFiles.Push(filename)
		}
	}
	return *flatFiles
}
Example #29
0
func (ctxt *context) checkCyclic(c *command, path *vector.StringVector) {
	fmt.Printf("checkCyclic %s\n", c.name)
	if c.visit {
		ctxt.fail("cyclic dependency at %s, path %v", c.name, path)
	}
	c.visit = true
	path.Push(c.name)
	for _, e := range c.conns {
		if e.gender == Female {
			ctxt.checkCyclic(e.male.cmd, path)
		}
	}
	path.Pop()
	c.visit = false
}
Example #30
0
func (client *Client) Keys(pattern string) ([]string, os.Error) {
	cmd := fmt.Sprintf("KEYS %s\r\n", pattern)
	res, err := client.sendCommand(cmd)

	if err != nil {
		return nil, err
	}

	keys := bytes.Fields(res.([]byte))
	var ret vector.StringVector
	for _, k := range keys {
		ret.Push(string(k))
	}
	return ret, nil
}