コード例 #1
0
ファイル: main.go プロジェクト: suifengRock/go-source
func main() {
	fmt.Println(strings.Index("chicken", "ken"))
	fmt.Println(strings.Index("chicken", "dmr"))

	fmt.Println(strings.ContainsAny("team", "e"))
	fmt.Println(strings.ContainsAny("failure", "u & i"))
	fmt.Println(strings.ContainsAny("foo", ""))
	fmt.Println(strings.ContainsAny("", ""))

	fmt.Println(1 & 1)
	fmt.Println(2 & 1)
	fmt.Println(4 & 1)
	fmt.Println(5 & 1)

	pow, sq := HashTest("1234567")
	fmt.Println(pow)
	fmt.Println(sq)

	str := "df 世 界 asd"
	s := "1界"
	index := strings.IndexAny(str, "界")
	fmt.Printf("%d......\n", index)
	for i, c := range str {
		fmt.Println(i)
		for _, m := range s {
			fmt.Printf("%c\t%c\n", c, m)
		}
	}

	for i := len(str); i > 0; {
		rune, size := utf8.DecodeLastRuneInString(str[0:i])
		fmt.Printf("%v\t", i)
		i -= size
		for _, m := range s {
			fmt.Printf("%c\t%v\t%v\n", rune, size, m)
		}
	}

	fmt.Println("bytes =", len(str))
	fmt.Println("runes =", utf8.RuneCountInString(str))

	for _, ss := range strings.Fields(str) {
		fmt.Println(ss)

	}
	fmt.Println(strings.ToTitle(str))

	str = "Hello, 世界"

	// for len(str) > 0 {
	// 	r, size := utf8.DecodeRuneInString(str)
	// 	fmt.Printf("%c %v\n", r, size)

	// 	str = str[size:]
	// }
	fmt.Println(Replace(str, "", "f", -1))

	hulu := new(huluwa)
	hello(hulu)
}
コード例 #2
0
func (s *DockerSuite) TestKillWithInvalidSignal(c *check.C) {
	testRequires(c, DaemonIsLinux)
	out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
	cid := strings.TrimSpace(out)
	c.Assert(waitRun(cid), check.IsNil)

	out, _, err := dockerCmdWithError("kill", "-s", "0", cid)
	c.Assert(err, check.NotNil)
	if !strings.ContainsAny(out, "Invalid signal: 0") {
		c.Fatal("Kill with an invalid signal didn't error out correctly")
	}

	running, _ := inspectField(cid, "State.Running")
	if running != "true" {
		c.Fatal("Container should be in running state after an invalid signal")
	}

	out, _ = dockerCmd(c, "run", "-d", "busybox", "top")
	cid = strings.TrimSpace(out)
	c.Assert(waitRun(cid), check.IsNil)

	out, _, err = dockerCmdWithError("kill", "-s", "SIG42", cid)
	c.Assert(err, check.NotNil)
	if !strings.ContainsAny(out, "Invalid signal: SIG42") {
		c.Fatal("Kill with an invalid signal error out correctly")
	}

	running, _ = inspectField(cid, "State.Running")
	if running != "true" {
		c.Fatal("Container should be in running state after an invalid signal")
	}
}
コード例 #3
0
ファイル: format_test.go プロジェクト: rawlingsj/gofabric8
func testGenericRecursive(t *testing.T, beforeErr error, beforeWant []string, list []wrapper, maxDepth int) {
	if len(beforeWant) == 0 {
		panic("beforeWant must not be empty")
	}
	for _, w := range list {
		if len(w.want) == 0 {
			panic("want must not be empty")
		}

		err := w.wrap(beforeErr)

		// Copy required cause append(beforeWant, ..) modified beforeWant subtly.
		beforeCopy := make([]string, len(beforeWant))
		copy(beforeCopy, beforeWant)

		beforeWant := beforeCopy
		last := len(beforeWant) - 1
		var want []string

		// Merge two stacks behind each other.
		if strings.ContainsAny(beforeWant[last], "\n") && strings.ContainsAny(w.want[0], "\n") {
			want = append(beforeWant[:last], append([]string{beforeWant[last] + "((?s).*)" + w.want[0]}, w.want[1:]...)...)
		} else {
			want = append(beforeWant, w.want...)
		}

		testFormatCompleteCompare(t, maxDepth, err, "%+v", want, false)
		if maxDepth > 0 {
			testGenericRecursive(t, err, want, list, maxDepth-1)
		}
	}
}
コード例 #4
0
ファイル: config.go プロジェクト: sujonmiya/youtube-dl
// reads the videoId property and try to find what we need inside
func (cfg *Config) findVideoId() (videoId string, err error) {
	videoId = cfg.videoId
	if strings.Contains(videoId, "youtu") || strings.ContainsAny(videoId, "\"?&/<%=") {
		log("Provided video id seems to be an url, trying to detect")
		re_list := []*regexp.Regexp{
			regexp.MustCompile(`(?:v|embed|watch\?v)(?:=|/)([^"&?/=%]{11})`),
			regexp.MustCompile(`(?:=|/)([^"&?/=%]{11})`),
			regexp.MustCompile(`([^"&?/=%]{11})`),
		}
		for _, re := range re_list {
			if is_match := re.MatchString(videoId); is_match {
				subs := re.FindStringSubmatch(videoId)
				videoId = subs[1]
			}
		}
	}
	log("Found video id: '%s'", videoId)
	if strings.ContainsAny(videoId, "?&/<%=") {
		return videoId, errors.New("invalid characters in video id")
	}
	if len(videoId) < 10 {
		return videoId, errors.New("the video id must be at least 10 characters long")
	}
	return videoId, nil
}
コード例 #5
0
ファイル: markov.go プロジェクト: Albrektson/markov
func preprocess(input string) (string, bool, bool) {
	ok := true
	end := false
	output := input
	var buffer bytes.Buffer

	//skip words with numerals
	nums := "1234567890"
	if strings.ContainsAny(input, nums) {
		ok = false
		return output, ok, end
	}

	//remove parenthesis
	i := strings.IndexAny(input, "()")
	if i > -1 {
		buffer.WriteString(input[:i])
		buffer.WriteString(input[i+1:])
		output = buffer.String()
	}

	if strings.ContainsAny(input, ".!?") {
		end = true
	}

	return output, ok, end
}
コード例 #6
0
ファイル: handlers.go プロジェクト: MajorMJR/homesite
func GetBlog(w http.ResponseWriter, r *http.Request) {
	u := User{}

	// Check if offset and limit were provided for pagination
	vars := mux.Vars(r)
	offset, err := strconv.Atoi(vars["offset"])
	if err != nil {
		// If var is empty assign default value
		if strings.ContainsAny(err.Error(), "invalid syntax") {
			offset = 0
		} else {
			log.Printf("No offset query parameter: %s", err)
		}
	}
	limit, err := strconv.Atoi(vars["limit"])
	if err != nil {
		// If var is empty assign default value
		if strings.ContainsAny(err.Error(), "invalid syntax") {
			limit = 10
		} else {
			log.Printf("No offset query parameter: %s", err)
		}
	}

	b, err := selectPageBlogEntries(limit, offset)
	if err != nil {
		log.Printf("ERROR: could not retrieve blog entries")
	}

	bFmt := []Post{}
	for _, post := range b {
		blogpost := Post{
			Id:       post.Id,
			Postdate: post.PostDate.Format("15:04:05 Mon Jan 2 2006"),
			Title:    post.Title,
			Tags:     post.Tags,
			Body:     template.HTML(string(blackfriday.MarkdownCommon([]byte(post.Body)))),
		}
		bFmt = append(bFmt, blogpost)
	}

	data := struct {
		Blog []Post
		User User
	}{
		bFmt,
		u,
	}

	t, err := template.ParseFiles("tmpl/base.html",
		"tmpl/header.tmpl",
		"tmpl/navbar.tmpl",
		"tmpl/blog-body.tmpl",
		"tmpl/footer.tmpl",
		"tmpl/js.tmpl")
	if err != nil {
		log.Printf("ERROR: error creating blog HTML template: %s", err)
	}
	t.Execute(w, data)
}
コード例 #7
0
ファイル: netutils.go プロジェクト: jojimt/netplugin
//ConvertBandwidth will change the format of the bandwidth to int64 format and return the updated bw.
//eg:- 2 kb bandwidth will be converted to 2*1024 and the result in Int64 format will be returned.
func ConvertBandwidth(bandwidth string) int64 {
	var rate int64

	const (
		kilobytes = 1024
		megabytes = 1024 * kilobytes
		gigabytes = 1024 * megabytes
	)

	regex := regexp.MustCompile("[0-9]+")
	bw := regex.FindAllString(bandwidth, -1)
	bwParseInt, err := strconv.ParseInt(bw[0], 10, 64)
	if err != nil {
		log.Errorf("error converting bandwidth string to uint64 %+v", err)
	}
	if strings.ContainsAny(bandwidth, "g|G") {
		rate = gigabytes
	} else if strings.ContainsAny(bandwidth, "m|M") {
		rate = megabytes
	} else if strings.ContainsAny(bandwidth, "k|K") {
		rate = kilobytes
	}
	bwInt := bwParseInt * rate
	bwInt = bwInt / 1000

	return bwInt
}
コード例 #8
0
ファイル: stringsTest.go プロジェクト: upccup/cuplearn
// ContainsAny reports whether any Unicode code points in chars within s
func ContainsAny(s, chars string) bool {
	fmt.Println(strings.ContainsAny("team", "i"))        // false
	fmt.Println(strings.ContainsAny("failure", "u & i")) // true
	fmt.Println(strings.ContainsAny("foo", ""))          // false
	fmt.Println(strings.ContainsAny("", ""))             // false
	return strings.ContainsAny(s, chars)
}
コード例 #9
0
ファイル: docker_test.go プロジェクト: jojimt/netplugin
func BwConvertInt64(bandwidth string) (int64, error) {
	var rate int64

	const (
		kiloBytes = 1024
		magaBytes = 1024 * kiloBytes
		gigaBytes = 1024 * magaBytes
	)

	regex := regexp.MustCompile("[0-9]+")
	bwStr := regex.FindAllString(bandwidth, -1)
	bwInt, err := strconv.ParseInt(bwStr[0], 10, 64)
	if err != nil {
		logrus.Errorf("error converting bandwidth string to uint64 %+v", err)
		return 0, err
	}
	if strings.ContainsAny(bandwidth, "g|G") {
		rate = gigaBytes
	} else if strings.ContainsAny(bandwidth, "m|M") {
		rate = magaBytes
	} else if strings.ContainsAny(bandwidth, "k|K") {
		rate = kiloBytes
	}
	bwInt64 := bwInt * rate
	bwInt64 = bwInt64 / 1000

	return bwInt64, nil
}
コード例 #10
0
ファイル: jp-import.go プロジェクト: rosrad/grid
func cuter(line string) (it Item, suc bool) {
	items := strings.FieldsFunc(line, fieldFilter)
	if len(items) < 2 {
		// fmt.Println(line)
		return it, false
	}

	it.word = strings.Replace(items[0], " ", "", -1)
	ext_start := 1
	for ; ext_start < len(items); ext_start++ {
		if strings.ContainsAny(items[ext_start], "[]【】") {
			it.ext += strings.Trim(items[ext_start], "[]【】><+ \t")
		} else {
			break
		}
	}

	meanings := ""
	for i := ext_start; i < len(items); i++ {
		if strings.ContainsAny(items[i], "0123456789") {
			if len(meanings) != 0 {
				meanings += "-"
			}
			meanings += strings.Trim(items[i], "[]【】 \t\r\n-")
		}
	}
	if len(meanings) == 0 {
		meanings = items[ext_start]
	}
	it.meanings = strings.Split(meanings, "-")
	return it, true
}
コード例 #11
0
ファイル: cronparser.go プロジェクト: Horrendus/beehive
func check_syntax(insane string) bool {
	/* State machine; Sane == S3, S1
	~	0\-9		,		-		*		/
	S0	S + 2		Err		Err		S + 3	Err
	S1	Err			Err		Err		Err		Err
	S2	S++			Err		Err		Err		Err
	S3	Err			S - 3	S + 2	Err		S + 2
	S4	S -	3		Err		Err		Err		Err
	S5	S--			Err		Err		Err		Err
	*/

	state := 0
	for i := 0; i != len(insane); i++ {
		if strings.ContainsAny(string(insane[i]), "0123456789") {
			if state == 0 {
				state += 2
			} else if state == 2 {
				state++
			} else if state == 4 {
				state -= 3
			} else if state == 5 {
				state--
			} else {
				return false
			}
		} else if strings.ContainsAny(string(insane[i]), ",") {
			if state == 3 {
				state -= 3
			} else {
				return false
			}
		} else if strings.ContainsAny(string(insane[i]), "-") {
			if state == 3 {
				state += 2
			} else {
				return false
			}
		} else if strings.ContainsAny(string(insane[i]), "*") {
			if state == 0 {
				state += 3
			} else {
				return false
			}
		} else if strings.ContainsAny(string(insane[i]), "/") {
			if state == 3 {
				state += 2
			} else {
				return false
			}
		} else {
			return false
		}
	}
	if state == 3 || state == 1 {
		return true
	} else {
		return false
	}
}
コード例 #12
0
func main() {

	defer func() {
		if r := recover(); r != nil {
			fmt.Println(r)
			os.Exit(1)
		}
	}()

	utils.LogInfo("\nDeploying Agent Server...")

	var ln string
	var e error
	rd := bufio.NewReader(os.Stdin)

	for {
		ln, e = rd.ReadString('\n')
		println(ln)
		if e != nil {
			panic(e)
		} else if strings.ContainsAny(ln, "AGENT_KUBER_API") {
			break
		}
	}

	if !strings.ContainsAny(ln, "AGENT_KUBER_API") {
		panic("Missing Key, AGENT_KUBER_API. Cannot proceed.")
	}

	kv := strings.Split(ln, "=")
	utils.SetKey("AGENT_KUBER_API", kv[1])

	pk, puk, _ := utils.CreateSSHKey()

	c := deploy.CenturyLink{
		PublicSSHKey:   puk,
		APIUsername:    os.Getenv("USERNAME"),
		APIPassword:    os.Getenv("PASSWORD"),
		GroupID:        os.Getenv("GROUP_ID"),
		CPU:            1,
		MemoryGB:       1,
		TCPOpenPorts:   []int{3001},
		ServerName:     "AGENT",
		ServerTemplate: "UBUNTU-14-64-TEMPLATE",
	}

	utils.LogInfo("\nWaiting for server creation...")
	s, e := c.DeployVM()

	if e != nil {
		panic(e)
	}

	utils.SetKey("AGENT_PRIVATE_KEY", base64.StdEncoding.EncodeToString([]byte(pk)))
	utils.SetKey("AGENT_PUBLIC_IP", s.PublicIP)

	utils.LogInfo("\nAgent server deployment complete!!")
}
コード例 #13
0
ファイル: testString.go プロジェクト: shawnpan/learnGo
func TestStrings() {
	fmt.Println("testStrings---------------------------------")
	a := "jiangkou jiangkou"
	b := "ang"
	fmt.Println("[a=", a, "][b=", b, "]")
	//查找某个字符是否在这个字符串中存在,存在返回true
	fmt.Println("strings.Contains(a, b) = ", strings.Contains(a, b))
	fmt.Println("strings.Contains(b, a) = ", strings.Contains(b, a))

	//查询字符串中是否包含多个字符
	c := "h&z"
	d := "i&o"
	fmt.Println("[c=", c, "][d=", d, "]")
	fmt.Println("strings.ContainsAny(a, c) = ", strings.ContainsAny(a, c))
	fmt.Println("strings.ContainsAny(a, d) = ", strings.ContainsAny(a, d))

	//一段字符串中有多少匹配到的字符
	fmt.Println("strings.Count(a, b) = ", strings.Count(a, b))

	//两个字符串在完全小写的情况下是否相等
	e := "JiAnGKOu"
	fmt.Println("e=", e)
	fmt.Println("strings.EqualFold(a, e) = ", strings.EqualFold(a, e))

	//空格来分割字符串最后返回的是[]string的切片
	f := "aa bcd efghij"
	fmt.Println("f=", f)
	fmt.Println("strings.Fields(f) = ", strings.Fields(f))

	//根据自定义函数来切分
	i := "aa|bcd_d|fgh_i|ej"
	j := '|'
	fmt.Println("[i=", i, "][j=", j, "]")
	fmt.Println(strings.FieldsFunc(i, func(s rune) bool {
		if s == rune(j) {
			return true
		}
		return false
	}))

	fmt.Println("strings.Split(i, string(j)) = ", strings.Split(i, string(j)))

	//判断是否以某个字符串开头
	g := "jia"
	fmt.Println("g=", g)
	fmt.Println("strings.HasPrefix(a, g) = ", strings.HasPrefix(a, g))

	//判断是否以某个字符串结尾
	h := "ou"
	fmt.Println("h=", h)
	fmt.Println("strings.HasSuffix(a, h) = ", strings.HasSuffix(a, h))

	// 字符串替换
	r := "welcome to shenzhen china"
	fmt.Print("orld str : ", r)
	r = strings.Replace(r, " ", ",", -1)
	fmt.Print(",replace str : ", r)
}
コード例 #14
0
ファイル: entityName_test.go プロジェクト: jddixon/xlUtil_go
func (s *XLSuite) noDotsOrDashes(rng *xr.PRNG) string {
	var length int = 3 + rng.Intn(16)
	var name = rng.NextFileName(length)
	for len(name) < 3 || strings.ContainsAny(name, ".-") ||
		strings.ContainsAny(name[0:1], "0123456789") {
		name = rng.NextFileName(length)
	}
	return name
}
コード例 #15
0
func main() {
	fmt.Println(strings.Contains("Assume", "Ass"))

	fmt.Println(strings.ContainsAny("team", "i"))
	fmt.Println(strings.ContainsAny("Hello", "aeiou&y"))

	fmt.Println(strings.HasPrefix("Hello World", "Hello"))
	fmt.Println(strings.HasSuffix("Hello World", "World"))
}
コード例 #16
0
ファイル: registry.go プロジェクト: johnnydtan/docker
func validVersion(version VersionInfo) bool {
	stopChars := " \t\r\n/"
	if strings.ContainsAny(version.Name(), stopChars) {
		return false
	}
	if strings.ContainsAny(version.Version(), stopChars) {
		return false
	}
	return true
}
コード例 #17
0
ファイル: work-with-strings.go プロジェクト: robotxet/gobits
func main() {
	s := "Hello world"
	s_equal := "Hello world"
	s_not := "world, Hello"

	// Simply iterate over string
	for _, c := range s {
		fmt.Printf("%c\n", c)
	}

	arr := []rune(s)

	for _, r := range arr {
		fmt.Printf("%d\n", r)
	}

	fmt.Printf("s := %s\n", s)
	fmt.Printf("s_equal := %s\n", s_equal)
	fmt.Printf("s_not := %s\n", s_not)

	//Compare returns an integer comparing two strings lexicographically.
	// The result will be 0 if a==b, -1 if a < b, and +1 if a > b
	fmt.Printf("equal: %d\n", strings.Compare(s, s_equal))
	fmt.Printf("not equal: %d\n", strings.Compare(s, s_not))

	//Contains reports whether substr is within s.
	fmt.Printf("check if \"world\" is substr of s: %v\n", strings.Contains(s, "world"))
	fmt.Printf("check in \"cat\" is substr of s: %v\n", strings.Contains(s, "cat"))

	// ContainsAny reports whether any Unicode code points in chars are within s.
	fmt.Printf("any of \"abcd\" in s: %v\n", strings.ContainsAny(s, "abcd"))
	fmt.Printf("any of \"mkt\" in s: %v\n", strings.ContainsAny(s, "mkt"))

	// ContainsRune reports whether the Unicode code point r is within s.
	fmt.Printf("find rune 72 is s: %v\n", strings.ContainsRune(s, 72))

	//ToLower
	fmt.Printf("lowercase: %s\n", strings.ToLower(s))

	//ToUpper
	fmt.Printf("uppercase: %s\n", strings.ToUpper(s))

	sentence := "Simple sentence with many words"

	words := strings.Split(sentence, " ")

	fmt.Printf("%v\n", words)

	//Split with many whitespaces : strings.Fields

	words = strings.Fields(sentence)

	fmt.Printf("%v\n", words)

}
コード例 #18
0
ファイル: templates.go プロジェクト: cbroglie/gosparkpost
// Validate runs sanity checks on a Template struct.
// This should catch most errors before attempting a doomed API call.
func (t *Template) Validate() error {
	if t == nil {
		return fmt.Errorf("Can't Validate a nil Template")
	}

	if t.Content.EmailRFC822 != "" {
		// TODO: optionally validate MIME structure
		// if MIME content is present, clobber all other Content options
		t.Content = Content{EmailRFC822: t.Content.EmailRFC822}
		return nil
	}

	// enforce required parameters
	if t.Content.Subject == "" {
		return fmt.Errorf("Template requires a non-empty Content.Subject")
	} else if t.Content.HTML == "" && t.Content.Text == "" {
		return fmt.Errorf("Template requires either Content.HTML or Content.Text")
	}
	_, err := ParseFrom(t.Content.From)
	if err != nil {
		return err
	}

	if len(t.Content.Attachments) > 0 {
		for _, att := range t.Content.Attachments {
			if len(att.Filename) > 255 {
				return fmt.Errorf("Attachment name length must be <= 255: [%s]", att.Filename)
			} else if strings.ContainsAny(att.B64Data, "\r\n") {
				return fmt.Errorf("Attachment data may not contain line breaks [\\r\\n]")
			}
		}
	}

	if len(t.Content.InlineImages) > 0 {
		for _, img := range t.Content.InlineImages {
			if len(img.Filename) > 255 {
				return fmt.Errorf("InlineImage name length must be <= 255: [%s]", img.Filename)
			} else if strings.ContainsAny(img.B64Data, "\r\n") {
				return fmt.Errorf("InlineImage data may not contain line breaks [\\r\\n]")
			}
		}
	}

	// enforce max lengths
	if len(t.ID) > 64 {
		return fmt.Errorf("Template id may not be longer than 64 bytes")
	} else if len(t.Name) > 1024 {
		return fmt.Errorf("Template name may not be longer than 1024 bytes")
	} else if len(t.Description) > 1024 {
		return fmt.Errorf("Template description may not be longer than 1024 bytes")
	}

	return nil
}
コード例 #19
0
ファイル: parser_test.go プロジェクト: jddixon/xlOverlay_go
func (s *XLSuite) getAName(rng *xr.PRNG) (name string) {
	name = string(rng.NextFileName(8))
	for {
		first := string(name[0])
		if !strings.ContainsAny(name, "-_.") && !strings.ContainsAny(first, "0123456789") {
			break
		}
		name = string(rng.NextFileName(8))
	}
	return
}
コード例 #20
0
ファイル: main.go プロジェクト: kheyalimitra/GeNA-Miner-Site
func ExampleContainsAny() {
	fmt.Println(strings.ContainsAny("team", "i"))
	fmt.Println(strings.ContainsAny("failure", "u & i"))
	fmt.Println(strings.ContainsAny("foo", ""))
	fmt.Println(strings.ContainsAny("", ""))
	// Output:
	// false
	// true
	// false
	// false
}
コード例 #21
0
ファイル: password.go プロジェクト: Rudloff/platform
func IsPasswordValid(password string) *model.AppError {
	id := "model.user.is_valid.pwd"
	isError := false
	min := model.PASSWORD_MINIMUM_LENGTH

	if IsLicensed && *License.Features.PasswordRequirements {
		if len(password) < *Cfg.PasswordSettings.MinimumLength || len(password) > model.PASSWORD_MAXIMUM_LENGTH {
			isError = true
		}

		if *Cfg.PasswordSettings.Lowercase {
			if !strings.ContainsAny(password, model.LOWERCASE_LETTERS) {
				isError = true
			}

			id = id + "_lowercase"
		}

		if *Cfg.PasswordSettings.Uppercase {
			if !strings.ContainsAny(password, model.UPPERCASE_LETTERS) {
				isError = true
			}

			id = id + "_uppercase"
		}

		if *Cfg.PasswordSettings.Number {
			if !strings.ContainsAny(password, model.NUMBERS) {
				isError = true
			}

			id = id + "_number"
		}

		if *Cfg.PasswordSettings.Symbol {
			if !strings.ContainsAny(password, model.SYMBOLS) {
				isError = true
			}

			id = id + "_symbol"
		}

		min = *Cfg.PasswordSettings.MinimumLength
	} else if len(password) > model.PASSWORD_MAXIMUM_LENGTH || len(password) < model.PASSWORD_MINIMUM_LENGTH {
		isError = true
		min = model.PASSWORD_MINIMUM_LENGTH
	}

	if isError {
		return model.NewLocAppError("User.IsValid", id+".app_error", map[string]interface{}{"Min": min}, "")
	}

	return nil
}
コード例 #22
0
ファイル: passman_test.go プロジェクト: seanpont/passman
func TestPasswordGeneration(t *testing.T) {
	assert := assert.Assert(t)
	generator := NewPasswordGenerator("lunc20")
	assert.Equal(generator.length, 20)
	password := generator.generate()
	assert.Equal(len(password), 20)
	assert.True(strings.ContainsAny(password, LOWERCASE), "missing characters")
	assert.True(strings.ContainsAny(password, UPPERCASE), "missing characters")
	assert.True(strings.ContainsAny(password, NUMBERS), "missing characters")
	assert.True(strings.ContainsAny(password, CHARACTERS), "missing characters")
}
コード例 #23
0
ファイル: user.go プロジェクト: JonPulfer/pman
// Function EditKey guides the user through editing a key in the key store.
func EditKey(ks KeyStore, KeyID string, secret []byte) {
	var editKey Key
	ks.Open(secret)
	editKey, ok := ks[KeyID]

	if ok {
		reader := bufio.NewReader(os.Stdin)
		fmt.Printf("What would you like to change?\n")
		fmt.Printf("Enter the first letter of each item you wish to edit: -\n")
		fmt.Printf("(L)oginname, (P)assword, (D)etail or (A)ll : ")
		input, err := reader.ReadString('\n')
		if err != nil {
			handleUserError(err)
		}

		// Edit the Login name
		if strings.ContainsAny(input, "LA") {
			fmt.Printf("Enter the new login name: ")
			newLoginname, err := reader.ReadString('\n')
			if err != nil {
				handleUserError(err)
			}
			newLoginname = strings.Trim(newLoginname, "\n")
			editKey.LoginName = newLoginname
		}

		// Edit the password
		if strings.ContainsAny(input, "PA") {
			fmt.Printf("Enter the new password: "******"\n")
			editKey.OldPassword = editKey.Password
			editKey.Password = newPassword
		}

		// Edit the Detail
		if strings.ContainsAny(input, "DA") {
			fmt.Printf("Enter the new details: ")
			newDetail, err := reader.ReadString('\n')
			if err != nil {
				handleUserError(err)
			}
			newDetail = strings.Trim(newDetail, "\n")
			editKey.Detail = newDetail
		}

		ks[KeyID] = editKey

		ks.Close(secret)
	}
}
コード例 #24
0
ファイル: lightweight.go プロジェクト: pombredanne/snappy-1
// PartBagByName finds a PartBag with the given name.
func PartBagByName(name string, origin string) *PartBag {
	if strings.ContainsAny(name, ".*?/") || strings.ContainsAny(origin, ".*?/") {
		panic("invalid name " + name + "." + origin)
	}

	for _, v := range find(name, origin) {
		return v
	}

	return nil
}
コード例 #25
0
ファイル: http.go プロジェクト: josephwinston/flynn
func validVersion(version VersionInfo) bool {
	const stopChars = " \t\r\n/"
	name := version.Name()
	vers := version.Version()
	if len(name) == 0 || strings.ContainsAny(name, stopChars) {
		return false
	}
	if len(vers) == 0 || strings.ContainsAny(vers, stopChars) {
		return false
	}
	return true
}
コード例 #26
0
func (vi *UAVersionInfo) isValid() bool {
	const stopChars = " \t\r\n/"
	name := vi.Name
	vers := vi.Version
	if len(name) == 0 || strings.ContainsAny(name, stopChars) {
		return false
	}
	if len(vers) == 0 || strings.ContainsAny(vers, stopChars) {
		return false
	}
	return true
}
コード例 #27
0
ファイル: useragent.go プロジェクト: wsnipex/mirrorbits
func (p *UserAgent) normalizeApple(comments []string) {

	if p.Platform == "IPhone" ||
		p.Platform == "IPad" ||
		p.Platform == "IPod" ||
		p.Platform == "AppleTV" {

		// some Apple UAs don't separate by "; ", but by ";"
		if strings.Contains(p.Platform, ";") {
			tmp := strings.Split(p.Platform, ";")
			p.Platform = tmp[0]
			comments = tmp[1:]
		}
		// set OS to IOS with the version limited to Major.Minor
		for _, com := range comments {
			if strings.ContainsAny(com, "0123456789") {
				o := strings.Split(com, " ")
				v := []string{}
				if len(o) >= 4 && strings.ContainsAny(o[3], "0123456789") {
					v = strings.Split(o[3], "_")
				} else if len(o) >= 3 && strings.ContainsAny(o[2], "0123456789") {
					v = strings.Split(o[2], "_")
				}
				if len(v) >= 2 {
					p.OS = "IOS"
					p.OSVer = v[0] + "." + v[1]
					return
				}
			}
		}
		p.OS = "IOS Unknown"
		return

	} else if p.Platform == "Macintosh" {

		// set OS to OSX with the version limited to Major.Minor
		for _, com := range comments {
			if strings.ContainsAny(com, "0123456789") {
				o := strings.Split(com, " ")
				if len(o) >= 5 && strings.ContainsAny(o[4], "0123456789") {
					v := strings.Split(o[4], "_")
					if len(v) >= 2 {
						p.OS = "OSX"
						p.OSVer = v[0] + "." + v[1]
						return
					}
				}
			}
		}
		p.OS = "OSX Unknown"
		return
	}
}
コード例 #28
0
ファイル: dao.go プロジェクト: xuzhiping7/studygolang
// 查询条件处理(TODO:暂时没有处理between和in)
func (this *Dao) Where(condition string) {
	this.whereVal = make([]interface{}, 0)
	stringBuilder := util.NewBuffer()
	conditions := SplitIn(condition, []string{" and ", " AND ", " or ", " OR "}...)
	for _, condition := range conditions {
		condition = strings.TrimSpace(condition)
		parts := SplitIn(condition, "=", "<", ">")
		if len(parts) >= 3 {
			// 处理不等于
			if strings.HasSuffix(parts[0], "!") {
				stringBuilder.Append("`" + strings.Trim(parts[0], "` !") + "` !")
			} else {
				stringBuilder.Append("`" + strings.Trim(parts[0], "` ") + "`")
			}
			stringBuilder.Append(strings.TrimSpace(parts[1]))
			if len(parts) > 3 {
				// 判断是不是 ">="或"<="
				if strings.ContainsAny(parts[2], "= & < & >") {
					stringBuilder.Append(strings.TrimSpace(parts[2]))
				}
				start := len(parts[0]) + len(parts[1]) + 1
				this.whereVal = append(this.whereVal, strings.TrimSpace(condition[start:]))
			} else {
				this.whereVal = append(this.whereVal, strings.TrimSpace(parts[2]))
			}
			stringBuilder.Append("?")
		} else {
			tmp := strings.ToUpper(parts[0])
			if tmp == "OR" || tmp == "AND" {
				stringBuilder.Append(" ").Append(tmp).Append(" ")
			} else {
				// 处理"in"语句(TODO:用正则处理?)
				if strings.ContainsAny(strings.ToLower(parts[0]), "in & ( & )") {
					ins := Split(parts[0], "(", ")")
					if len(ins) == 3 {
						inVals := strings.Split(ins[1], ",")
						for _, inVal := range inVals {
							this.whereVal = append(this.whereVal, inVal)
						}
						// in中有多少个值
						inLen := len(inVals)
						qms := strings.Repeat("?,", inLen)
						field := ins[0][:len(ins[0])-3]
						stringBuilder.Append("`" + strings.Trim(field, "` ") + "` in").Append("(").Append(qms[:len(qms)-1]).Append(")")
					}
				} else {
					stringBuilder.Append("`" + strings.Trim(parts[0], "` ") + "`")
				}
			}
		}
	}
	this.where = stringBuilder.String()
}
コード例 #29
0
ファイル: set.go プロジェクト: bluehawksky/geodns
func intMode(mode string) types.IntMode {
	var m types.IntMode
	if strings.ContainsAny(mode, "dD") {
		m |= types.Dec
	}
	if strings.ContainsAny(mode, "hH") {
		m |= types.Hex
	}
	if strings.ContainsAny(mode, "oO") {
		m |= types.Oct
	}
	return m
}
コード例 #30
0
ファイル: field_test.go プロジェクト: Danzabar/forms
// Testing class output
func TestAddingHtmlProperties(t *testing.T) {
	m := make(map[string]string)
	m["class"] = "testclass"
	m["data-id"] = "3"

	field := NewField()
	field.Props = m

	prop := field.getHtmlProperties()

	assert.Equal(t, true, strings.ContainsAny(prop, "class=\"testclass\""))
	assert.Equal(t, true, strings.ContainsAny(prop, "data-id=\"3\""))
}