Esempio n. 1
0
func do_line(row []string) {
	name := row[0]
	col1, _ := strconv.Atof32(row[1])
	col2, _ := strconv.Atof32(row[2])

	result := col1 * col2

	fmt.Printf("%s is %.02f\n", name, result)
}
Esempio n. 2
0
func (rs *ResultSet) float32(ord int) (value float32, isNull bool) {
	if rs.conn.LogLevel >= LogVerbose {
		defer rs.conn.logExit(rs.conn.logEnter("*ResultSet.float32"))
	}

	isNull = rs.isNull(ord)
	if isNull {
		return
	}

	val := rs.values[ord]

	switch rs.fields[ord].format {
	case textFormat:
		// strconv.Atof32 does not handle NaN
		if string(val) == "NaN" {
			value = float32(math.NaN())
		} else {
			var err os.Error
			value, err = strconv.Atof32(string(val))
			panicIfErr(err)
		}

	case binaryFormat:
		value = math.Float32frombits(binary.BigEndian.Uint32(val))
	}

	return
}
Esempio n. 3
0
// Scan parses the values of the current result row (set using Result.Next)
// into the given arguments.
func (r *Result) Scan(args ...interface{}) os.Error {
	if len(args) != r.ncols {
		return os.NewError(fmt.Sprintf("incorrect argument count for Result.Scan: have %d want %d", len(args), r.ncols))
	}

	for i, v := range args {
		if int(C.PQgetisnull(r.res, C.int(r.currRow), C.int(i))) == 1 {
			continue
		}
		val := C.GoString(C.PQgetvalue(r.res, C.int(r.currRow), C.int(i)))
		switch v := v.(type) {
		case *[]byte:
			if !strings.HasPrefix(val, "\\x") {
				return argErr(i, "[]byte", "invalid byte string format")
			}
			buf, err := hex.DecodeString(val[2:])
			if err != nil {
				return argErr(i, "[]byte", err.String())
			}
			*v = buf
		case *string:
			*v = val
		case *bool:
			*v = val == "t"
		case *int:
			x, err := strconv.Atoi(val)
			if err != nil {
				return argErr(i, "int", err.String())
			}
			*v = x
		case *int64:
			x, err := strconv.Atoi64(val)
			if err != nil {
				return argErr(i, "int64", err.String())
			}
			*v = x
		case *float32:
			x, err := strconv.Atof32(val)
			if err != nil {
				return argErr(i, "float32", err.String())
			}
			*v = x
		case *float64:
			x, err := strconv.Atof64(val)
			if err != nil {
				return argErr(i, "float64", err.String())
			}
			*v = x
		case *time.Time:
			x, _, err := ParseTimestamp(val)
			if err != nil {
				return argErr(i, "time.Time", err.String())
			}
			*v = *x
		default:
			return os.NewError("unsupported type in Scan: " + reflect.TypeOf(v).String())
		}
	}
	return nil
}
Esempio n. 4
0
func AsFloat32(v interface{}) (float32, os.Error) {
	switch value := v.(type) {
	default:
		return 0, os.NewError(fmt.Sprintf("unexpected type: %T", value))
	case int:
		return float32(value), nil
	case int8:
		return float32(value), nil
	case int16:
		return float32(value), nil
	case int32:
		return float32(value), nil
	case int64:
		return float32(value), nil
	case uint:
		return float32(value), nil
	case uint8:
		return float32(value), nil
	case uint16:
		return float32(value), nil
	case uint32:
		return float32(value), nil
	case uint64:
		return float32(value), nil
	case float32:
		return float32(value), nil
	case float64:
		return float32(value), nil
	case string:
		return strconv.Atof32(value)
	}
	panic(fmt.Sprintf("unsupported type: %s", reflect.ValueOf(v).Type().Name()))
}
Esempio n. 5
0
// Get node value as float32
func (this *Node) F32(namespace, name string) float32 {
	if node := rec_SelectNode(this, namespace, name); node != nil && node.Value != "" {
		n, _ := strconv.Atof32(node.Value)
		return n
	}
	return 0
}
Esempio n. 6
0
func NewStatusMessage(s string) *StatusMessage {
	var msg StatusMessage
	progressRe := regexp.MustCompile("\\[download\\][ \t]+([0-9.]+)%[ \t]+of[ \t]+([0-9\\.mkgb]+) at[ \t]+([0-9.gkmb\\-]+)/s[ \t]+eta[ \t]+([0-9\\-]+):([0-9\\-]+)")
	if strings.HasPrefix(s, "[info]") && strings.Index(s, ":") != -1 {
		msg.state = kDownloadingMetadata
	} else if match := progressRe.FindStringSubmatch(strings.ToLower(s)); match != nil {
		msg.state = kDownloadingVideo
		progress, e := strconv.Atof32(match[1])
		if e != nil {
			return nil
		}
		msg.totalBytes, e = SizeStringToInt(match[2])
		if e != nil {
			return nil
		} else {
			minsRemaining, e := strconv.Atoi(match[4])
			if e == nil {
				secsRemaining, e := strconv.Atoi(match[5])
				if e != nil {
					msg.secondsRemaining = uint64(minsRemaining*60 + secsRemaining)
				}
			}

			msg.bytesTransferred =
				uint64(float32(msg.totalBytes) * (progress / 100))
		}
	} else if strings.HasPrefix(s, "[ffmpeg]") && strings.Index(s, ":") != -1 {
		msg.state = kExtractingAudio
	}

	return &msg
}
Esempio n. 7
0
/*
Get the next term from the expression.
If the next input is a number, return it.
If the next input is a parenthesis, find the value of the expression within it.

Returns:
	float32 - the value of the expression starting from the next input
*/
func term() float32 {
	var result float32
	nextInput := nextInput()
	switch nextInput {
	case "(":
		result = sum()
	case ")":
		result += 0
	default:
		if a, b := strconv.Atof32(nextInput); b == nil {
			result = a
		} else {
			if forgivenessCount == 0 {
				if nextInput != "Makefile" {
					fmt.Println(nextInput)
					os.Exit(0)
				} else {
					fmt.Println(phrase[0] + ": syntax error")
					os.Exit(2)
				}
			} else {
				fmt.Println(phrase[0] + ": non-numeric argument")
				os.Exit(2)
			}
		}
		forgivenessCount--
	}
	return result
}
func atof(s []byte) gl.GLfloat {
	f, err := strconv.Atof32(string(s))
	if err != nil {
		panic(err)
	}
	return gl.GLfloat(f)
}
Esempio n. 9
0
//function that fetches the exchange rate from bitcoincharts
func getExchangeRate(c appengine.Context) float32 {

	client := urlfetch.Client(c)
	resp, err := client.Get("http://bitcoincharts.com/t/weighted_prices.json")
	if err != nil {
		log.Print("getExchangeRate err ", err)
		return -1.0
	}

	//decode the json
	dec := json.NewDecoder(resp.Body)

	var f interface{}
	if err2 := dec.Decode(&f); err != nil {
		log.Println("getExchangeRate err2 ", err2)
		return -1.0
	}

	m := f.(map[string]interface{})
	//get the value for USD 24h
	tmptocheck := m["USD"].(map[string]interface{})["24h"]

	switch v := tmptocheck.(type) {
	case string: //if value is string, it converts it
		newValue, _ := strconv.Atof32(tmptocheck.(string))
		//log.Print(newValue)
		return newValue
	default: //otherwise returns a false value (in case no data is fetched or something)
		return -1.0
	}

	return -1.0
}
Esempio n. 10
0
// Get attribute value as float32
func (this *Node) Af32(namespace, name string) float32 {
	if s := this.As(namespace, name); s != "" {
		n, _ := strconv.Atof32(s)
		return n
	}
	return 0
}
Esempio n. 11
0
func (rs *ResultSet) float32(ord int) (value float32, isNull bool) {
	if rs.conn.LogLevel >= LogVerbose {
		defer rs.conn.logExit(rs.conn.logEnter("*ResultSet.float32"))
	}

	isNull = rs.isNull(ord)
	if isNull {
		return
	}

	val := rs.values[ord]

	switch rs.fields[ord].format {
	case textFormat:
		// strconv.Atof32 does not handle "-Infinity" and "Infinity"
		valStr := string(val)
		switch valStr {
		case "-Infinity":
			value = float32(math.Inf(-1))

		case "Infinity":
			value = float32(math.Inf(1))

		default:
			var err os.Error
			value, err = strconv.Atof32(valStr)
			panicIfErr(err)
		}

	case binaryFormat:
		value = math.Float32frombits(binary.BigEndian.Uint32(val))
	}

	return
}
Esempio n. 12
0
func GwtFloat(reg *Registry, strtable, payload []string, partype string, idxv int) (interface{}, int, os.Error) {
	v, err := strconv.Atof32(payload[idxv])
	if err != nil {
		return nil, 1, err
	}

	return v, 1, nil
}
Esempio n. 13
0
func (self *Slider) textToValue() {
	f, err := strconv.Atof32(self.txt)
	if err != nil {
		self.value = 0
	} else {
		self.value = float32(f)
	}
}
Esempio n. 14
0
func (this *Section) F32(key string, defval float32) float32 {
	if v, ok := this.Pairs[key]; ok {
		if f, err := strconv.Atof32(v); err == nil {
			return f
		}
	}
	return defval
}
Esempio n. 15
0
File: nagios.go Progetto: pjjw/ncd
func splitUnits(in string) (val float32, units string, err os.Error) {
	lastnum := strings.LastIndexAny(in, "0123456789.")
	units = ""
	if lastnum == -1 {
		err = os.NewError("non-numeric value")
		return
	}
	if lastnum+1 < len(in) {
		/* pd.Units = proto.String(in[lastnum+1 : len(in)])*/
		units = in[lastnum+1 : len(in)]
		val, err = strconv.Atof32(in[0 : lastnum+1])
		if err != nil {
			return 0, "", err
		}
	} else {
		val, err = strconv.Atof32(in)
	}
	return
}
Esempio n. 16
0
func GetFloatQueryParam(params map[string][]string, name string) (float32, *string) {
	stringValue, err := GetQueryParam(params, name)
	if err != nil {
		return 0.0, err
	}
	result, convErr := strconv.Atof32(*stringValue)
	if convErr != nil {
		message := "Invalid value for parameter " + name + ", expected float"
		return 0.0, &message
	}
	return result, nil
}
Esempio n. 17
0
/**
 * Read row data packet
 */
func (pkt *packetRowData) read(reader *bufio.Reader) (err os.Error) {
	// Read (check if exists) null bit map
	c, err := reader.ReadByte()
	if err != nil {
		return
	}
	if c >= 0x40 && c <= 0x7f {
		pkt.nullBitMap = c
	} else {
		reader.UnreadByte()
	}
	// Allocate memory
	pkt.values = make([]interface{}, len(pkt.fields))
	// Read data for each field
	for i, field := range pkt.fields {
		str, _, err := pkt.readlengthCodedString(reader)
		if err != nil {
			return
		}
		switch field.Type {
		// Strings and everythign else, keep as string
		default:
			pkt.values[i] = str
		// Tiny, small + med int convert into (u)int
		case FIELD_TYPE_TINY, FIELD_TYPE_SHORT, FIELD_TYPE_LONG:
			if field.Flags.Unsigned {
				pkt.values[i], _ = strconv.Atoui(str)
			} else {
				pkt.values[i], _ = strconv.Atoi(str)
			}
		// Big int convert to (u)int64
		case FIELD_TYPE_LONGLONG:
			if field.Flags.Unsigned {
				pkt.values[i], _ = strconv.Atoui64(str)
			} else {
				pkt.values[i], _ = strconv.Atoi64(str)
			}
		// Floats
		case FIELD_TYPE_FLOAT:
			pkt.values[i], _ = strconv.Atof32(str)
		// Double
		case FIELD_TYPE_DOUBLE:
			pkt.values[i], _ = strconv.Atof64(str)
		}
	}
	return
}
Esempio n. 18
0
//function to fetch difficulty from the blockexplorer
func fetchDifficulty(c appengine.Context) float32 {

	client := urlfetch.Client(c)
	resp, err := client.Get("http://blockexplorer.com/q/getdifficulty")
	if err != nil {
		log.Print("fetchDifficulty err %s", err.String())
		//http.Error(w, err.String(), http.StatusInternalServerError)
		return -1.0
	}

	//read response
	bs, _ := ioutil.ReadAll(resp.Body)

	//convert string to float
	difficulty, _ := strconv.Atof32(string(bs))

	return difficulty
}
Esempio n. 19
0
// Action to be performed by each button, returns a handler function
func Input(b *gtk.GtkButton) func() {
	return func() {
		if strings.Index(operators, b.GetLabel()) != -1 {
			val, _ := strconv.Atof32(display.GetText())
			Calculation(val, b.GetLabel())
			display.SetText(GetResult())
			inputMode = false
		} else {
			if inputMode {
				display.SetText(display.GetText() + b.GetLabel())
			} else {
				display.SetText(b.GetLabel())
				inputMode = true
				if result.operator == "=" {
					Reset()
				}
			}
		}
	}
}
Esempio n. 20
0
// Wrapper around strconv.Atof32.  Handles dddddp+ddd (binary exponent)
// itself, passes the rest on to strconv.Atof32.
func myatof32(s string) (f float32, ok bool) {
	a := strings.Split(s, "p", 2)
	if len(a) == 2 {
		n, err := strconv.Atoi(a[0])
		if err != nil {
			println("bad n", a[0])
			return 0, false
		}
		e, err1 := strconv.Atoi(a[1])
		if err1 != nil {
			println("bad p", a[1])
			return 0, false
		}
		return float32(float64(n) * pow2(e)), true
	}
	f1, err1 := strconv.Atof32(s)
	if err1 != nil {
		return 0, false
	}
	return f1, true
}
Esempio n. 21
0
//page that calculates everything for the user
func recalculate(w http.ResponseWriter, r *http.Request) {
	//log.Print("recalculate")

	var Calc Calculations //new calculations instance

	//getting data from request
	Calc.Difficulty, _ = strconv.Atof32(r.FormValue("difficulty"))
	Calc.HashRate, _ = strconv.Atof32(r.FormValue("hashrate"))
	Calc.ExchangeRate, _ = strconv.Atof32(r.FormValue("exchangerate"))
	Calc.DisplayResults = true //set to true to display the second table

	Calc.RigCost, _ = strconv.Atof32(r.FormValue("rigcost"))
	Calc.PowerConsumption, _ = strconv.Atof32(r.FormValue("powerconsumption"))
	Calc.PowerCost, _ = strconv.Atof32(r.FormValue("powercost"))
	Calc.BitcoinsPerBlock, _ = strconv.Atof32(r.FormValue("bitcoinsperblock"))

	Calc = calculateEverything(Calc) //perform aditional calculations

	CalcTemplate.Execute(w, Calc) //display the page
}
Esempio n. 22
0
File: nagios.go Progetto: pjjw/ncd
// parse an individial element of perfdata
func parsePerfDataElement(str string) (pd *PerfData, err os.Error) {
	m := strings.SplitN(str, "=", 2)
	if len(m) < 2 {
		err = os.NewError("no value")
		return nil, err
	}
	name := m[0]
	pd = &PerfData{Name: proto.String(name)}
	n := strings.Split(m[1], ";")
	nf := make([]float32, len(n))
	var units string
	nf[0], units, err = splitUnits(n[0])
	pd.Value = proto.Float32(nf[0])
	if units != "" {
		pd.Units = proto.String(units)
	}
	// convert remaining values to floats if they exist
	for i, v := range n[1:len(n)] {
		nf[i+1], err = strconv.Atof32(v)
		if err != nil {
			return nil, err
		}
	}
	switch {
	case len(nf) >= 5:
		pd.Maximum = proto.Float32(nf[4])
		fallthrough
	case len(nf) >= 4:
		pd.Minimum = proto.Float32(nf[3])
		fallthrough
	case len(nf) >= 3:
		pd.Critical = proto.Float32(nf[2])
		fallthrough
	case len(nf) >= 2:
		pd.Warning = proto.Float32(nf[1])
	}
	return pd, nil
}
Esempio n. 23
0
// t is a struct type.
func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {
	sprop := GetProperties(t)
	for _, prop := range sprop.Prop {
		fi := sprop.tags[prop.Tag]
		ft := t.Field(fi).Type

		// nested messages
		if ft.Kind() == reflect.Ptr && ft.Elem().Kind() == reflect.Struct {
			dm.nested = append(dm.nested, fi)
			continue
		}

		sf := scalarField{
			index: fi,
			kind:  ft.Elem().Kind(),
		}

		// scalar fields without defaults
		if prop.Default == "" {
			dm.scalars = append(dm.scalars, sf)
			continue
		}

		// a scalar field: either *T or []byte
		switch ft.Elem().Kind() {
		case reflect.Bool:
			x, err := strconv.Atob(prop.Default)
			if err != nil {
				log.Printf("proto: bad default bool %q: %v", prop.Default, err)
				continue
			}
			sf.value = x
		case reflect.Float32:
			x, err := strconv.Atof32(prop.Default)
			if err != nil {
				log.Printf("proto: bad default float32 %q: %v", prop.Default, err)
				continue
			}
			sf.value = x
		case reflect.Float64:
			x, err := strconv.Atof64(prop.Default)
			if err != nil {
				log.Printf("proto: bad default float64 %q: %v", prop.Default, err)
				continue
			}
			sf.value = x
		case reflect.Int32:
			x, err := strconv.Atoi64(prop.Default)
			if err != nil {
				log.Printf("proto: bad default int32 %q: %v", prop.Default, err)
				continue
			}
			sf.value = int32(x)
		case reflect.Int64:
			x, err := strconv.Atoi64(prop.Default)
			if err != nil {
				log.Printf("proto: bad default int64 %q: %v", prop.Default, err)
				continue
			}
			sf.value = x
		case reflect.String:
			sf.value = prop.Default
		case reflect.Uint8:
			// []byte (not *uint8)
			sf.value = []byte(prop.Default)
		case reflect.Uint32:
			x, err := strconv.Atoui64(prop.Default)
			if err != nil {
				log.Printf("proto: bad default uint32 %q: %v", prop.Default, err)
				continue
			}
			sf.value = uint32(x)
		case reflect.Uint64:
			x, err := strconv.Atoui64(prop.Default)
			if err != nil {
				log.Printf("proto: bad default uint64 %q: %v", prop.Default, err)
				continue
			}
			sf.value = x
		default:
			log.Printf("proto: unhandled def kind %v", ft.Elem().Kind())
			continue
		}

		dm.scalars = append(dm.scalars, sf)
	}

	return dm
}
Esempio n. 24
0
func filterEdges(c appengine.Context, filename string, chrm string, start int, end int, filters []filter) ([]edge, os.Error) {
	out := make([]edge, 0, 2)

	indexname := fmt.Sprintf("%s.index.%s.json", filename, chrm)
	c.Logf("attempting to load %s from m cache", indexname)

	var indexjson []byte
	switch indexitem, err := memcache.Get(c, indexname); {
	case err == memcache.ErrCacheMiss:
		c.Logf("item not in the cache")

		q := datastore.NewQuery("fileNameToKey").Filter("Filename=", indexname)
		blobs := make([]fileNameToKey, 0, 100)
		if _, err := q.GetAll(c, &blobs); err != nil {
			c.Logf("%v", err)

		}
		if len(blobs) == 0 {
			return out, nil
		}

		c.Logf("blobs[0] is %v %v", blobs[0].Filename, blobs[0].BlobKey)
		blobreader := blobstore.NewReader(c, blobs[0].BlobKey)

		c.Logf("reading blob into indexjson")
		c.Logf("indexjson is %v long before", len(indexjson))
		var readerr os.Error
		if indexjson, readerr = ioutil.ReadAll(blobreader); readerr != nil && readerr != os.EOF {

			c.Logf("error loading json from blob: %v", readerr)
			return out, readerr

		}

		item := &memcache.Item{Key: indexname,
			Value: indexjson,
		}

		// Add the item to the memcache, if the key does not already exist
		if err := memcache.Add(c, item); err == memcache.ErrNotStored {
			c.Logf("item with key %q already exists", item.Key)
		} else if err != nil {
			c.Logf("error adding item: %v", err)
		}

	case err != nil:
		c.Logf("error getting item: %v", err)

	case err == nil:
		c.Logf(" indexjson Loaded from memcache.")
		indexjson = indexitem.Value

	}
	c.Logf("indexjson is %v long after", len(indexjson))
	index := make([]edge, 0, 100)
	if err := json.Unmarshal(indexjson, &index); err != nil {
		c.Logf("error parseingjson: %v", err)
		return out, err
	}

	if len(index) > 0 {
		leftbound := bisect_left(index, start, 0, -1)
		rightbound := bisect_right(index, end, 0, -1)
		for i := leftbound; i < rightbound; i++ {
			e := index[i]
			includeme := false
			if len(filters) > 0 {
				for _, filter := range filters {

					switch min, err := strconv.Atof32(filter.Minscore); {
					case err != nil:
						c.Logf("error parseing filter: %v", err)
					case e.Type == filter.Type && e.Score >= min:
						includeme = true
						break
					}
				}
			} else {
				includeme = true
			}

			if includeme {
				out = append(out, e)
			}
		}
	}

	return out, nil
}
Esempio n. 25
0
File: main.go Progetto: nunb/GoForth
func parse_forth(dat string, DataStack *vector.Vector) {
	L := DataStack.Len()

	switch strings.TrimSpace(string(dat)) {
	case "":
	case "<cr>":
		return
	case "t":
		//check the DataStack size using the popped value
		//	if it passes, then the program continues
		minimum := int(DataStack.Pop().(float32))
		if DataStack.Len() < minimum {
			log.Println("DataStack has not enough minerals (values)")
		}
	case ".":
		log.Println(DataStack.Pop())
	case "0SP":
		DataStack.Cut(0, L)
	case ".S":
		log.Println(DataStack)
	case "2/":
		DataStack.Push(DataStack.Pop().(float32) / 2)
	case "2*":
		DataStack.Push(DataStack.Pop().(float32) * 2)
	case "2-":
		DataStack.Push(DataStack.Pop().(float32) - 2)
	case "2+":
		DataStack.Push(DataStack.Pop().(float32) + 2)
	case "1-":
		DataStack.Push(DataStack.Pop().(float32) - 1)
	case "1+":
		DataStack.Push(DataStack.Pop().(float32) + 1)
	case "DUP":
		DataStack.Push(DataStack.Last())
	case "?DUP":
		if DataStack.Last().(float32) != 0 {
			DataStack.Push(DataStack.Last().(float32))
		}
	case "PICK":
		number := int(DataStack.Pop().(float32))

		if number < L {
			DataStack.Push(DataStack.At(L - 1 - number).(float32))
		} else {
			log.Fatal("picking out of stack not allowed. Stack Length: " + string(L) + ". Selecting: " + string(number) + ".")
			return
		}
	case "TUCK":
		DataStack.Insert(L-2, int(DataStack.Last().(float32)))
	case "NIP":
		DataStack.Delete(L - 2)
	case "2DROP":
		DataStack.Pop()
		DataStack.Pop()
	case "2DUP":
		DataStack.Push(DataStack.At(L - 2))
		DataStack.Push(DataStack.At(DataStack.Len() - 2))
	case "DROP":
		DataStack.Pop()
	case "OVER":
		DataStack.Push(DataStack.At(L - 2))
	case "SWAP":
		l := DataStack.Len()
		DataStack.Swap(l-2, l-1)
	case "*":
		num1 := DataStack.Pop().(float32)
		num2 := DataStack.Pop().(float32)
		DataStack.Push(num1 * num2)
	case "+":
		num1 := DataStack.Pop().(float32)
		num2 := DataStack.Pop().(float32)
		DataStack.Push(num1 + num2)
	case "-":
		num1 := DataStack.Pop().(float32)
		num2 := DataStack.Pop().(float32)
		DataStack.Push(num2 - num1)
	case "/":
		num1 := DataStack.Pop().(float32)
		num2 := DataStack.Pop().(float32)
		DataStack.Push(num2 / num1)
	case "-ROT":
		DataStack.Swap(L-1, L-2)
		DataStack.Swap(L-2, L-3)
	case "ROT":
		DataStack.Swap(L-3, L-2)
		DataStack.Swap(L-2, L-1)
	case "2OVER":
		DataStack.Push(DataStack.At(L - 4))
		DataStack.Push(DataStack.At(DataStack.Len() - 4))
	case "2SWAP":
		DataStack.Swap(L-4, L-2)
		DataStack.Swap(L-3, L-1)
	case "EMIT":
		log.Println(string([]byte{uint8(DataStack.Last().(float32))}))
	default:
		val, ok := strconv.Atof32(dat)

		if ok == nil {
			DataStack.Push(val)
		} else {
			log.Println(ok)
			log.Fatalln("error, unknown token \"" + dat + "\"")
		}
	}
}
Esempio n. 26
0
func (this *Option) Float32() float32 {
	if v, err := strconv.Atof32(this.value); err == nil {
		return v
	}
	return this.defaultval.(float32)
}
Esempio n. 27
0
func (s *Stmt) Scan(args ...interface{}) os.Error {
	n := int(C.sqlite3_column_count(s.stmt))
	if n != len(args) {
		return os.NewError("incorrect argument count")
	}

	for i, v := range args {
		n := C.sqlite3_column_bytes(s.stmt, C.int(i))
		p := C.sqlite3_column_blob(s.stmt, C.int(i))

		if p == nil && n > 0 {
			return os.NewError("got nil blob")
		}

		var data []byte
		if n > 0 {
			// fix(jimt): Must make a copy here. Once Stmt.Finalize() is called,
			// this memory becomes invalid. This was done on purpose according
			// to Russ: http://code.google.com/p/gosqlite/issues/detail?id=1
			// I prefer it with the copy statement here. Behaviour otherwise is
			// misleading and cost me 3 hours of hair pulling.
			data = make([]byte, n)
			copy(data, (*[1<<31 - 1]byte)(unsafe.Pointer(p))[0:n])
		}

		switch v := v.(type) {
		case *[]byte:
			*v = data
		case *string:
			*v = string(data)
		case *bool:
			*v = string(data) == "1"
		case *int:
			x, err := strconv.Atoi(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as int: " + err.String())
			}
			*v = x
		case *int8:
			x, err := strconv.Atoi(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as int: " + err.String())
			}
			*v = int8(x)
		case *int16:
			x, err := strconv.Atoi(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as int: " + err.String())
			}
			*v = int16(x)
		case *int32:
			x, err := strconv.Atoi(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as int: " + err.String())
			}
			*v = int32(x)
		case *int64:
			x, err := strconv.Atoi64(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as int64: " + err.String())
			}
			*v = x
		case *uint:
			x, err := strconv.Atoui(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as int: " + err.String())
			}
			*v = x
		case *uint8:
			x, err := strconv.Atoui(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as int: " + err.String())
			}
			*v = uint8(x)
		case *uint16:
			x, err := strconv.Atoui(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as int: " + err.String())
			}
			*v = uint16(x)
		case *uint32:
			x, err := strconv.Atoui(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as int: " + err.String())
			}
			*v = uint32(x)
		case *uint64:
			x, err := strconv.Atoui64(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as int64: " + err.String())
			}
			*v = x
		case *float:
			x, err := strconv.Atof(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as float64: " + err.String())
			}
			*v = x
		case *float32:
			x, err := strconv.Atof32(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as float64: " + err.String())
			}
			*v = x
		case *float64:
			x, err := strconv.Atof64(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as float64: " + err.String())
			}
			*v = x
		default:
			return os.NewError("unsupported type in Scan: " + reflect.Typeof(v).String())
		}
	}
	return nil
}
Esempio n. 28
0
// literal consumes a literal from d.data[d.off-1:], decoding into the value v.
// The first byte of the literal has been read already
// (that's how the caller knows it's a literal).
func (d *decodeState) literal(v reflect.Value) {
	// All bytes inside literal return scanContinue op code.
	start := d.off - 1
	op := d.scanWhile(scanContinue)

	// Scan read one byte too far; back up.
	d.off--
	d.scan.undo(op)
	item := d.data[start:d.off]

	// Check for unmarshaler.
	wantptr := item[0] == 'n' // null
	unmarshaler, pv := d.indirect(v, wantptr)
	if unmarshaler != nil {
		err := unmarshaler.UnmarshalJSON(item)
		if err != nil {
			d.error(err)
		}
		return
	}
	v = pv

	switch c := item[0]; c {
	case 'n': // null
		switch v.(type) {
		default:
			d.saveError(&UnmarshalTypeError{"null", v.Type()})
		case *reflect.InterfaceValue, *reflect.PtrValue, *reflect.MapValue:
			v.SetValue(nil)
		}

	case 't', 'f': // true, false
		value := c == 't'
		switch v := v.(type) {
		default:
			d.saveError(&UnmarshalTypeError{"bool", v.Type()})
		case *reflect.BoolValue:
			v.Set(value)
		case *reflect.InterfaceValue:
			v.Set(reflect.NewValue(value))
		}

	case '"': // string
		s, ok := unquote(item)
		if !ok {
			d.error(errPhase)
		}
		switch v := v.(type) {
		default:
			d.saveError(&UnmarshalTypeError{"string", v.Type()})
		case *reflect.StringValue:
			v.Set(s)
		case *reflect.InterfaceValue:
			v.Set(reflect.NewValue(s))
		}

	default: // number
		if c != '-' && (c < '0' || c > '9') {
			d.error(errPhase)
		}
		s := string(item)
		switch v := v.(type) {
		default:
			d.error(&UnmarshalTypeError{"number", v.Type()})
		case *reflect.InterfaceValue:
			n, err := strconv.Atof64(s)
			if err != nil {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(reflect.NewValue(n))

		case *reflect.IntValue:
			n, err := strconv.Atoi(s)
			if err != nil {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(n)
		case *reflect.Int8Value:
			n, err := strconv.Atoi(s)
			if err != nil || int(int8(n)) != n {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(int8(n))
		case *reflect.Int16Value:
			n, err := strconv.Atoi(s)
			if err != nil || int(int16(n)) != n {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(int16(n))
		case *reflect.Int32Value:
			n, err := strconv.Atoi(s)
			if err != nil || int(int32(n)) != n {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(int32(n))
		case *reflect.Int64Value:
			n, err := strconv.Atoi64(s)
			if err != nil {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(n)

		case *reflect.UintValue:
			n, err := strconv.Atoui(s)
			if err != nil {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(n)
		case *reflect.Uint8Value:
			n, err := strconv.Atoui(s)
			if err != nil || uint(uint8(n)) != n {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(uint8(n))
		case *reflect.Uint16Value:
			n, err := strconv.Atoui(s)
			if err != nil || uint(uint16(n)) != n {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(uint16(n))
		case *reflect.Uint32Value:
			n, err := strconv.Atoui(s)
			if err != nil || uint(uint32(n)) != n {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(uint32(n))
		case *reflect.Uint64Value:
			n, err := strconv.Atoui64(s)
			if err != nil {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(n)
		case *reflect.UintptrValue:
			n, err := strconv.Atoui64(s)
			if err != nil || uint64(uintptr(n)) != n {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(uintptr(n))

		case *reflect.FloatValue:
			n, err := strconv.Atof(s)
			if err != nil {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(n)
		case *reflect.Float32Value:
			n, err := strconv.Atof32(s)
			if err != nil {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(n)
		case *reflect.Float64Value:
			n, err := strconv.Atof64(s)
			if err != nil {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(n)
		}
	}
}
Esempio n. 29
0
func (g *GetOpt) GetFloat32(o string) (float32, os.Error) {
	return strconv.Atof32(g.Get(o))
}
Esempio n. 30
0
func writeTo(data []byte, val reflect.Value) os.Error {
	s := string(data)
	switch v := val.(type) {
	// if we're writing to an interace value, just set the byte data
	// TODO: should we support writing to a pointer?
	case *reflect.InterfaceValue:
		v.Set(reflect.NewValue(data))
	case *reflect.BoolValue:
		b, err := strconv.Atob(s)
		if err != nil {
			return err
		}
		v.Set(b)
	case *reflect.IntValue:
		i, err := strconv.Atoi(s)
		if err != nil {
			return err
		}
		v.Set(i)
	case *reflect.Int8Value:
		i, err := strconv.Atoi(s)
		if err != nil {
			return err
		}
		v.Set(int8(i))
	case *reflect.Int16Value:
		i, err := strconv.Atoi(s)
		if err != nil {
			return err
		}
		v.Set(int16(i))
	case *reflect.Int32Value:
		i, err := strconv.Atoi(s)
		if err != nil {
			return err
		}
		v.Set(int32(i))
	case *reflect.Int64Value:
		i, err := strconv.Atoi64(s)
		if err != nil {
			return err
		}
		v.Set(i)
	case *reflect.UintValue:
		ui, err := strconv.Atoui(s)
		if err != nil {
			return err
		}
		v.Set(ui)

	case *reflect.Uint8Value:
		ui, err := strconv.Atoui(s)
		if err != nil {
			return err
		}
		v.Set(uint8(ui))
	case *reflect.Uint16Value:
		ui, err := strconv.Atoui(s)
		if err != nil {
			return err
		}
		v.Set(uint16(ui))
	case *reflect.Uint32Value:
		ui, err := strconv.Atoui(s)
		if err != nil {
			return err
		}
		v.Set(uint32(ui))
	case *reflect.Uint64Value:
		ui, err := strconv.Atoui64(s)
		if err != nil {
			return err
		}
		v.Set(ui)
	case *reflect.UintptrValue:
		ui, err := strconv.Atoui64(s)
		if err != nil {
			return err
		}
		v.Set(uintptr(ui))
	case *reflect.FloatValue:
		f, err := strconv.Atof(s)
		if err != nil {
			return err
		}
		v.Set(f)

	case *reflect.Float32Value:
		f, err := strconv.Atof32(s)
		if err != nil {
			return err
		}
		v.Set(f)
	case *reflect.Float64Value:
		f, err := strconv.Atof64(s)
		if err != nil {
			return err
		}
		v.Set(f)

	case *reflect.StringValue:
		v.Set(s)
	case *reflect.SliceValue:
		typ := v.Type().(*reflect.SliceType)
		if _, ok := typ.Elem().(*reflect.Uint8Type); ok {
			v.Set(reflect.NewValue(data).(*reflect.SliceValue))
		}
	}
	return nil
}