Beispiel #1
0
func (w *Huobi) checkAccount(a, price, amount string) bool {
	btc, cny := w.get_account_info()

	FPrice, err := strconv.ParseFloat(price, 64)
	if err != nil {
		logger.Debugln("price is not float")
		return false
	}
	FAmount, err := strconv.ParseFloat(amount, 64)
	if err != nil {
		logger.Debugln("amount is not float")
		return false
	}
	if a == "do_buy" {
		if float64(cny) < FPrice*FAmount {
			return false
		}
	} else {
		if float64(btc) < FAmount {
			return false
		}
	}

	return true
}
Beispiel #2
0
func onRequest(w http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	f := &Frame{xrange, yrange}
	{
		v, err := strconv.ParseFloat(req.FormValue("xr"), 64)
		if err == nil {
			f.xrange = v
		}
		v, err = strconv.ParseFloat(req.FormValue("yr"), 64)
		if err == nil {
			f.yrange = v
		}
	}
	i := &Image{width, height}
	{
		v, err := strconv.Atoi(req.FormValue("w"))
		if err == nil {
			i.width = v
		}
		v, err = strconv.Atoi(req.FormValue("h"))
		if err == nil {
			i.height = v
		}
	}
	run(w, f, i)
}
Beispiel #3
0
func doRow0(top *Top, line string) {

	rexp := regexp.MustCompile(`top[\s\-0-9:]+up([:0-9A-z,\s]+?)([0-9] user.*)`)
	matches := rexp.FindStringSubmatch(line)
	if len(matches) != 3 {
		return
	}

	top.Uptime = strings.Trim(matches[1], " ,")

	ls := strings.Split(matches[2], ",")
	if len(ls) != 4 {
		return
	}
	// users
	ls[0] = strings.TrimSpace(ls[0])
	top.Users, _ = strconv.Atoi(strings.Split(ls[0], " ")[0])
	// load avgs
	// 5
	if i := strings.Index(ls[1], "load average:"); i > -1 {
		ls[1] = strings.TrimSpace(ls[1][i+13:])
		top.LoadAvg5, _ = strconv.ParseFloat(ls[1], 64)
	}
	// 10
	top.LoadAvg10, _ = strconv.ParseFloat(strings.TrimSpace(ls[2]), 64)
	// 15
	top.LoadAvg15, _ = strconv.ParseFloat(strings.TrimSpace(ls[3]), 64)
}
Beispiel #4
0
func (pfs *ProcFS) Get(k string) {
	var uf = path.Join(procfsdir, "uptime")
	switch k {
	case PROCFS_SELF:
		var selfdir = path.Join(procfsdir, "self")
		if !exists(selfdir) {
			return
		}
		fi, _ := os.Readlink(selfdir)
		pfs.Self = fi
	case PROCFS_UPTIME:
		str, err := ioutil.ReadFile(uf)
		if err == nil {
			ss := strings.Fields(string(str))
			if len(ss) >= 2 {
				it, _ := strconv.ParseFloat(ss[0], 64)
				pfs.Uptime = int(it)
			}
		}
	case PROCFS_IDLETIME:
		str, err := ioutil.ReadFile(uf)
		if err == nil {
			ss := strings.Fields(string(str))
			if len(ss) >= 2 {
				it, _ := strconv.ParseFloat(ss[1], 64)
				pfs.Idletime = int(it)
			}
		}
	case PROCFS_MOUNTS:
		pfs.Mounts = getMounts(path.Join(procfsdir, "mounts"))
	}
}
Beispiel #5
0
func transform(extractChannel, transformChannel chan *Order) {
	f, _ := os.Open("./../productList.txt")
	defer f.Close()
	r := csv.NewReader(f)

	records, _ := r.ReadAll()

	productList := make(map[string]*Product)

	for _, record := range records {
		product := new(Product)
		product.PartNumber = record[0]
		product.UnitCost, _ = strconv.ParseFloat(record[1], 64)
		product.UnitPrice, _ = strconv.ParseFloat(record[2], 64)
		productList[product.PartNumber] = product
	}

	for o := range extractChannel {
		time.Sleep(3 * time.Millisecond)
		o.UnitCost = productList[o.PartNumber].UnitCost
		o.UnitPrice = productList[o.PartNumber].UnitPrice
		transformChannel <- o
	}

	close(transformChannel)

}
Beispiel #6
0
func CoerceFloat(v interface{}) (float64, error) {
	switch val := v.(type) {
	case int:
		return float64(val), nil
	case int32:
		return float64(val), nil
	case int64:
		return float64(val), nil
	case uint32:
		return float64(val), nil
	case uint64:
		return float64(val), nil
	case float64:
		return val, nil
	case string:
		if len(val) > 0 {
			if iv, err := strconv.ParseFloat(val, 64); err == nil {
				return iv, nil
			}
		}
	case []byte:
		if len(val) > 0 {
			if iv, err := strconv.ParseFloat(string(val), 64); err == nil {
				return iv, nil
			}
		}
	case json.RawMessage:
		if len(val) > 0 {
			if iv, err := strconv.ParseFloat(string(val), 64); err == nil {
				return iv, nil
			}
		}
	}
	return 0, fmt.Errorf("Could not Coerce Value: %v", v)
}
Beispiel #7
0
func (qs *QuerySplitter) splitBoundariesFloatColumn(pkMinMax *sqltypes.Result) ([]sqltypes.Value, error) {
	boundaries := []sqltypes.Value{}
	if pkMinMax == nil || len(pkMinMax.Rows) != 1 || pkMinMax.Rows[0][0].IsNull() || pkMinMax.Rows[0][1].IsNull() {
		return boundaries, nil
	}
	min, err := strconv.ParseFloat(pkMinMax.Rows[0][0].String(), 64)
	if err != nil {
		return nil, err
	}
	max, err := strconv.ParseFloat(pkMinMax.Rows[0][1].String(), 64)
	if err != nil {
		return nil, err
	}
	interval := (max - min) / float64(qs.splitCount)
	if interval == 0 {
		return nil, err
	}
	qs.rowCount = int64(interval)
	for i := 1; i < int(qs.splitCount); i++ {
		boundary := min + interval*float64(i)
		v, err := sqltypes.BuildValue(boundary)
		if err != nil {
			return nil, err
		}
		boundaries = append(boundaries, v)
	}
	return boundaries, nil
}
func main() {
	csvfile, err := os.Open("rosalind_ini2.txt")
	if err != nil {
		log.Fatal(err)
	}

	defer csvfile.Close()

	reader := csv.NewReader(csvfile)
	reader.Comma = ' '
	reader.FieldsPerRecord = 2

	records, err := reader.ReadAll()
	if err != nil {
		log.Fatal(err)
	}

	for _, record := range records {
		a, err := strconv.ParseFloat(record[0], 64)
		if err != nil {
			log.Fatal(err)
		}

		b, err := strconv.ParseFloat(record[1], 64)
		if err != nil {
			log.Fatal(err)
		}

		result := (a * a) + (b * b)
		fmt.Printf("%f\n", result)
		return
	}
}
Beispiel #9
0
// Get location (name, lat and lng)
// via NUS Web
func getLocationInfoNUS(query string) ([]LocationInfo, error) {
	url := fmt.Sprintf("http://map.nus.edu.sg/index.php/search/by/%s", query)
	doc, err := goquery.NewDocument(url)
	if err != nil {
		return nil, err
	}

	var locations []LocationInfo

	s := doc.Find("#search_list a[href=\"javascript:void(0)\"]").First()

	onclick, _ := s.Attr("onclick")
	regex := regexp.MustCompile("long=([0-9\\.]+?)&lat=([0-9\\.]+?)'")
	matches := regex.FindAllStringSubmatch(onclick, -1)

	if len(matches) == 0 || len(matches[0]) != 3 {
		return nil, fmt.Errorf("Can't find lat and lng from query: %s", query)
	}

	x, _ := strconv.ParseFloat(matches[0][1], 64)
	y, _ := strconv.ParseFloat(matches[0][2], 64)

	location := LocationInfo{
		Name: s.Text(),
		Lng:  x,
		Lat:  y,
	}

	locations = append(locations, location)

	return locations, nil
}
Beispiel #10
0
func SaveBehaviorLog(orgcode string, data []map[string]string) {
	log.Println("SaveLog")
	session := db.GetDBSession()
	defer db.ReleaseDBSession(session)
	c := session.DB("person_info").C("behavior_log")
	bulk := c.Bulk()
	for i, fields := range data {
		log.Println(i, fields)
		mac := fields["MAC"]
		mac = filterMac(mac)
		IpInt, err4 := strconv.ParseInt(fields["DST_IP"], 10, 64)
		Ip := inet_ntoa(IpInt)
		port := fields["DST_PORT"]
		lng, err1 := strconv.ParseFloat(fields["LONGITUDE"], 64)
		lat, err2 := strconv.ParseFloat(fields["LATITUDE"], 64)
		if orgcode == "779852855" && err2 != nil {
			lat, err2 = strconv.ParseFloat(fields["LAITTUDE"], 64)
		}
		time, err3 := strconv.Atoi(fields["CAPTURE_TIME"])
		if err1 != nil || err2 != nil || err3 != nil || err4 != nil {
			log.Println("error:", err1, err2, err3, err4)
			continue
		}
		lng, lat = data_file.Bd09towgs84(lng, lat)
		if saveToDB {
			//c.Insert(fields)
			bulk.Insert(bson.M{"mac": mac, "dst_ip": Ip, "dst_port": port, "longitude": lng, "latitude": lat, "org_code": orgcode, "time": uint32(time)})
		}
	}
	bulk.Run()
}
// UnmarshalJSON implements json.Unmarshaller on AccountInfo.
// This is needed because the Vultr API is inconsistent in it's JSON responses for account info.
// Some fields can change type, from JSON number to JSON string and vice-versa.
func (a *AccountInfo) UnmarshalJSON(data []byte) (err error) {
	if a == nil {
		*a = AccountInfo{}
	}

	var fields map[string]interface{}
	if err := json.Unmarshal(data, &fields); err != nil {
		return err
	}

	b, err := strconv.ParseFloat(fmt.Sprintf("%v", fields["balance"]), 64)
	if err != nil {
		return err
	}
	a.Balance = b

	pc, err := strconv.ParseFloat(fmt.Sprintf("%v", fields["pending_charges"]), 64)
	if err != nil {
		return err
	}
	a.PendingCharges = pc

	lpa, err := strconv.ParseFloat(fmt.Sprintf("%v", fields["last_payment_amount"]), 64)
	if err != nil {
		return err
	}
	a.LastPaymentAmount = lpa

	a.LastPaymentDate = fmt.Sprintf("%v", fields["last_payment_date"])

	return
}
Beispiel #12
0
func SaveTraceInfo(orgcode string, data []map[string]string) {
	log.Println("SaveTraceInfo")
	session := db.GetDBSession()
	defer db.ReleaseDBSession(session)
	c := session.DB("detector").C("detector_report")
	bulk := c.Bulk()
	for i, fields := range data {
		//log.Println(fields)
		mac := fields["MAC"]
		mac = filterMac(mac)
		ap_mac := fields["ACCESS_AP_MAC"]
		ap_mac = filterMac(ap_mac)
		lng, err1 := strconv.ParseFloat(fields["COLLECTION_EQUIPMENT_LONGITUDE"], 64)
		lat, err2 := strconv.ParseFloat(fields["COLLECTION_EQUIPMENT_LATITUDE"], 64)
		time, err3 := strconv.Atoi(fields["CAPTURE_TIME"])
		if err1 != nil || err2 != nil || err3 != nil {
			continue
		}
		lng, lat = data_file.Bd09towgs84(lng, lat)
		log.Println(i, ": mac", mac, "ap_mac", ap_mac, "lng", lng, "lat", lat, "time", time)

		if saveToDB {
			bulk.Insert(bson.M{"ap_mac": ap_mac, "device_mac": mac, "longitude": lng, "latitude": lat, "org_code": orgcode, "time": uint32(time)})
		}
	}
	bulk.Run()
}
Beispiel #13
0
func (sm *statMonitor) Monitor(packets <-chan StatPacket, wg *sync.WaitGroup) {
	var s StatPacket
	var floatValue float64
	var intValue int

	t := time.Tick(time.Duration(sm.flushInterval) * time.Second)
	ok := true
	for ok {
		select {
		case <-t:
			sm.Flush()
		case s, ok = <-packets:
			if !ok {
				sm.Flush()
				break
			}
			switch s.Modifier {
			case "ms":
				floatValue, _ = strconv.ParseFloat(s.Value, 64)
				sm.timers[s.Bucket] = append(sm.timers[s.Bucket], floatValue)
			case "g":
				intValue, _ = strconv.Atoi(s.Value)
				sm.gauges[s.Bucket] += intValue
			default:
				floatValue, _ = strconv.ParseFloat(s.Value, 32)
				sm.counters[s.Bucket] += int(float32(floatValue) * (1 / s.Sampling))
			}
		}
	}
	log.Println("StatsdMonitor for input stopped: ", sm.ir.Name())
	wg.Done()
}
Beispiel #14
0
func (s *StatsdInput) handleMessage(message []byte) {
	var packet StatPacket
	var value string
	st := sanitizeRegexp.ReplaceAllString(string(message), "")
	for _, item := range packetRegexp.FindAllStringSubmatch(st, -1) {
		value = item[2]
		if item[3] == "ms" {
			_, err := strconv.ParseFloat(item[2], 32)
			if err != nil {
				value = "0"
			}
		}

		sampleRate, err := strconv.ParseFloat(item[5], 32)
		if err != nil {
			sampleRate = 1
		}

		packet.Bucket = item[1]
		packet.Value = value
		packet.Modifier = item[3]
		packet.Sampling = float32(sampleRate)
		s.Packet <- packet
	}
}
Beispiel #15
0
Datei: scan.go Projekt: vsayer/go
// convertFloat converts the string to a float64value.
func (s *ss) convertFloat(str string, n int) float64 {
	if p := indexRune(str, 'p'); p >= 0 {
		// Atof doesn't handle power-of-2 exponents,
		// but they're easy to evaluate.
		f, err := strconv.ParseFloat(str[:p], n)
		if err != nil {
			// Put full string into error.
			if e, ok := err.(*strconv.NumError); ok {
				e.Num = str
			}
			s.error(err)
		}
		m, err := strconv.Atoi(str[p+1:])
		if err != nil {
			// Put full string into error.
			if e, ok := err.(*strconv.NumError); ok {
				e.Num = str
			}
			s.error(err)
		}
		return math.Ldexp(f, m)
	}
	f, err := strconv.ParseFloat(str, n)
	if err != nil {
		s.error(err)
	}
	return f
}
Beispiel #16
0
func LoadAvg() (*LoadAvgStat, error) {
	filename := common.HostProc("loadavg")
	line, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}

	values := strings.Fields(string(line))

	load1, err := strconv.ParseFloat(values[0], 64)
	if err != nil {
		return nil, err
	}
	load5, err := strconv.ParseFloat(values[1], 64)
	if err != nil {
		return nil, err
	}
	load15, err := strconv.ParseFloat(values[2], 64)
	if err != nil {
		return nil, err
	}

	ret := &LoadAvgStat{
		Load1:  load1,
		Load5:  load5,
		Load15: load15,
	}

	return ret, nil
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")

	vars := mux.Vars(r)
	lat, latErr := strconv.ParseFloat(vars["lat"], 32)
	if latErr != nil {
		ReturnErrorToClient(w, latErr, "Invalid latitude value. Expecting a floating point number")
		return
	}

	lng, lngErr := strconv.ParseFloat(vars["lng"], 32)
	if lngErr != nil {
		ReturnErrorToClient(w, lngErr, "Invalid longitude value. Expecting a floating point number")
		return
	}

	tracelog.Trace("Lat Value", "main", "Lat is %f", lat)
	tracelog.Trace("Lng Value", "main", "Lng is %f", lng)

	postalCode, postaCodeErr := ReverseGeocodeToPostalCode(lat, lng)
	if postaCodeErr != nil {
		ReturnErrorToClient(w, postaCodeErr, "Error determining zip code from given coordinates")
		return
	}

	tracelog.Trace("Postal Code Value", "main", "Postal Code is %s", postalCode)
	var response = GeocodeResponse{postalCode}

	w.WriteHeader(http.StatusOK)
	var err error
	if err = json.NewEncoder(w).Encode(response); err != nil {
		tracelog.Error(err, "An error occurred while encoding json response", "NearbyHandler")
		panic(err)
	}
}
Beispiel #18
0
func (d *DataPoint) clean() error {
	if err := d.Tags.Clean(); err != nil {
		return fmt.Errorf("cleaning tags for metric %s: %s", d.Metric, err)
	}
	m, err := Clean(d.Metric)
	if err != nil {
		return fmt.Errorf("cleaning metric %s: %s", d.Metric, err)
	}
	if d.Metric != m {
		d.Metric = m
	}
	switch v := d.Value.(type) {
	case string:
		if i, err := strconv.ParseInt(v, 10, 64); err == nil {
			d.Value = i
		} else if f, err := strconv.ParseFloat(v, 64); err == nil {
			d.Value = f
		} else {
			return fmt.Errorf("Unparseable number %v", v)
		}
	case uint64:
		if v > math.MaxInt64 {
			d.Value = float64(v)
		}
	case *big.Int:
		if bigMaxInt64.Cmp(v) < 0 {
			if f, err := strconv.ParseFloat(v.String(), 64); err == nil {
				d.Value = f
			}
		}
	}
	return nil
}
Beispiel #19
0
// parseLatLngs splits up a string of lat:lng points and returns the list of parsed
// entries.
func parseLatLngs(s string) []LatLng {
	pieces := strings.Split(s, ",")
	var lls []LatLng
	for _, piece := range pieces {
		// Skip empty strings.
		if len(strings.TrimSpace(piece)) == 0 {
			continue
		}

		p := strings.Split(strings.TrimSpace(piece), ":")
		if len(p) != 2 {
			panic(fmt.Sprintf("invalid input string for parseLatLngs: %q", piece))
		}

		lat, err := strconv.ParseFloat(p[0], 64)
		if err != nil {
			panic(fmt.Sprintf("invalid float in parseLatLngs: %q, err: %v", p[0], err))
		}

		lng, err := strconv.ParseFloat(p[1], 64)
		if err != nil {
			panic(fmt.Sprintf("invalid float in parseLatLngs: %q, err: %v", p[1], err))
		}

		lls = append(lls, LatLngFromDegrees(lat, lng))
	}
	return lls
}
Beispiel #20
0
// CgroupCPU returnes specified cgroup id CPU status.
// containerid is same as docker id if you use docker.
// If you use container via systemd.slice, you could use
// containerid = docker-<container id>.scope and base=/sys/fs/cgroup/cpuacct/system.slice/
func CgroupCPU(containerid string, base string) (*CPUTimesStat, error) {
	if len(base) == 0 {
		base = "/sys/fs/cgroup/cpuacct/docker"
	}
	path := path.Join(base, containerid, "cpuacct.stat")

	lines, _ := readLines(path)
	// empty containerid means all cgroup
	if len(containerid) == 0 {
		containerid = "all"
	}
	ret := &CPUTimesStat{CPU: containerid}
	for _, line := range lines {
		fields := strings.Split(line, " ")
		if fields[0] == "user" {
			user, err := strconv.ParseFloat(fields[1], 32)
			if err == nil {
				ret.User = float32(user)
			}
		}
		if fields[0] == "system" {
			system, err := strconv.ParseFloat(fields[1], 32)
			if err == nil {
				ret.System = float32(system)
			}
		}
	}

	return ret, nil
}
Beispiel #21
0
func ReadNormals(fileName string) []Vector {
	file, err := os.Open(fileName)
	common.Check(err)
	defer file.Close()

	scanner := bufio.NewScanner(file)
	scanner.Split(bufio.ScanWords)

	var normals []Vector

	for scanner.Scan() {
		x, err := strconv.ParseFloat(scanner.Text(), 64)
		common.Check(err)

		scanner.Scan()
		y, err := strconv.ParseFloat(scanner.Text(), 64)
		common.Check(err)

		scanner.Scan()
		z, err := strconv.ParseFloat(scanner.Text(), 64)
		common.Check(err)

		normals = append(normals, Vector{x, y, z})
	}
	common.Check(scanner.Err())
	return normals
}
Beispiel #22
0
func loadData() []float32 {

	csvfile, err := Asset("www/GDA94_SITE.CSV")
	if err != nil {
		fmt.Println(err)
		return nil
	}
	file := bytes.NewReader(csvfile)

	r := csv.NewReader(file)

	records, err := r.ReadAll()
	if err != nil {
		log.Fatal(err)
	}

	var points []float32

	for _, each := range records {
		lat, _ := strconv.ParseFloat(each[1], 64)
		lng, _ := strconv.ParseFloat(each[2], 64)
		lng = 256 * (0.5 + lng/360)
		lat = project(lat)
		lat32, lng32 := float32(lat), float32(lng)
		points = append(points, lng32)
		points = append(points, lat32)
	}
	return points
}
Beispiel #23
0
// ParseFloat parse value and return Float object
func ParseFloat(arg interface{}) (Float, Error) {
	switch obj := arg.(type) {
	case string:
		i, err := strconv.ParseFloat(obj, 64)
		if err != nil {
			return 0, ErrInvalid
		}
		return Float(i), nil
	case bool:
		if obj {
			return Float(1.0), nil
		}
		return Float(0.0), nil
	case int, int8, int32, int64, uint, uint8, uint32, uint64:
		i, err := strconv.ParseFloat(fmt.Sprintf("%d", obj), 64)
		if err != nil {
			return 0, ErrInvalid
		}
		return Float(i), nil
	case float32, float64, complex64:
		i, err := strconv.ParseFloat(fmt.Sprintf("%f", obj), 64)
		if err != nil {
			return 0, ErrInvalid
		}
		return Float(i), nil
	}
	return 0, nil
}
func PollRequest(w http.ResponseWriter, req *http.Request) {
	var result SiteResponse
	var status SiteStatus
	site, err := LookupSite(req.FormValue("conference"), req.Host, true)
	if err != nil {
		status = SiteStatus{Error: err}
	} else if poll := req.FormValue("poll"); poll != "" {
		status = SiteStatus{Status: poll}
		if x, err := strconv.ParseFloat(req.FormValue("tracker_status_at"), 64); err == nil {
			status.Seq = TrackerSeq(x)
		}
		var timeout time.Duration
		if x, err := strconv.ParseFloat(req.FormValue("timeout"), 64); err == nil {
			timeout = time.Duration(x * float64(time.Millisecond))
		}
		status = <-site.DifferentStatus(status, timeout)
	} else {
		status = <-site.Status()
	}
	if status.Error == nil {
		result.Ok = true
		result.Status = status.Status
		result.Seq = status.Seq
	} else {
		result.Error = status.Error.Error()
	}
	outputResponse(w, result)
}
Beispiel #25
0
func setField(field reflect.Value, defaultVal string) {
	var iface interface{}
	var err error

	switch field.Kind() {
	case reflect.Bool:
		iface, err = strconv.ParseBool(defaultVal)
	case reflect.Int:
		iface, err = strconv.ParseInt(defaultVal, 10, 64)
		iface = int(iface.(int64))
	case reflect.Int8:
		iface, err = strconv.ParseInt(defaultVal, 10, 8)
		iface = int8(iface.(int64))
	case reflect.Int16:
		iface, err = strconv.ParseInt(defaultVal, 10, 16)
		iface = int16(iface.(int64))
	case reflect.Int32:
		iface, err = strconv.ParseInt(defaultVal, 10, 32)
		iface = int32(iface.(int64))
	case reflect.Int64:
		t, err := time.ParseDuration(defaultVal)
		if err == nil {
			iface, err = t, nil
		} else {
			iface, err = strconv.ParseInt(defaultVal, 10, 64)
		}
	case reflect.Uint:
		iface, err = strconv.ParseUint(defaultVal, 10, 64)
		iface = uint(iface.(uint64))
	case reflect.Uint8:
		iface, err = strconv.ParseUint(defaultVal, 10, 8)
		iface = uint8(iface.(uint64))
	case reflect.Uint16:
		iface, err = strconv.ParseUint(defaultVal, 10, 16)
		iface = uint16(iface.(uint64))
	case reflect.Uint32:
		iface, err = strconv.ParseUint(defaultVal, 10, 32)
		iface = uint32(iface.(uint64))
	case reflect.Uint64:
		iface, err = strconv.ParseUint(defaultVal, 10, 64)
	case reflect.Uintptr:
		iface, err = strconv.ParseUint(defaultVal, 10, 64)
		iface = uintptr(iface.(uint64))
	case reflect.Float32:
		iface, err = strconv.ParseFloat(defaultVal, 32)
		iface = float32(iface.(float64))
	case reflect.Float64:
		iface, err = strconv.ParseFloat(defaultVal, 64)
	case reflect.String:
		iface = defaultVal
	default:
		err = errInvalidFieldType
	}

	if err == nil {
		if field.CanSet() {
			field.Set(reflect.ValueOf(iface))
		}
	}
}
Beispiel #26
0
func (m VarnishPlugin) FetchMetrics() (map[string]float64, error) {
	var out []byte
	var err error

	if m.VarnishName == "" {
		out, err = exec.Command(m.VarnishStatPath, "-1").CombinedOutput()
	} else {
		out, err = exec.Command(m.VarnishStatPath, "-1", "-n", m.VarnishName).CombinedOutput()
	}
	if err != nil {
		return nil, errors.New(fmt.Sprintf("%s: %s", err, out))
	}

	lineexp, err := regexp.Compile("^([^ ]+) +(\\d+)")

	stat := make(map[string]float64)
	for _, line := range strings.Split(string(out), "\n") {
		match := lineexp.FindStringSubmatch(line)
		if match == nil {
			continue
		}

		switch match[1] {
		case "client_req", "MAIN.client_req":
			stat["requests"], err = strconv.ParseFloat(match[2], 64)
		case "cache_hit", "MAIN.cache_hit":
			stat["cache_hits"], err = strconv.ParseFloat(match[2], 64)
		}
	}

	return stat, err
}
/*
* Function to format the reply of the PortFolio Stocks
* @params stocks: String which holds values like `GOOGL:0:$656.99,APPL:5:$96.11`
* @params stockdata: Stucture of the YAHOO API
* @return: Formatted string like 'GOOGL:0:+$656.99','APPL:5:+$96.11'
 */
func format_reply_portfoliostocks(stocks string, stockdata *StockData) string {
	var value string
	stock := strings.Split(stocks, ",")
	for i := 0; i < len(stockdata.List.Resources); i++ {
		StockName := stockdata.List.Resources[i].Resource.Fields.Symbol
		for j := 0; j < len(stock); j++ {
			if !strings.EqualFold(StockName, strings.Split(stock[j], ":")[0]) {
				continue
			}
			CurrentMarketValue, _ := strconv.ParseFloat(stockdata.List.Resources[i].Resource.Fields.Price, 64)
			StockPrice, _ := strconv.ParseFloat(strings.Split(stock[j], ":")[2], 64)
			quantity := strings.Split(stock[j], ":")[1]
			value = value + ",'" + StockName + ":" + quantity
			if CurrentMarketValue > StockPrice {
				value = value + ":+$"
			} else if CurrentMarketValue < StockPrice {
				value = value + ":-$"
			} else {
				value = value + ":$"
			}
			value = value + strconv.FormatFloat(CurrentMarketValue, 'f', 2, 64) + "'"
		}
	}
	return strings.Trim(value, ",")
}
Beispiel #28
0
func handleMessage(conn *net.UDPConn, remaddr net.Addr, buf *bytes.Buffer) {
	var packet Packet
	var value string
	var sanitizeRegexp = regexp.MustCompile("[^a-zA-Z0-9\\-_\\.:\\|@]")
	var packetRegexp = regexp.MustCompile("([a-zA-Z0-9_]+):(\\-?[0-9\\.]+)\\|(c|ms)(\\|@([0-9\\.]+))?")
	s := sanitizeRegexp.ReplaceAllString(buf.String(), "")
	for _, item := range packetRegexp.FindAllStringSubmatch(s, -1) {
		value = item[2]
		if item[3] == "ms" {
			_, err := strconv.ParseFloat(item[2], 32)
			if err != nil {
				value = "0"
			}
		}

		sampleRate, err := strconv.ParseFloat(item[5], 32)
		if err != nil {
			sampleRate = 1
		}

		packet.Bucket = item[1]
		packet.Value = value
		packet.Modifier = item[3]
		packet.Sampling = float32(sampleRate)

		if *debug {
			log.Println("Packet: bucket = %s, value = %s, modifier = %s, sampling = %f\n", packet.Bucket, packet.Value, packet.Modifier, packet.Sampling)
		}

		In <- packet
	}
}
Beispiel #29
0
/*
ymin, ymax = 0 - not set
ymin = ymin and != 0 - single range value
ymin != ymax - fixed range
*/
func getYRange(w http.ResponseWriter, r *http.Request) (ymin, ymax float64, ok bool) {
	var err error

	yr := r.URL.Query().Get("yrange")

	switch {
	case yr == "":
		ok = true
	case strings.Contains(yr, `,`):
		y := strings.Split(yr, `,`)
		if len(y) != 2 {
			web.BadRequest(w, r, "invalid yrange query param.")
			return
		}
		ymin, err = strconv.ParseFloat(y[0], 64)
		if err != nil {
			web.BadRequest(w, r, "invalid yrange query param.")
			return
		}
		ymax, err = strconv.ParseFloat(y[1], 64)
		if err != nil {
			web.BadRequest(w, r, "invalid yrange query param.")
			return
		}
	default:
		ymin, err = strconv.ParseFloat(yr, 64)
		if err != nil || ymin <= 0 {
			web.BadRequest(w, r, "invalid yrange query param.")
			return
		}
		ymax = ymin
	}
	ok = true
	return
}
Beispiel #30
0
func setGPOS(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
	rr := new(GPOS)
	rr.Hdr = h
	l := <-c
	if l.length == 0 {
		return rr, nil, ""
	}
	_, e := strconv.ParseFloat(l.token, 64)
	if e != nil || l.err {
		return nil, &ParseError{f, "bad GPOS Longitude", l}, ""
	}
	rr.Longitude = l.token
	<-c // zBlank
	l = <-c
	_, e = strconv.ParseFloat(l.token, 64)
	if e != nil || l.err {
		return nil, &ParseError{f, "bad GPOS Latitude", l}, ""
	}
	rr.Latitude = l.token
	<-c // zBlank
	l = <-c
	_, e = strconv.ParseFloat(l.token, 64)
	if e != nil || l.err {
		return nil, &ParseError{f, "bad GPOS Altitude", l}, ""
	}
	rr.Altitude = l.token
	return rr, nil, ""
}