Beispiel #1
1
func (h *ZJUJudger) Login(_ UserInterface) error {

	h.client.Get("http://acm.zju.edu.cn/onlinejudge/login.do")

	uv := url.Values{}
	uv.Add("handle", h.username)
	uv.Add("password", h.userpass)

	req, err := http.NewRequest("POST", "http://acm.zju.edu.cn/onlinejudge/login.do", strings.NewReader(uv.Encode()))
	if err != nil {
		return BadInternet
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	resp, err := h.client.Do(req)
	if err != nil {
		log.Println("err", err)
		return BadInternet
	}
	defer resp.Body.Close()

	b, _ := ioutil.ReadAll(resp.Body)
	html := string(b)

	if strings.Index(html, "Handle or password is invalid.") >= 0 ||
		strings.Index(html, "Handle is required.") >= 0 ||
		strings.Index(html, "Password is required.") >= 0 {
		return LoginFailed
	}

	return nil
}
Beispiel #2
1
func RenderSpecialLink(rawBytes []byte, urlPrefix string) []byte {
	ms := MentionPattern.FindAll(rawBytes, -1)
	for _, m := range ms {
		rawBytes = bytes.Replace(rawBytes, m,
			[]byte(fmt.Sprintf(`<a href="/user/%s">%s</a>`, m[1:], m)), -1)
	}
	ms = commitPattern.FindAll(rawBytes, -1)
	for _, m := range ms {
		m = bytes.TrimSpace(m)
		i := strings.Index(string(m), "commit/")
		j := strings.Index(string(m), "#")
		if j == -1 {
			j = len(m)
		}
		rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
			` <code><a href="%s">%s</a></code>`, m, ShortSha(string(m[i+7:j])))), -1)
	}
	ms = issueFullPattern.FindAll(rawBytes, -1)
	for _, m := range ms {
		m = bytes.TrimSpace(m)
		i := strings.Index(string(m), "issues/")
		j := strings.Index(string(m), "#")
		if j == -1 {
			j = len(m)
		}
		rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
			` <a href="%s">#%s</a>`, m, ShortSha(string(m[i+7:j])))), -1)
	}
	ms = issueIndexPattern.FindAll(rawBytes, -1)
	for _, m := range ms {
		rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
			`<a href="%s/issues/%s">%s</a>`, urlPrefix, m[1:], m)), -1)
	}
	return rawBytes
}
Beispiel #3
0
// substituteParams substitute all params inside double chevron to the correct value
// param value will be obtained from dicts map
func substituteParams(toReplace, words string, dicts map[string]interface{}) string {
	// non empty scalar node remain unchanged
	// except it has double chevron bracket
	if toReplace != "" && (strings.Index(toReplace, "<<") < 0 && strings.Index(toReplace, ">>") < 0) {
		return toReplace
	}
	if words == "" {
		return toReplace
	}

	removeParamBracket := func(param string) string {
		param = strings.TrimSpace(param)
		return param[2 : len(param)-2]
	}

	// search params
	params := dcRe.FindAllString(words, -1)

	// substitute the params
	for _, p := range params {
		pVal := getParamValue(removeParamBracket(p), dicts)
		words = strings.Replace(words, p, pVal, -1)
	}
	return words
}
Beispiel #4
0
func (this *SrcHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	tmaster := time.Now()
	switch r.Method { // Likely faster not to use a map[string]func.
	case "GET":
		if strings.Index(r.URL.Path, common.SrcsPath) != 0 {
			handlerutils.HttpError(w, "Bad path: "+r.URL.Path, http.StatusBadRequest)
			return
		}
		this.getHandler(w, r)
	case "POST":
		if strings.Index(r.URL.Path, common.SrcPath) != 0 {
			handlerutils.HttpError(w, "Bad path: "+r.URL.Path, http.StatusBadRequest)
			return
		}
		src := r.URL.Path[len(common.SrcPath):]
		this.postHandler(w, r, src)
	case "PUT":
		if strings.Index(r.URL.Path, common.SrcPath) != 0 {
			handlerutils.HttpError(w, "Bad path: "+r.URL.Path, http.StatusBadRequest)
			return
		}
		src := r.URL.Path[len(common.SrcPath):]
		this.putHandler(w, r, src)
	default:
		handlerutils.HttpError(w, "Bad method: "+r.Method, http.StatusBadRequest)
		return
	}

	glog.V(2).Infof("PERF: total service time: %v\n", time.Now().Sub(tmaster))
}
Beispiel #5
0
func bzrResolveRepo(vcsBzr *vcsCmd, rootDir, remoteRepo string) (realRepo string, err error) {
	outb, err := vcsBzr.runOutput(rootDir, "info "+remoteRepo)
	if err != nil {
		return "", err
	}
	out := string(outb)

	// Expect:
	// ...
	//   (branch root|repository branch): <URL>
	// ...

	found := false
	for _, prefix := range []string{"\n  branch root: ", "\n  repository branch: "} {
		i := strings.Index(out, prefix)
		if i >= 0 {
			out = out[i+len(prefix):]
			found = true
			break
		}
	}
	if !found {
		return "", fmt.Errorf("unable to parse output of bzr info")
	}

	i := strings.Index(out, "\n")
	if i < 0 {
		return "", fmt.Errorf("unable to parse output of bzr info")
	}
	out = out[:i]
	return strings.TrimSpace(string(out)), nil
}
Beispiel #6
0
func ReadSNMP(path string) (*Snmp, error) {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}

	lines := strings.Split(string(data), "\n")

	// Maps a netstat metric to its value (i.e. SyncookiesSent --> 0)
	statMap := make(map[string]string)

	// patterns
	// TcpExt: SyncookiesSent SyncookiesRecv SyncookiesFailed... <-- header
	// TcpExt: 0 0 1764... <-- values
	for i := 1; i < len(lines); i = i + 2 {
		headers := strings.Fields(lines[i-1][strings.Index(lines[i-1], ":")+1:])
		values := strings.Fields(lines[i][strings.Index(lines[i], ":")+1:])
		for j, header := range headers {
			statMap[header] = values[j]
		}
	}

	out := Snmp{}
	elem := reflect.ValueOf(&out.TCP).Elem()
	typeOfElem := elem.Type()

	for i := 0; i < elem.NumField(); i++ {
		if val, ok := statMap[typeOfElem.Field(i).Name]; ok {
			parsedVal, _ := strconv.ParseUint(val, 10, 64)
			elem.Field(i).SetUint(parsedVal)
		}
	}

	return &out, nil
}
func fileWriter(t *testing.T, file *os.File, logs []string) {
	filename := file.Name()
	time.Sleep(1 * time.Second) // wait for start Tail...

	for _, line := range logs {
		if strings.Index(line, RotateMarker) != -1 {
			log.Println("fileWriter: rename file => file.old")
			os.Rename(filename, filename+".old")
			file.Close()
			file, _ = os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0644)
			log.Println("fileWriter: re-opened file")
		} else if strings.Index(line, TruncateMarker) != -1 {
			time.Sleep(1 * time.Second)
			log.Println("fileWriter: truncate(file, 0)")
			os.Truncate(filename, 0)
			file.Seek(int64(0), os.SEEK_SET)
		}
		_, err := file.WriteString(line)
		log.Print("fileWriter: wrote ", line)
		if err != nil {
			log.Println("write failed", err)
		}
		time.Sleep(1 * time.Millisecond)
	}
	file.Close()
}
Beispiel #8
0
//NewSheet marshal the reader's content, the sst can be nil
//using setSharedStringTable set is later
func NewSheet(r io.Reader, sst *sharedStringTable) (*Sheet, error) {

	data, err := ioutil.ReadAll(r)
	content := string(data)
	index1 := strings.Index(content, `<sheetData>`)
	index2 := strings.Index(content, `</sheetData>`)
	if index1 == -1 {
		return nil, errors.New(fmt.Sprintf("Can't find the sheetData tag, %s", content))
	}
	if index2 == -1 {
		return nil, errors.New(fmt.Sprintf("Can't find the </sheetData> %s", content))
	}
	head := content[0:index1]
	tail := content[index2+len(`</sheetData>`):]
	sheetData := content[index1 : index2+len(`</sheetData>`)]
	if err != nil {
		return nil, err
	}
	sheet := &Sheet{head: head, tail: tail, sst: sst}
	err = xml.Unmarshal([]byte(sheetData), sheet)
	if err != nil {
		return nil, err
	}
	return sheet, nil
}
Beispiel #9
0
func cleanGitignore(input string) (output string, err error) {
	if len(input) == 0 {
		return input, nil
	}

	if strings.Contains(input, delimiterStart) {
		if strings.Count(input, delimiterStart) > 1 {
			return input, errors.New("multiple instances of start delimiter")
		}
		if strings.Contains(input, delimiterEnd) {
			if strings.Count(input, delimiterEnd) > 1 {
				return input, errors.New("multiple instances of closing delimiter")
			}
			startPos := strings.Index(input, delimiterStart)
			endPos := strings.Index(input, delimiterEnd) + len(delimiterEnd)

			if startPos-2 >= 0 && input[startPos-2] == '\n' {
				startPos--
			}
			if endPos+1 < len(input) && input[endPos+1] == '\n' {
				endPos++
			}

			output = input[:startPos] + input[endPos:]
		} else {
			return input, errors.New("found no closing delimiter")
		}
	} else {
		output = input
	}

	return output, nil
}
Beispiel #10
0
// getDirSubdir takes a source and returns a tuple of the URL without
// the subdir and the URL with the subdir.
func getDirSubdir(src string) (string, string) {
	// Calcaulate an offset to avoid accidentally marking the scheme
	// as the dir.
	var offset int
	if idx := strings.Index(src, "://"); idx > -1 {
		offset = idx + 3
	}

	// First see if we even have an explicit subdir
	idx := strings.Index(src[offset:], "//")
	if idx == -1 {
		return src, ""
	}

	idx += offset
	subdir := src[idx+2:]
	src = src[:idx]

	// Next, check if we have query parameters and push them onto the
	// URL.
	if idx = strings.Index(subdir, "?"); idx > -1 {
		query := subdir[idx:]
		subdir = subdir[:idx]
		src += query
	}

	return src, subdir
}
Beispiel #11
0
func filePathsFromArgs(args []string) ([]string, error) {
	var output []string
	var err error

	if len(args) == 0 {
		output, err = filepath.Glob("*")
		if err != nil {
			return []string{}, err
		}
	} else {
		for _, arg := range args {
			if strings.Index(arg, "*") < 0 && strings.Index(arg, "?") < 0 {
				output = append(output, arg)
				continue
			}
			matches, err := filepath.Glob(arg)
			if err != nil {
				return []string{}, err
			}
			for _, match := range matches {
				output = append(output, match)
			}
		}
	}

	sort.Strings(output)

	return output, nil
}
Beispiel #12
0
func TestPurgeOnlyUploads(t *testing.T) {
	oldUploadCount := 5
	oneHourAgo := time.Now().Add(-1 * time.Hour)
	fs := testUploadFS(t, oldUploadCount, "test-repo", oneHourAgo)

	// Create a directory tree outside _uploads and ensure
	// these files aren't deleted.
	dataPath, err := pm.path(uploadDataPathSpec{name: "test-repo", uuid: uuid.New()})
	if err != nil {
		t.Fatalf(err.Error())
	}
	nonUploadPath := strings.Replace(dataPath, "_upload", "_important", -1)
	if strings.Index(nonUploadPath, "_upload") != -1 {
		t.Fatalf("Non-upload path not created correctly")
	}

	nonUploadFile := path.Join(nonUploadPath, "file")
	if err = fs.PutContent(nonUploadFile, []byte("")); err != nil {
		t.Fatalf("Unable to write data file")
	}

	deleted, errs := PurgeUploads(fs, time.Now(), true)
	if len(errs) != 0 {
		t.Error("Unexpected errors", errs)
	}
	for _, file := range deleted {
		if strings.Index(file, "_upload") == -1 {
			t.Errorf("Non-upload file deleted")
		}
	}
}
func opener(t *testing.T) func(string) (Reader, Reader) {
	var wrdr, wrdr2 Reader
	return func(path string) (Reader, Reader) {
		buf, _ := ioutil.ReadFile(path)
		rdr := bytes.NewReader(buf)
		rdr2 := bytes.NewReader(buf)
		var err error
		if wrdr == nil {
			wrdr, err = NewReader(rdr)
		} else {
			err = wrdr.Reset(rdr)
		}
		if err != nil {
			if strings.Index(path, "invalid") != -1 {
				return nil, nil
			}
			t.Fatalf("test case: %s; error: %v", path, err)
		}
		if wrdr2 == nil {
			wrdr2, err = NewReader(rdr2)
		} else {
			err = wrdr2.Reset(rdr2)
		}
		if err != nil {
			if strings.Index(path, "invalid") != -1 {
				return nil, nil
			}
			t.Fatalf("test case: %s; error: %v", path, err)
		}
		return wrdr, wrdr2
	}
}
func testAccDatabaseCheck(rn string, name *string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[rn]
		if !ok {
			return fmt.Errorf("resource not found: %s", rn)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("database id not set")
		}

		conn := testAccProvider.Meta().(mysqlc.Conn)
		rows, _, err := conn.Query("SHOW CREATE DATABASE terraform_acceptance_test")
		if err != nil {
			return fmt.Errorf("error reading database: %s", err)
		}
		if len(rows) != 1 {
			return fmt.Errorf("expected 1 row reading database but got %d", len(rows))
		}

		row := rows[0]
		createSQL := string(row[1].([]byte))

		if strings.Index(createSQL, "CHARACTER SET utf8") == -1 {
			return fmt.Errorf("database default charset isn't utf8")
		}
		if strings.Index(createSQL, "COLLATE utf8_bin") == -1 {
			return fmt.Errorf("database default collation isn't utf8_bin")
		}

		*name = rs.Primary.ID

		return nil
	}
}
// Handle 352 who reply
func (conn *Conn) h_352(line *Line) {
	nk := conn.st.GetNick(line.Args[5])
	if nk == nil {
		logging.Warn("irc.352(): received WHO reply for unknown nick %s",
			line.Args[5])
		return
	}
	if nk == conn.Me() {
		return
	}
	nk.Ident = line.Args[2]
	nk.Host = line.Args[3]
	// XXX: do we care about the actual server the nick is on?
	//      or the hop count to this server?
	// last arg contains "<hop count> <real name>"
	a := strings.SplitN(line.Args[len(line.Args)-1], " ", 2)
	nk.Name = a[1]
	if idx := strings.Index(line.Args[6], "*"); idx != -1 {
		nk.Modes.Oper = true
	}
	if idx := strings.Index(line.Args[6], "B"); idx != -1 {
		nk.Modes.Bot = true
	}
	if idx := strings.Index(line.Args[6], "H"); idx != -1 {
		nk.Modes.Invisible = true
	}
}
Beispiel #16
0
func loadTestUsersCommand(c *Context, command *model.Command) bool {
	cmd1 := "/loadtest users"
	cmd2 := "/loadtest users fuzz"

	if strings.Index(command.Command, cmd1) == 0 && !command.Suggest {
		cmd := cmd1
		doFuzz := false
		if strings.Index(command.Command, cmd2) == 0 {
			doFuzz = true
			cmd = cmd2
		}
		usersr, err := parseRange(command.Command, cmd)
		if err == false {
			usersr = utils.Range{10, 15}
		}
		client := model.NewClient(c.GetSiteURL())
		userCreator := NewAutoUserCreator(client, c.Session.TeamId)
		userCreator.Fuzzy = doFuzz
		userCreator.CreateTestUsers(usersr)
		return true
	} else if strings.Index(cmd1, command.Command) == 0 {
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd1, Description: "Add a specified number of random users to current team <Min Users> <Max Users>"})
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd2, Description: "Add a specified number of random users with fuzz text to current team <Min Users> <Max Users>"})
	} else if strings.Index(cmd2, command.Command) == 0 {
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd2, Description: "Add a specified number of random users with fuzz text to current team <Min Users> <Max Users>"})
	}

	return false
}
Beispiel #17
0
func loadTestChannelsCommand(c *Context, command *model.Command) bool {
	cmd1 := "/loadtest channels"
	cmd2 := "/loadtest channels fuzz"

	if strings.Index(command.Command, cmd1) == 0 && !command.Suggest {
		cmd := cmd1
		doFuzz := false
		if strings.Index(command.Command, cmd2) == 0 {
			doFuzz = true
			cmd = cmd2
		}
		channelsr, err := parseRange(command.Command, cmd)
		if err == false {
			channelsr = utils.Range{20, 30}
		}
		client := model.NewClient(c.GetSiteURL())
		client.MockSession(c.Session.Token)
		channelCreator := NewAutoChannelCreator(client, c.Session.TeamId)
		channelCreator.Fuzzy = doFuzz
		channelCreator.CreateTestChannels(channelsr)
		return true
	} else if strings.Index(cmd1, command.Command) == 0 {
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd1, Description: "Add a specified number of random channels to current team <MinChannels> <MaxChannels>"})
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd2, Description: "Add a specified number of random channels with fuzz text to current team <Min Channels> <Max Channels>"})
	} else if strings.Index(cmd2, command.Command) == 0 {
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd2, Description: "Add a specified number of random channels with fuzz text to current team <Min Channels> <Max Channels>"})
	}

	return false
}
Beispiel #18
0
func MeasurementFromSeriesKey(key string) string {
	idx := strings.Index(key, ",")
	if idx == -1 {
		return key
	}
	return key[:strings.Index(key, ",")]
}
// FilenameParam groups input in two categories: URLs and files (files, directories, STDIN)
// If enforceNamespace is false, namespaces in the specs will be allowed to
// override the default namespace. If it is true, namespaces that don't match
// will cause an error.
// If ContinueOnError() is set prior to this method, objects on the path that are not
// recognized will be ignored (but logged at V(2)).
func (b *Builder) FilenameParam(enforceNamespace bool, filenameOptions *FilenameOptions) *Builder {
	recursive := filenameOptions.Recursive
	paths := filenameOptions.Filenames
	for _, s := range paths {
		switch {
		case s == "-":
			b.Stdin()
		case strings.Index(s, "http://") == 0 || strings.Index(s, "https://") == 0:
			url, err := url.Parse(s)
			if err != nil {
				b.errs = append(b.errs, fmt.Errorf("the URL passed to filename %q is not valid: %v", s, err))
				continue
			}
			b.URL(defaultHttpGetAttempts, url)
		default:
			if !recursive {
				b.singular = true
			}
			b.Path(recursive, s)
		}
	}

	if enforceNamespace {
		b.RequireNamespace()
	}

	return b
}
Beispiel #20
0
func combineURL(rootURL, subURL string) string {
	protocolEnd := "://"
	protoEndIndex := strings.Index(rootURL, protocolEnd)
	a := rootURL[protoEndIndex+len(protocolEnd):]
	rootIndex := strings.Index(a, "/")
	return rootURL[0:protoEndIndex+len(protocolEnd)+rootIndex] + subURL
}
Beispiel #21
0
func sizer(originalTag string) string {
	tag := originalTag
	if strings.Index(tag, widthAttr) > -1 &&
		strings.Index(tag, heightAttr) > -1 {
		return tag // width & height attributes are already present
	}
	match := srcRx.FindStringSubmatch(tag)
	if match == nil {
		fmt.Println("can't find <img>'s src attribute", tag)
		return tag
	}
	file, err := os.Open(match[1])
	if err != nil {
		fmt.Println("can't open image to read its size:", err)
		return tag
	}
	defer file.Close()
	config, _, err := image.DecodeConfig(file)
	if err != nil {
		fmt.Println("can't ascertain the image's size:", err)
		return tag
	}
	tag, end := tagEnd(tag)
	if strings.Index(tag, widthAttr) == -1 {
		tag += fmt.Sprintf(` %s"%d"`, widthAttr, config.Width)
	}
	if strings.Index(tag, heightAttr) == -1 {
		tag += fmt.Sprintf(` %s"%d"`, heightAttr, config.Height)
	}
	tag += end
	return tag
}
Beispiel #22
0
func insertSQLClause(querySQL, clause string) string {
	// get first index of any additional clause: group by, order by, limit, for update, sql end if nothing
	// insert clause into the index position
	sql := strings.ToLower(querySQL)
	idxExtra := len(sql)
	if idxGroupBy := strings.Index(sql, " group by"); idxGroupBy > 0 && idxGroupBy < idxExtra {
		idxExtra = idxGroupBy
	}
	if idxOrderBy := strings.Index(sql, " order by"); idxOrderBy > 0 && idxOrderBy < idxExtra {
		idxExtra = idxOrderBy
	}
	if idxLimit := strings.Index(sql, " limit"); idxLimit > 0 && idxLimit < idxExtra {
		idxExtra = idxLimit
	}
	if idxForUpdate := strings.Index(sql, " for update"); idxForUpdate > 0 && idxForUpdate < idxExtra {
		idxExtra = idxForUpdate
	}
	var b bytes.Buffer
	b.Write([]byte(querySQL[:idxExtra]))
	if strings.Contains(sql, "where") {
		b.Write(kwAnd)
	} else {
		b.Write(kwWhere)
	}
	b.Write([]byte(clause))
	if idxExtra < len(sql) {
		b.Write([]byte(querySQL[idxExtra:]))
	}
	return b.String()
}
Beispiel #23
0
func TestPostStoreGet(t *testing.T) {
	Setup()

	o1 := &model.Post{}
	o1.ChannelId = model.NewId()
	o1.UserId = model.NewId()
	o1.Message = "a" + model.NewId() + "b"

	etag1 := (<-store.Post().GetEtag(o1.ChannelId)).Data.(string)
	if strings.Index(etag1, model.CurrentVersion+".0.") != 0 {
		t.Fatal("Invalid Etag")
	}

	o1 = (<-store.Post().Save(o1)).Data.(*model.Post)

	etag2 := (<-store.Post().GetEtag(o1.ChannelId)).Data.(string)
	if strings.Index(etag2, model.CurrentVersion+"."+o1.Id) != 0 {
		t.Fatal("Invalid Etag")
	}

	if r1 := <-store.Post().Get(o1.Id); r1.Err != nil {
		t.Fatal(r1.Err)
	} else {
		if r1.Data.(*model.PostList).Posts[o1.Id].CreateAt != o1.CreateAt {
			t.Fatal("invalid returned post")
		}
	}

	if err := (<-store.Post().Get("123")).Err; err == nil {
		t.Fatal("Missing id should have failed")
	}
}
Beispiel #24
0
func resolvePathObj(j *simplejson.Json, path string) *simplejson.Json {
	if j == nil {
		return nil
	}

	if idx := strings.Index(path, "["); idx > 0 {
		var idx2 int
		var objidx int
		var err error

		idx2 = strings.Index(path, "]")

		if objidx, err = strconv.Atoi(path[idx+1 : strings.Index(path, "]")]); err != nil {
			return nil
		}

		oldpath := path[0:idx]
		newpath := path[idx2+2:]

		return resolvePathObj(j.GetPath(oldpath).GetIndex(objidx), newpath)
	} else {
		if resolved := j.GetPath(path); resolved != nil {
			return resolved
		}
	}

	return nil
}
Beispiel #25
0
func TestStructNonStruct(t *testing.T) {
	type Struct struct {
		A string
	}
	type NonStruct string
	s := Struct{"hello"}
	var sp Struct
	if err := encAndDec(s, &sp); err != nil {
		t.Error(err)
	}
	var ns NonStruct
	if err := encAndDec(s, &ns); err == nil {
		t.Error("should get error for struct/non-struct")
	} else if strings.Index(err.Error(), "type") < 0 {
		t.Error("for struct/non-struct expected type error; got", err)
	}
	// Now try the other way
	var nsp NonStruct
	if err := encAndDec(ns, &nsp); err != nil {
		t.Error(err)
	}
	if err := encAndDec(ns, &s); err == nil {
		t.Error("should get error for non-struct/struct")
	} else if strings.Index(err.Error(), "type") < 0 {
		t.Error("for non-struct/struct expected type error; got", err)
	}
}
Beispiel #26
0
func ComputePct100(accuracy string) int {
	pct := strings.Index(accuracy, "%")
	if pct > 0 {
		accuracy = accuracy[0:pct]
	}
	dot := strings.Index(accuracy, ".")
	if dot < 0 {
		if n, err := strconv.Atoi(accuracy); err == nil {
			return n * 100
		}
		return 0
	}
	pct100 := 0
	if n, err := strconv.Atoi(accuracy[0:dot]); err == nil {
		pct100 = n * 100
	}
	frac := accuracy[dot+1:]
	if len(frac) == 1 {
		if n, err := strconv.Atoi(frac); err == nil {
			pct100 += n * 10
		}
	} else {
		if len(frac) > 2 {
			frac = frac[0:2]
		}
		if frac[0] == '0' {
			frac = frac[1:]
		}
		if n, err := strconv.Atoi(frac); err == nil {
			pct100 += n
		}
	}
	return pct100
}
Beispiel #27
0
func TestGobEncoderFieldTypeError(t *testing.T) {
	// GobEncoder to non-decoder: error
	b := new(bytes.Buffer)
	enc := NewEncoder(b)
	err := enc.Encode(GobTest1{17, &StringStruct{"ABC"}})
	if err != nil {
		t.Fatal("encode error:", err)
	}
	dec := NewDecoder(b)
	x := &GobTest2{}
	err = dec.Decode(x)
	if err == nil {
		t.Fatal("expected decode error for mismatched fields (encoder to non-decoder)")
	}
	if strings.Index(err.Error(), "type") < 0 {
		t.Fatal("expected type error; got", err)
	}
	// Non-encoder to GobDecoder: error
	b.Reset()
	err = enc.Encode(GobTest2{17, "ABC"})
	if err != nil {
		t.Fatal("encode error:", err)
	}
	y := &GobTest1{}
	err = dec.Decode(y)
	if err == nil {
		t.Fatal("expected decode error for mismatched fields (non-encoder to decoder)")
	}
	if strings.Index(err.Error(), "type") < 0 {
		t.Fatal("expected type error; got", err)
	}
}
Beispiel #28
0
func (c *config) discoverSingle(glob string, m *map[string]string) error {
	matches, err := filepath.Glob(glob)
	if err != nil {
		return err
	}

	if *m == nil {
		*m = make(map[string]string)
	}

	prefix := filepath.Base(glob)
	prefix = prefix[:strings.Index(prefix, "*")]
	for _, match := range matches {
		file := filepath.Base(match)

		// If the filename has a ".", trim up to there
		if idx := strings.Index(file, "."); idx >= 0 {
			file = file[:idx]
		}

		// Look for foo-bar-baz. The plugin name is "baz"
		plugin := file[len(prefix):]
		log.Printf("[DEBUG] Discovered plugin: %s = %s", plugin, match)
		(*m)[plugin] = match
	}

	return nil
}
Beispiel #29
0
func loadTestCommand(c *Context, command *model.Command) bool {
	cmd := "/loadtest"

	// This command is only available when EnableTesting is true
	if !utils.Cfg.ServiceSettings.EnableTesting {
		return false
	}

	if strings.Index(command.Command, cmd) == 0 {
		if loadTestSetupCommand(c, command) {
			return true
		}
		if loadTestUsersCommand(c, command) {
			return true
		}
		if loadTestChannelsCommand(c, command) {
			return true
		}
		if loadTestPostsCommand(c, command) {
			return true
		}
	} else if strings.Index(cmd, command.Command) == 0 {
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd, Description: "Debug Load Testing"})
	}

	return false
}
func ContainsMoreThanOneSlashInNationalNumber(
	number *PhoneNumber,
	candidate string) bool {
	var firstSlash = strings.Index(candidate, "/")
	if firstSlash < 0 {
		// No slashes, this is okay.
		return false
	}
	// Now look for a second one.
	var secondSlash = strings.Index(candidate[firstSlash+1:], "/")
	if secondSlash < 0 {
		// Only one slash, this is okay.
		return false
	}

	// If the first slash is after the country calling code, this is permitted.
	var candidateHasCountryCode = (number.GetCountryCodeSource() == PhoneNumber_FROM_NUMBER_WITH_PLUS_SIGN ||
		number.GetCountryCodeSource() == PhoneNumber_FROM_NUMBER_WITHOUT_PLUS_SIGN)
	cc := strconv.Itoa(int(number.GetCountryCode()))
	if candidateHasCountryCode &&
		NormalizeDigitsOnly(candidate[0:firstSlash]) == cc {
		// Any more slashes and this is illegal.
		return strings.Contains(candidate[secondSlash+1:], "/")
	}
	return true
}