func (conn *Connection) Indexes() (indexes []*Index, err error) { const sql = `SELECT RDB$INDICES.RDB$RELATION_NAME, RDB$INDICES.RDB$INDEX_NAME, RDB$INDICES.RDB$UNIQUE_FLAG, RDB$INDICES.RDB$INDEX_TYPE FROM RDB$INDICES JOIN RDB$RELATIONS ON RDB$INDICES.RDB$RELATION_NAME = RDB$RELATIONS.RDB$RELATION_NAME WHERE (RDB$RELATIONS.RDB$SYSTEM_FLAG <> 1 OR RDB$RELATIONS.RDB$SYSTEM_FLAG IS NULL);` var cursor *Cursor if cursor, err = conn.Execute(sql); err != nil { return } defer cursor.Close() for cursor.Next() { var index Index if err = cursor.Scan(&index.TableName, &index.Name, &index.Unique, &index.Unique); err != nil { return } index.Name = strings.TrimRightFunc(index.Name, unicode.IsSpace) index.TableName = strings.TrimRightFunc(index.TableName, unicode.IsSpace) if index.Columns, err = conn.IndexColumns(index.Name); err != nil { return } if conn.database.LowercaseNames && !hasLowercase(index.Name) { index.Name = strings.ToLower(index.Name) } if conn.database.LowercaseNames && !hasLowercase(index.TableName) { index.TableName = strings.ToLower(index.TableName) } indexes = append(indexes, &index) } if cursor.Err() != io.EOF { err = cursor.Err() } return }
func daemonIpcHandleConn(conn *net.UnixConn) { defer cluegetterRecover("daemonIpcHandleConn") defer conn.Close() for { message, err := bufio.NewReader(conn).ReadString('\x00') if err != nil { if message != "" { Log.Info("Got %s on IPC Socket. Ignoring.", err.Error()) } return } kv := strings.SplitN(message, " ", 2) handle := strings.TrimRightFunc(kv[0], func(v rune) bool { return v == '\x00' }) callback := ipcHandlers[handle] v := "" if len(kv) > 1 { v = strings.TrimRightFunc(kv[1], func(v rune) bool { return v == '\x00' }) } if callback == nil { Log.Debug("Received IPC message but no such pattern was registered, ignoring: <%s>%s", handle, v) return } callback(v) } }
// a < b = -1 // a == b = 0 // a > b = 1 func compareVersions(a, b string) int { if a == b { return 0 } aParts := strings.Split(a, ".") bParts := strings.Split(b, ".") for i, verA := range aParts { if len(bParts) <= i { return 1 } verB := bParts[i] aInt, err := strconv.Atoi(strings.TrimRightFunc(verA, isNotNumber)) if err != nil { aInt = 0 } bInt, err := strconv.Atoi(strings.TrimRightFunc(verB, isNotNumber)) if err != nil { bInt = 0 } if aInt > bInt { return 1 } if aInt < bInt { return -1 } } return 0 }
func (conn *Connection) Columns(tableName string) (columns []*Column, err error) { const sqlColumns = ` SELECT r.rdb$field_name, r.rdb$field_source, f.rdb$field_type, f.rdb$field_sub_type, f.rdb$field_length, f.rdb$field_precision, f.rdb$field_scale, COALESCE(r.rdb$default_source, f.rdb$default_source) rdb$default_source, COALESCE(r.rdb$null_flag, f.rdb$null_flag) rdb$null_flag FROM rdb$relation_fields r JOIN rdb$fields f ON r.rdb$field_source = f.rdb$field_name WHERE r.rdb$relation_name = ? ORDER BY r.rdb$field_position` var cursor *Cursor if cursor, err = conn.Execute(sqlColumns, tableName); err != nil { return } defer cursor.Close() for cursor.Next() { var col Column var sqlType int16 if err = cursor.Scan( &col.Name, &col.Domain, &sqlType, &col.SqlSubtype, &col.Length, &col.Precision, &col.Scale, &col.Default, &col.Nullable); err != nil { return } col.Name = strings.TrimRightFunc(col.Name, unicode.IsSpace) if conn.database.LowercaseNames && !hasLowercase(col.Name) { col.Name = strings.ToLower(col.Name) } col.Domain = strings.TrimRightFunc(col.Domain, unicode.IsSpace) if strings.HasPrefix(col.Domain, "RDB$") { col.Domain = "" } col.SqlType = sqlTypeFromCode(int(sqlType), int(col.SqlSubtype.Value)) if !col.Default.Null { col.Default.Value = strings.Replace(col.Default.Value, "DEFAULT ", "", 1) col.Default.Value = strings.TrimLeftFunc(col.Default.Value, unicode.IsSpace) } columns = append(columns, &col) } if cursor.Err() != io.EOF { err = cursor.Err() } return }
func killSmallWordLeft(ed *Editor) { left := strings.TrimRightFunc(ed.line[:ed.dot], unicode.IsSpace) // The case of left == "" is handled as well. r, _ := utf8.DecodeLastRuneInString(left) if isAlnum(r) { left = strings.TrimRightFunc(left, isAlnum) } else { left = strings.TrimRightFunc( left, func(r rune) bool { return !isAlnum(r) }) } ed.line = left + ed.line[ed.dot:] ed.dot = len(left) }
func handleConnection(conn net.Conn) { defer conn.Close() tcpconn, ok := conn.(*net.TCPConn) if ok { tcpconn.SetLinger(-1) tcpconn.SetKeepAlive(true) } readbuf := bufio.NewReader(conn) sendError(conn, SmtpNoServiceHere, "This is not the SMTP Service you are looking for, move along.") for { cmd, err := readbuf.ReadString('\n') if err != nil { break } cmd = strings.TrimRightFunc(cmd, unicode.IsSpace) if cmd == "" { continue } if strings.ToLower(cmd) == "quit" { break } sendError(conn, SmtpBadSequenceOfCommands, "bad sequence of commands") } }
func (w wsCollapser) Write(p []byte) (n int, err error) { lines := strings.Split(string(p), "\n") for i, line := range lines { l := line if *w.prevNewLine { l = strings.TrimLeftFunc(l, unicode.IsSpace) } curNewLine := (i < len(lines)-1) || (len(p) > 0 && p[len(p)-1] == '\n') if curNewLine { l = strings.TrimRightFunc(l, unicode.IsSpace) } if len(l) == 0 { *w.prevNewLine = curNewLine continue } if *w.prevNewLine && !*w.prevTag && l[0] != '<' { _, err := (*w.writer).Write([]byte(" ")) if err != nil { return 0, err } } _, err := (*w.writer).Write([]byte(l)) if err != nil { return 0, err } *w.prevTag = l[len(l)-1] == '>' *w.prevNewLine = curNewLine } return len(p), nil }
func mainTest(t *testing.T, args ...string) string { os.Args = append([]string{"tinystat"}, args...) f, err := ioutil.TempFile(os.TempDir(), "tinystat") if err != nil { t.Fatal(err) } defer func() { f.Close() }() oldStdout := os.Stdout defer func() { os.Stdout = oldStdout }() os.Stdout = f main() stdout, err := ioutil.ReadFile(f.Name()) if err != nil { t.Fatal(err) } // strip everything of trailing whitespace lines := strings.Split(string(stdout), "\n") for i, line := range lines { lines[i] = strings.TrimRightFunc(line, unicode.IsSpace) } return strings.Join(lines, "\n") }
// Read returns a full YAML document. func (r *YAMLReader) Read() ([]byte, error) { var buffer bytes.Buffer for { line, err := r.reader.Read() if err != nil && err != io.EOF { return nil, err } sep := len([]byte(separator)) if i := bytes.Index(line, []byte(separator)); i == 0 { // We have a potential document terminator i += sep after := line[i:] if len(strings.TrimRightFunc(string(after), unicode.IsSpace)) == 0 { if buffer.Len() != 0 { return buffer.Bytes(), nil } if err == io.EOF { return nil, err } } } if err == io.EOF { if buffer.Len() != 0 { // If we're at EOF, we have a final, non-terminated line. Return it. return buffer.Bytes(), nil } return nil, err } buffer.Write(line) } }
func (s *Service) PostApps_Repos_Points(args *cmdArgs, env *rpcutil.Env) (err error) { appid := args.CmdArgs[0] repoid := args.CmdArgs[1] data, err := ioutil.ReadAll(env.Req.Body) if err != nil { return err } reqSql := strings.TrimLeftFunc(string(data), isWhiteSpace) point := strings.TrimRightFunc(reqSql, isWhiteSpace) wurl := fmt.Sprintf("/v4/apps/%s/repos/%s/points", appid, repoid) err = s.PandoraClient.CallWith(nil, nil, "POST", wurl, "text/plain", bytes.NewBuffer([]byte(point)), len(point)) if err != nil { return fmt.Errorf("write pandora fail, error:%v", err) } err = s.InfluxdbClient.CallWith(nil, nil, "POST", "/write?db=pandora&rp=default", "text/plain", bytes.NewBuffer([]byte(point)), len(point)) if err != nil && err.Error() != "No Content" { return fmt.Errorf("write influxdb fail, error:%v", err) } return }
func (templater *templater) UsageFunc(exposedFlags ...string) func(*cobra.Command) error { return func(c *cobra.Command) error { t := template.New("custom") t.Funcs(template.FuncMap{ "trim": strings.TrimSpace, "trimRight": func(s string) string { return strings.TrimRightFunc(s, unicode.IsSpace) }, "gt": cobra.Gt, "eq": cobra.Eq, "rpad": rpad, "flagsNotIntersected": flagsNotIntersected, "flagsUsages": flagsUsages, "cmdGroups": templater.cmdGroups, "rootCmd": templater.rootCmdName, "isRootCmd": templater.isRootCmd, "optionsCmdFor": templater.optionsCmdFor, "exposed": func(c *cobra.Command) *flag.FlagSet { exposed := flag.NewFlagSet("exposed", flag.ContinueOnError) if len(exposedFlags) > 0 { for _, name := range exposedFlags { if flag := c.Flags().Lookup(name); flag != nil { exposed.AddFlag(flag) } } } return exposed }, }) template.Must(t.Parse(templater.UsageTemplate)) return t.Execute(c.Out(), c) } }
func main() { show("original", simple) show("leading ws removed", strings.TrimLeftFunc(simple, unicode.IsSpace)) show("trailing ws removed", strings.TrimRightFunc(simple, unicode.IsSpace)) // equivalent to strings.TrimFunc(simple, unicode.IsSpace) show("both removed", strings.TrimSpace(simple)) }
func parseEngineeringNotation(in string) (uint64, error) { if in == "" { return 0, nil } var numerics = func(r rune) bool { return r >= '0' && r <= '9' } var nonNumerics = func(r rune) bool { return !numerics(r) } suffix := strings.TrimLeftFunc(in, numerics) numeric := strings.TrimRightFunc(in, nonNumerics) val, err := strconv.ParseUint(numeric, 10, 64) if err != nil { return 0, fmt.Errorf("Parsing engineering notation for '%s'", in) } switch suffix { case "K", "k": val *= (1 << 10) case "M", "m": val *= (1 << 20) case "G", "g": val *= (1 << 30) case "T", "t": val *= (1 << 40) case "": break default: return 0, fmt.Errorf("Parsing engineering notation for '%s'", in) } return val, nil }
func (templater *templater) templateFuncs(exposedFlags ...string) template.FuncMap { return template.FuncMap{ "trim": strings.TrimSpace, "trimRight": func(s string) string { return strings.TrimRightFunc(s, unicode.IsSpace) }, "trimLeft": func(s string) string { return strings.TrimLeftFunc(s, unicode.IsSpace) }, "gt": cobra.Gt, "eq": cobra.Eq, "rpad": rpad, "appendIfNotPresent": appendIfNotPresent, "flagsNotIntersected": flagsNotIntersected, "visibleFlags": visibleFlags, "flagsUsages": flagsUsages, "cmdGroups": templater.cmdGroups, "cmdGroupsString": templater.cmdGroupsString, "rootCmd": templater.rootCmdName, "isRootCmd": templater.isRootCmd, "optionsCmdFor": templater.optionsCmdFor, "usageLine": templater.usageLine, "exposed": func(c *cobra.Command) *flag.FlagSet { exposed := flag.NewFlagSet("exposed", flag.ContinueOnError) if len(exposedFlags) > 0 { for _, name := range exposedFlags { if flag := c.Flags().Lookup(name); flag != nil { exposed.AddFlag(flag) } } } return exposed }, } }
func (cl cmdLine) Arg() string { s := string(cl) if idx := strings.Index(s, " "); idx != -1 { return strings.TrimRightFunc(s[idx+1:len(s)-2], unicode.IsSpace) } return "" }
func (b *CommandBot) HandleUpdate(_ *Bot, up *Update) { if up.Message == nil { return } if up.Message.Text == nil { return } text := *up.Message.Text if len(text) == 0 || text[0] != '/' { // Not a command return } cmd, args := Split(text[1:len(text)], ' ') cmd = strings.TrimRightFunc(cmd, unicode.IsSpace) cmd, to := Split(cmd, '@') if to != "" && to != b.Name { log.Println("addressed not to me, but to", to) // Not addressed to me return } for _, ach := range b.AnyHandlers { ach(b, cmd, args, up.Message) } chs, ok := b.Handlers[cmd] if !ok { log.Printf("unknown command %q", cmd) return } for _, ch := range chs { ch(b, args, up.Message) } }
func parse(line string) (cmd, req string) { cmd, req = "any", "" line = strings.TrimRightFunc(line, check) if strings.HasPrefix(line, "quit") { cmd, req = "quit", "" return cmd, req } if strings.HasPrefix(strings.ToLower(line), "get") { switch index := strings.Index(line, " "); index { case 3: str := strings.SplitN(line, " ", 2) cmd, req = "get", str[1] if req != "" { cmd = "get" } else { cmd = "bad" } case -1: if strings.EqualFold(line, "get") { cmd = "bad" } else { cmd = "any" } } } return }
func IsCloudConfig(userdata string) bool { header := strings.SplitN(userdata, "\n", 2)[0] // Trim trailing whitespaces header = strings.TrimRightFunc(header, unicode.IsSpace) return (header == "#cloud-config") }
// buildPath finds the absolute path based on the path parameter and the new relative path. func (p *PaginatedResult) buildPath(path string, newRelativePath string) (string, error) { oldURL, err := url.Parse("http://example.com" + path) if err != nil { return "", newError(50000, err) } rootPath := strings.TrimRightFunc(oldURL.Path, func(r rune) bool { return r != '/' }) return rootPath + strings.TrimLeft(newRelativePath, "./"), nil }
func (s command) Argument() string { d := string(s) data := strings.Split(d, " ") if len(data) > 1 { return strings.TrimRightFunc(strings.Join(data[1:], " "), unicode.IsSpace) } return "" }
func isCloudConfig(userdata []byte) bool { header := strings.SplitN(string(decompressIfGzipped(userdata)), "\n", 2)[0] // Trim trailing whitespaces header = strings.TrimRightFunc(header, unicode.IsSpace) return (header == "#cloud-config") }
// preprocess extracts the rectangle of lines that contain map data from the input. func preprocess(asciiMap string) (lines []string, err error) { lines = strings.Split(asciiMap, "\n") // Remove heading and trailing empty lines. for len(lines) > 0 && isEmpty(lines[0]) { lines = lines[1:len(lines)] } for len(lines) > 0 && isEmpty(lines[len(lines)-1]) { lines = lines[0 : len(lines)-1] } if len(lines) == 0 { err = errors.New("Empty ASCII") return } indent := math.MaxInt32 maxWidth := 0 // Deterimine indent level and rightmost text level, look for forbidden things for _, line := range lines { if strings.Contains(line, "\t") { err = errors.New("Physical tabs in chunk ASCII") return } if isEmpty(line) { err = errors.New("Discontinuous ASCII map") return } startPos, endPos := measure(line) if startPos >= 0 { if startPos < indent { indent = startPos } if endPos > maxWidth { maxWidth = endPos } } } // Correct the width for the indent level. maxWidth -= indent // Pad all lines to the same width. for i, line := range lines { line = strings.TrimRightFunc(line, unicode.IsSpace) line = line[indent:len(line)] pad := maxWidth - len(line) if pad > 0 { line += strings.Repeat(" ", pad) } if len(line) != maxWidth { panic("Line padding broken") } lines[i] = line } return }
// TrimRightFunc trims the runes from the right end of the text where the specified callback function returns true, // returning a new structure and leaving the original unchanged. func (piece *RichText) TrimRightFunc(f func(rune) bool) *RichText { s := piece.String() trimmed := strings.TrimRightFunc(s, f) if len(trimmed) == len(s) { return piece } left, _ := piece.Split(len(trimmed)) return left }
//get value in string func getRawValue(input []byte) (string, int) { start := SkipSpace(input) end := start + skipUntilValueEnd(input[start:]) val := string(input[start:end]) val = strings.TrimRightFunc(val, unicode.IsSpace) idx := end + skipRest(input[end:]) return val, idx }
func fSay(wr io.Writer, msg string, trim bool) (int, error) { if trim { msg = strings.TrimRightFunc(msg, unicode.IsSpace) } if c, _ := utf8.DecodeLastRuneInString(msg); unicode.IsSpace(c) { return fmt.Fprint(wr, msg) } return fmt.Fprintln(wr, msg) }
// NOTE(xiaq): A word is now defined as a series of non-whitespace chars. func killWordLeft(ed *Editor) { if ed.dot == 0 { } space := strings.LastIndexFunc( strings.TrimRightFunc(ed.line[:ed.dot], unicode.IsSpace), unicode.IsSpace) + 1 ed.line = ed.line[:space] + ed.line[ed.dot:] ed.dot = space }
func getCoverUrlFromInput() string { term.OutputMessage("Enter a URL the cover image: ") cover_url, err := STD_IN.ReadString('\n') if err != nil { term.OutputError("Error accepting input.") os.Exit(2) } return strings.TrimRightFunc(cover_url, unicode.IsSpace) }
func (u *PrefixedUi) prefixLines(prefix, message string) string { var result bytes.Buffer for _, line := range strings.Split(message, "\n") { result.WriteString(fmt.Sprintf("%s: %s\n", prefix, line)) } return strings.TrimRightFunc(result.String(), unicode.IsSpace) }
func moveDotLeftWord(ed *Editor) { if ed.dot == 0 { return } space := strings.LastIndexFunc( strings.TrimRightFunc(ed.line[:ed.dot], unicode.IsSpace), unicode.IsSpace) + 1 ed.dot = space }
func (this *html_cleaner) trim_empty_spaces(n *html.Node) { this.trim_empty_spaces_func(n, func(o string) string { return strings.TrimLeftFunc(o, unicode.IsSpace) }) this.trim_empty_spaces_func(n, func(o string) string { return strings.TrimRightFunc(o, unicode.IsSpace) }) }