func (self *ProcState) Get(pid int) error { contents, err := readProcFile(pid, "stat") if err != nil { return err } headerAndStats := strings.SplitAfterN(string(contents), ")", 2) pidAndName := headerAndStats[0] fields := strings.Fields(headerAndStats[1]) name := strings.SplitAfterN(pidAndName, " ", 2)[1] if name[0] == '(' && name[len(name)-1] == ')' { self.Name = name[1 : len(name)-1] // strip ()'s } else { return errors.New(fmt.Sprintf("Malformed process stats for pid %d", pid)) } self.State = RunState(fields[0][0]) self.Ppid, _ = strconv.Atoi(fields[1]) self.Tty, _ = strconv.Atoi(fields[4]) self.Priority, _ = strconv.Atoi(fields[15]) self.Nice, _ = strconv.Atoi(fields[16]) self.Processor, _ = strconv.Atoi(fields[36]) return nil }
func getcityname(city string) string { if strings.Contains(city, "县") { citys = strings.SplitAfterN(city, "市", 2)[1] } if strings.Contains(city, "市") { if strings.Count(city, "市") >= 2 { citys = strings.SplitAfterN(city, "市", 2)[1] } else { citys = strings.SplitAfterN(city, "省", 2)[1] } } if strings.Contains(city, "区") { if strings.Count(city, "区") >= 2 { citys = strings.SplitAfterN(city, "区", 2)[1] } else { if strings.Contains(city, "特别行政区") { citys, _ = SubstringIndex(city, "特别行政区") } if strings.Contains(city, "市") { citys = strings.SplitAfterN(city, "市", 2)[1] } } } return "" }
func main() { s1 := "foo!bar" s2 := "boo!bar!bazzz" s3 := "doo" fmt.Printf("%v\n", strings.SplitAfterN(s1, "!", 2)) fmt.Printf("%v\n", strings.SplitAfterN(s2, "!", 2)) fmt.Printf("%v\n", strings.SplitAfterN(s3, "!", 2)) fmt.Printf("%d\n", len(strings.SplitAfterN(s3, "!", 2))) }
func setConfigVal(val string, l string) { // Set the config variable base on val in the line 1 // Config values are expected to be of the form foo="bar" switch val { case "tf_url": v := strings.SplitAfterN(l, "=", 2) tf_url = strings.Replace(strings.TrimSpace(v[1]), "\"", "", -1) case "apikey": v := strings.SplitAfterN(l, "=", 2) apikey = strings.Replace(strings.TrimSpace(v[1]), "\"", "", -1) } }
func (self *ProcState) Get(pid int) error { contents, err := readProcFile(pid, "stat") if err != nil { return err } headerAndStats := strings.SplitAfterN(string(contents), ")", 2) pidAndName := headerAndStats[0] fields := strings.Fields(headerAndStats[1]) name := strings.SplitAfterN(pidAndName, " ", 2)[1] if name[0] == '(' && name[len(name)-1] == ')' { self.Name = name[1 : len(name)-1] // strip ()'s } else { return errors.New(fmt.Sprintf("Malformed process stats for pid %d", pid)) } self.State = RunState(fields[0][0]) self.Ppid, _ = strconv.Atoi(fields[1]) self.Pgid, _ = strconv.Atoi(fields[2]) self.Tty, _ = strconv.Atoi(fields[4]) self.Priority, _ = strconv.Atoi(fields[15]) self.Nice, _ = strconv.Atoi(fields[16]) self.Processor, _ = strconv.Atoi(fields[36]) // Read /proc/[pid]/status to get the uid, then lookup uid to get username. status, err := getProcStatus(pid) if err != nil { return fmt.Errorf("failed to read process status for pid %d. %v", pid, err) } uids, err := getUIDs(status) if err != nil { return fmt.Errorf("failed to read process status for pid %d. %v", pid, err) } user, err := user.LookupId(uids[0]) if err == nil { self.Username = user.Username } else { self.Username = uids[0] } return nil }
func HandleTcpReading(channel ssh.Channel, term *terminal.Terminal, http map[string]string) { defer channel.Close() for { line, err := term.ReadLine() if err != nil { break } logfile.Println(line) if line == "" { channel.Close() return } if strings.Contains(line, ":") { kv := strings.SplitAfterN(line, ":", 2) http[kv[0]] = strings.TrimSpace(kv[1]) } else { kv := strings.Fields(line) if kv[0] == "POST" || kv[0] == "GET" { http["Method"] = kv[0] http["URI"] = kv[1] } else { http[kv[0]] = kv[1] } } } }
func parseCommand(rawCommand string) (*Command, error) { parsed := strings.SplitAfterN(rawCommand, " ", 2) parsed[0] = strings.TrimSpace(parsed[0]) command := new(Command) switch parsed[0] { case "USE": dataLength := len([]rune(parsed[1])) if dataLength == 0 { return nil, errors.New("The command USE must have an valid queue name") } command.Command = Use command.Data = parsed[1] case "PUT": dataLength := len([]rune(parsed[1])) if dataLength == 0 { return nil, errors.New("The command PUT cannot save an empty item") } command.Command = Put command.Data = parsed[1] case "GET": command.Command = Get case "PURGE": command.Command = Purge case "QUIT": command.Command = Quit default: return nil, errors.New("Invalid command") } return command, nil }
func parseScalaDocFile(f string, r io.Reader) []shared.Namespace { d := xml.NewDecoder(r) var t xml.Token var err error namespaces := []shared.Namespace{} for ; err == nil; t, err = d.Token() { if se, ok := t.(xml.StartElement); ok { switch { case se.Name.Local == "a" && hasAttr(se, "title", "Permalink"): // <a href="../../index.html#scala.collection.TraversableLike@WithFilterextendsFilterMonadic[A,Repr]" // title="Permalink" // target="_top"> // <img src="../../../lib/permalink.png" alt="Permalink" /> // </a> href, err := attr(se, "href") if err == nil { subs := strings.SplitAfterN(href, "#", 2) if len(subs) > 1 { n, err := parseNamespace(f, subs[0], subs[1]) if err != nil { log.Println(err) } else { namespaces = append(namespaces, n) } } } } } } return namespaces }
// Use firstTime=true if this is the first time calling printMongoOutput() after startMongo() func (sh *QShell) printMongoOutput(firstTime bool) error { maxBytesReadAtOnce := 10000 buf := make([]byte, maxBytesReadAtOnce) var recBytes []byte for { n, err := sh.mongoStateHolder.getPty().Read(buf) if err != nil && err != io.EOF { return err } if n == maxBytesReadAtOnce { if err := sh.print("\nWARNING: Probably missing some of mongo's output"); err != nil { return err } } recBytes = append(recBytes, buf[:n]...) rec := string(recBytes) // Very fast in Golang // Terrible hacks to determine when mongo is finished printing output if strings.Count(rec, "\r\n> ") == 2 || firstTime && strings.Count(rec, "\r\n> ") == 1 { // Remove the "\r\n> " that mongo outputs msg := strings.TrimSuffix(strings.TrimSpace(strings.Replace(rec, "\r\n> ", "\n", -1)), "\n") if !firstTime { // Remove the first line of mongo output, which is an echo of the user's input msg = strings.SplitAfterN(msg, "\n", 2)[1] } if firstTime { msg += "\n" } if err := sh.print(msg); err != nil { return err } break } } return nil }
// WorkLock - Acquire consul for cluster to aquire right to schedule tasks. func WorkLock() (err error) { clusterID := os.Getenv("RDPGD_CLUSTER") if clusterID == "" { matrixName := os.Getenv(`RDPGD_MATRIX`) matrixNameSplit := strings.SplitAfterN(matrixName, `-`, -1) matrixColumn := os.Getenv(`RDPGD_MATRIX_COLUMN`) for i := 0; i < len(matrixNameSplit)-1; i++ { clusterID = clusterID + matrixNameSplit[i] } clusterID = clusterID + "c" + matrixColumn } key := fmt.Sprintf("rdpg/%s/tasks/work/lock", clusterID) client, _ := consulapi.NewClient(consulapi.DefaultConfig()) workLock, err = client.LockKey(key) if err != nil { log.Error(fmt.Sprintf("tasks.WorkLock() Error Locking Work Key %s ! %s", key, err)) return } workLockCh, err = workLock.Lock(nil) // Acquire Consul K/V Lock if err != nil { log.Error(fmt.Sprintf("tasks.WorkLock() Error Acquiring Work Key lock %s ! %s", key, err)) return } if workLockCh == nil { err = fmt.Errorf(`tasks.WorkLock() Work Lock not acquired`) } return }
func GetCommand(body, from, dir string) (*exec.Cmd, error) { split := strings.SplitAfterN(body, " ", 2) cmd := strings.TrimSpace(split[0]) if !cmd_validator.MatchString(cmd) { return nil, fmt.Errorf("Bad command \"%s\"", cmd) } var ( info os.FileInfo err error ) path := dir + Strip(cmd[1:]) if info, err = os.Stat(path); err != nil { return nil, err } if info.IsDir() || info.Mode()&0111 == 0 { return nil, fmt.Errorf("\"%s\" isn't executable", path) } args := []string{Strip(GetNick(from)), strconv.FormatBool(in(admin, from))} if len(split) > 1 { args = append(args, Strip(split[1])) } return exec.Command(path, args...), nil }
func (d *Directory) AddObject(obj *storage.Object) error { name := strings.TrimPrefix(obj.Name, d.Prefix) split := strings.SplitAfterN(name, "/", 2) // Propagate update time to parent directories, excluding indexes. // Used to detect when indexes should be regenerated. if split[len(split)-1] != "index.html" { objUpdated, err := time.Parse(time.RFC3339Nano, obj.Updated) if err != nil { return err } if d.Updated.Before(objUpdated) { d.Updated = objUpdated } } // Save object locally if it has no slash or only ends in slash if len(split) == 1 || len(split[1]) == 0 { d.Objects[name] = obj return nil } sub, ok := d.SubDirs[split[0]] if !ok { sub = &Directory{ Bucket: d.Bucket, Prefix: d.Prefix + split[0], SubDirs: make(map[string]*Directory), Objects: make(map[string]*storage.Object), } d.SubDirs[split[0]] = sub } return sub.AddObject(obj) }
func FindSauerbraten() string { env := os.Environ() best := "" for i := range env { current := strings.ToLower(env[i]) if strings.HasPrefix(current, "programfiles(x86)=") { best = env[i] break } if strings.HasPrefix(current, "programfiles=") { best = env[i] } } if best == "" { return "" } split := strings.SplitAfterN(best, "=", 2) if len(split) < 2 { return "" } sauerbraten := path.Join(split[1], "Sauerbraten") if futility.DirectoryExists(sauerbraten) { return sauerbraten } return "" }
func EnvValue(env string) string { split := strings.SplitAfterN(env, "=", 2) if len(split) < 2 { return "" } return split[1] }
func main() { s := "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450" var dstr []string = strings.SplitAfterN(s, "", len(s)) var dint [1000]int n0 := 0 n1 := 0 n2 := 0 n3 := 0 n4 := 0 result := 0 for x := 0; x < len(s); x++ { dint[x], _ = strconv.Atoi(dstr[x]) // fmt.Printf("dint[%v] is: %v\n", x, dint[x]) } for i := 0; i < 996; i++ { n0 = dint[i] n1 = dint[i+1] n2 = dint[i+2] n3 = dint[i+3] n4 = dint[i+4] if n0*n1*n2*n3*n4 > result { result = n0 * n1 * n2 * n3 * n4 } } fmt.Printf("Answer is: %v", result) }
// GetLatestInfo gets information about the latest release for the current branch func GetLatestInfo() (*Info, error) { location := fmt.Sprintf("https://%s/%s/info", ReleaseHost, viper.GetString("gitBranch")) resp, err := http.Get(location) if err != nil { return nil, err } if resp.StatusCode != 200 { return nil, fmt.Errorf("Status %d was not OK", resp.StatusCode) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } var info Info for _, line := range strings.Split(string(body), "\n") { infoLine := strings.SplitAfterN(line, " ", 2) if len(infoLine) != 2 { continue } switch strings.TrimSpace(infoLine[0]) { case "version": info.Version = infoLine[1] case "commit": info.Commit = infoLine[1] case "date": if date, err := time.Parse(time.RFC3339, infoLine[1]); err == nil { info.Date = date } } } return &info, nil }
func getGetwayInfo(resultMsg string) Geteway { geteway := Geteway{} lines := strings.Split(resultMsg, "\r\n") for _, line := range lines { //按照第一个冒号分为两个字符串 nameValues := strings.SplitAfterN(line, ":", 2) if len(nameValues) < 2 { continue } switch strings.ToUpper(strings.Trim(strings.Split(nameValues[0], ":")[0], " ")) { case "ST": geteway.ST = nameValues[1] case "CACHE-CONTROL": geteway.Cache = nameValues[1] case "LOCATION": urls := strings.Split(strings.Split(nameValues[1], "//")[1], "/") geteway.Host = urls[0] geteway.DeviceDescUrl = "/" + urls[1] case "SERVER": geteway.GetewayName = nameValues[1] default: } } return geteway }
func init() { pgPort = os.Getenv(`RDPGD_PG_PORT`) if pgPort == `` { pgPort = `7432` } pgPass = os.Getenv(`RDPGD_PG_PASS`) MatrixName = os.Getenv(`RDPGD_MATRIX`) MatrixNameSplit = strings.SplitAfterN(MatrixName, `-`, -1) MatrixColumn = os.Getenv(`RDPGD_MATRIX_COLUMN`) ClusterID = os.Getenv(`RDPGD_CLUSTER`) if ClusterID == "" { for i := 0; i < len(MatrixNameSplit)-1; i++ { ClusterID = ClusterID + MatrixNameSplit[i] } ClusterID = ClusterID + "c" + MatrixColumn } rdpgdAdminPort = os.Getenv(`RDPGD_ADMIN_PORT`) if rdpgdAdminPort == "" { rdpgdAdminPort = "58888" } rdpgdAdminUser = os.Getenv(`RDPGD_ADMIN_USER`) if rdpgdAdminUser == "" { rdpgdAdminUser = "******" } rdpgdAdminPass = os.Getenv(`RDPGD_ADMIN_PASS`) if rdpgdAdminPass == "" { rdpgdAdminPass = "******" } }
func main() { api := GetApi() v := url.Values{} v.Set("count", "200") var sourceText bytes.Buffer var verb string re := regexp.MustCompile(`@.*?\W`) for { if sourceText.Len() > 24000 { sourceText.Reset() } verb = GetVerb() search_result, err := api.GetSearch("\""+verb+"\" -RT", v) if err != nil { panic(err) } for _, tweet := range search_result.Statuses { sourceText.WriteString(strings.ToLower(tweet.Text)) sourceText.WriteString(" ") } sample := re.ReplaceAllString(sourceText.String(), " ") for i := 0; i < 1200; i++ { sample = strings.SplitAfterN(sample, " ", 2)[1] fmt.Println(markov.Generate(26, 2, sample)) time.Sleep(75000 * time.Microsecond) } } }
/* GetWriteMasterIP returns the write master IP for the service cluster. */ func (s *Service) GetWriteMasterIP() (ip string, err error) { log.Trace(fmt.Sprintf(`services.Service<%s>#GetWriteMaster()`, s.Name)) client, err := consulapi.NewClient(consulapi.DefaultConfig()) if err != nil { log.Error(fmt.Sprintf("services.Service<%s>#GetWriteMaster() ! %s", s.Name, err)) return } catalog := client.Catalog() clusterID := os.Getenv("RDPGD_CLUSTER") if clusterID == "" { matrixName := os.Getenv(`RDPGD_MATRIX`) matrixNameSplit := strings.SplitAfterN(matrixName, `-`, -1) matrixColumn := os.Getenv(`RDPGD_MATRIX_COLUMN`) for i := 0; i < len(matrixNameSplit)-1; i++ { clusterID = clusterID + matrixNameSplit[i] } clusterID = clusterID + "c" + matrixColumn } svcs, _, err := catalog.Service(fmt.Sprintf(`%s-master`, clusterID), "", nil) if err != nil { log.Error(fmt.Sprintf(`services.Service<%s>#GetWriteMaster() ! %s`, s.Name, err)) return } if len(svcs) == 0 { return "", nil } ip = svcs[0].Address return }
// Parse an url and extract referer, it returns a RefererResult. func Parse(uri string) (refResult *RefererResult) { puri, _ := url.Parse(uri) // Split before the first dot ".". parts := strings.SplitAfterN(puri.Host, ".", 2) rhost := "" if len(parts) > 1 { rhost = parts[1] } queries := []string{puri.Host + puri.Path, rhost + puri.Path, puri.Host, rhost} for _, q := range queries { refResult = lookup(puri, q, false) if refResult.Known { return } } if !refResult.Known { for _, q := range queries { refResult = lookup(puri, q, true) if refResult.Known { return } } } return }
func init() { MatrixName = os.Getenv(`RDPGD_MATRIX`) MatrixNameSplit = strings.SplitAfterN(MatrixName, `-`, -1) MatrixColumn = os.Getenv(`RDPGD_MATRIX_COLUMN`) ClusterID = os.Getenv(`RDPGD_CLUSTER`) if ClusterID == "" { for i := 0; i < len(MatrixNameSplit)-1; i++ { ClusterID = ClusterID + MatrixNameSplit[i] } ClusterID = ClusterID + "c" + MatrixColumn } if ClusterID == "" { log.Error(`tasks.Scheduler() RDPGD_CLUSTER not found in environment!!!`) } pbPort = os.Getenv(`RDPGD_PB_PORT`) if pbPort == `` { pbPort = `6432` } pgPass = os.Getenv(`RDPGD_PG_PASS`) pgPort = os.Getenv(`RDPGD_PG_PORT`) ps := os.Getenv(`RDPGD_POOL_SIZE`) if ps == "" { poolSize = 10 } else { p, err := strconv.Atoi(ps) if err != nil { poolSize = 10 } else { poolSize = p } } }
func UseShlex(path string) (map[string]string, error) { bashString, err := inputFromFileToString(path) if err != nil { return nil, err } keyValueArray, err := shlex.Split(bashString) if err != nil { return nil, err } var keyValueMap map[string]string keyValueMap = make(map[string]string) for i := 0; i < len(keyValueArray); i++ { if strings.Contains(keyValueArray[i], "=") { keyValue := strings.SplitAfterN(keyValueArray[i], "=", 2) keyValue[0] = keyValue[0][:len(keyValue[0])-1] if keyValue[0] == strings.ToUpper(keyValue[0]) && keyValue[0] != "" { keyValueMap[keyValue[0]] = keyValue[1] } } } return keyValueMap, nil }
func init() { // Set MyIP variable client, err := consulapi.NewClient(consulapi.DefaultConfig()) if err != nil { log.Error(fmt.Sprintf("config.init() consulapi.NewClient()! %s", err)) } else { agent := client.Agent() info, err := agent.Self() if err != nil { log.Error(fmt.Sprintf("config.init() agent.Self()! %s", err)) } else { MyIP = info["Config"]["AdvertiseAddr"].(string) } } ClusterService = os.Getenv("RDPGD_CLUSTER_SERVICE") //Set up the ClusterID MatrixName := os.Getenv(`RDPGD_MATRIX`) MatrixNameSplit := strings.SplitAfterN(MatrixName, `-`, -1) MatrixColumn := os.Getenv(`RDPGD_MATRIX_COLUMN`) ClusterID = os.Getenv("RDPGD_CLUSTER") if ClusterID == "" { for i := 0; i < len(MatrixNameSplit)-1; i++ { ClusterID = ClusterID + MatrixNameSplit[i] } ClusterID = ClusterID + "c" + MatrixColumn } }
func tokenizeForward(arg string) (string, string, error) { switch arg[0] { case ':': return "", arg[1:], nil case '[': parts := strings.SplitAfterN(arg, "]", 2) if len(parts) != 2 { return "", "", fmt.Errorf("Argument missing closing bracket: %q", arg) } if parts[1][0] == ':' { return parts[0], parts[1][1:], nil } return "", "", fmt.Errorf("Unexpected token: %q", parts[1]) default: parts := strings.SplitN(arg, ":", 2) if len(parts) < 2 { return parts[0], "", nil } return parts[0], parts[1], nil } }
func ParseConfigFile(filepath string) { f, err := os.Open(filepath) if err != nil { fmt.Println("Error opening config file: %s", err) return } defer f.Close() b := bufio.NewReader(f) for { str, err := b.ReadString('\n') if err != nil { break } str = strings.TrimSpace(str) if len(str) > 0 && str[0] != '#' { config_options := strings.SplitAfterN(str, " ", 2) Config[strings.TrimSpace(config_options[0])] = strings.TrimSpace(config_options[1]) } } }
func serviceFQDNFromInstanceFQDN(instance string) string { pieces := strings.SplitAfterN(instance, ".", 2) if len(pieces) != 2 { return "" } return pieces[1] }
func doExec(loc string, cmd string) { var fullpath string if loc == "" { fullpath = root } else { var err error charaddr := strings.SplitAfterN(loc, ",#", 2) fullpath, err = getFullPath(charaddr[1]) if err != nil { fmt.Fprintf(os.Stderr, err.Error()) return } fi, err := os.Stat(fullpath) if err != nil { fmt.Fprintf(os.Stderr, err.Error()) return } if !fi.IsDir() { fullpath, _ = path.Split(fullpath) } } var args []string = make([]string, 1) args[0] = cmd fds := []*os.File{os.Stdin, os.Stdout, os.Stderr} _, err := os.StartProcess(args[0], args, &os.ProcAttr{Env: os.Environ(), Dir: fullpath, Files: fds}) if err != nil { fmt.Fprintf(os.Stderr, err.Error()) return } return }
func (this *SearchGateway) resolve(result string) { this.upnp.Gateway = &Gateway{} lines := strings.Split(result, "\r\n") for _, line := range lines { //According to a first colon into two strings nameValues := strings.SplitAfterN(line, ":", 2) if len(nameValues) < 2 { continue } switch strings.ToUpper(strings.Trim(strings.Split(nameValues[0], ":")[0], " ")) { case "ST": this.upnp.Gateway.ST = nameValues[1] case "CACHE-CONTROL": this.upnp.Gateway.Cache = nameValues[1] case "LOCATION": urls := strings.Split(strings.Split(nameValues[1], "//")[1], "/") this.upnp.Gateway.Host = urls[0] this.upnp.Gateway.DeviceDescUrl = "/" + urls[1] case "SERVER": this.upnp.Gateway.GatewayName = nameValues[1] default: } } }
// Creates a new *magnetKey structure from a magnet key string "k" or an error. func newMagnetKey(k string) (*magnetKey, error) { r := magnetKey{} // Fail on unsupported key. if len(k) < 2 { return nil, ErrInvalidMagnet } var ok bool if r.Type, ok = KeyTypeMap[k[0:2]]; !ok { return nil, ErrInvalidMagnet } // KeySuplement special case. if r.Type == KeySuplement { b := strings.SplitAfterN(k, ".", 1) if len(b) < 2 { return nil, ErrInvalidMagnet } r.Supl = b[1] } // Get index. c := strings.Split(k, ".") if len(c) > 2 { return nil, ErrInvalidMagnet } if len(c) == 2 { v, err := strconv.Atoi(c[1]) if err != nil { return nil, ErrInvalidMagnet } r.Indx = v } return &r, nil }