Problem with Double, String and Integer conversion - string

Why is the value 4.49504794 ? It should be usdRate:String * sas * ddx:EditText.
I want it to be 0.00000001 * input from edittext (from user) * usdRate:String (1 BTC in USD)
It should be 0.00000001/44950 * x (user_input = x) = (0,00002224694105)
I'm also wanting to limit usdRate:String to only 5 digits total, or somehow remove the last four symbols in the string.
var usdRate:String = (JSONObject(json).getJSONObject("bpi").getJSONObject("USD")["rate"] as String)
val text = usdRate.replace(",", "")
val text2 = text.replace(".", "")
val satosh: Int = text2.toInt()
val sas: Double = 0.00000001
val sas2: Double = sas.toDouble() * satosh.toDouble()
val ddx:EditText = findViewById(R.id.editTextNumber2)
val sasEnty: Double = (ddx.text.toString().toDouble() * sas2)
//1 satoshi value in USD
usdView.text = sasEnty.toString()
//Problem end
Picture of output in application
Output

This code gave me the output I was looking for. When a user input 3 as a value, will it return 0.0013994405520000002
//ex 45,000.01234
var usdRate: String = (JSONObject(json).getJSONObject("bpi").getJSONObject("USD")["rate"] as String).toString()
val usdRateN1: String = usdRate.replace(",", "")
val sastoshi: Double = 0.00000001
var antalSatoshi = sastoshi * ddx.text.toString().toDouble()
var FinalUsdCount = (usdRateN1.toDouble() * antalSatoshi )
Math.round(FinalUsdCount)

Related

wxPython ListCtrl string size

I have a wx.ListCtrl with 2 columns: the second is editable to receive a string. My string is 64Kb in size and it looks like the editable field can only accommodate 32738 characters. How to pass my 64000 bytes?
self.sndList[g] = EditableListCtrl(self.panel, size=(largListE, hautList), style=wx.LC_REPORT | wx.BORDER_SUNKEN, pos=(X,Y+25))
self.sndList[g].InsertColumn(0, '<<< ' + self.vmc.prod[g]['name'] + ' >>>', width=largeurN )
self.sndList[g].InsertColumn(1, u'<<< value >>>', wx.LIST_FORMAT_RIGHT, width=largeurV)
for var in self.vmc.snd_varlist_PDProd[g]:
index = self.sndList[g].InsertStringItem(10000, str(var))
val = str(self.vmc.snd_assem_PDProd[g][var])
if self.vmc.snd_assem_PDProd_type[g][var] == RPSDK_TYPE_REAL:
res=val.find('.')
if res > 0:
val = val[0:res+7]
self.sndList_PrevVal[g].append(val)
self.sndList_LongRefresh[g].append(0)
if val == '':
val = '<EMPTY>'
self.sndList[g].SetStringItem(index, 1, val)

how to extract an integer range from a string

I have a string that contains different ranges and I need to find their value
var str = "some text x = 1..14, y = 2..4 some text"
I used the substringBefore() and substringAfter() methodes to get the x and y but I can't find a way to get the values because the numbers could be one or two digits or even negative numbers.
One approach is to use a regex, e.g.:
val str = "some text x = 1..14, y = 2..4 some text"
val match = Regex("x = (-?\\d+[.][.]-?\\d+).* y = (-?\\d+[.][.]-?\\d+)")
.find(str)
if (match != null)
println("x=${match.groupValues[1]}, y=${match.groupValues[2]}")
// prints: x=1..14, y=2..4
\\d matches a single digit, so \\d+ matches one or more digits; -? matches an optional minus sign; [.] matches a dot; and (…) marks a group that you can then retrieve from the groupValues property. (groupValues[0] is the whole match, so the individual values start from index 1.)
You could easily add extra parens to pull out each number separately, instead of whole ranges.
(You may or may not find this as readable or maintainable as string-manipulation approaches…)
Is this solution fit for you?
val str = "some text x = 1..14, y = 2..4 some text"
val result = str.replace(",", "").split(" ")
var x = ""; var y = ""
for (i in 0..result.count()-1) {
if (result[i] == "x") {
x = result[i+2]
} else if (result[i] == "y") {
y = result[i+2]
}
}
println(x)
println(y)
Using KotlinSpirit library
val rangeParser = object : Grammar<IntRange>() {
private var first: Int = -1
private var last: Int = -1
override val result: IntRange
get() = first..last
override fun defineRule(): Rule<*> {
return int {
first = it
} + ".." + int {
last = it
}
}
}.toRule().compile()
val str = "some text x = 1..14, y = 2..4 some text"
val ranges = rangeParser.findAll(str)
https://github.com/tiksem/KotlinSpirit

Is there a way in Kotlin Multiplatform to format a float to a number of decimal places?

Most of the answers use Java (e.g. String.format) to get the job done, but I need a way to do this purely with Kotlin to support multiplatform programming.
This means not using java.* standard packages.
Say a method like fun Float.toString(numOfDec: Int). I'd like the value to round e.g.:
35.229938f.toString(1) should return 35.2
35.899991f.toString(2) should return 35.90
If you want to return a float, but only to remove the trailing decimals use this:
fun Float.roundToDecimals(decimals: Int): Float {
var dotAt = 1
repeat(decimals) { dotAt *= 10 }
val roundedValue = (this * dotAt).roundToInt()
return (roundedValue / dotAt) + (roundedValue % dotAt).toFloat() / dotAt
}
I created the following Float extension (this should also work with Double):
/**
* Return the float receiver as a string display with numOfDec after the decimal (rounded)
* (e.g. 35.72 with numOfDec = 1 will be 35.7, 35.78 with numOfDec = 2 will be 35.80)
*
* #param numOfDec number of decimal places to show (receiver is rounded to that number)
* #return the String representation of the receiver up to numOfDec decimal places
*/
fun Float.toString(numOfDec: Int): String {
val integerDigits = this.toInt()
val floatDigits = ((this - integerDigits) * 10f.pow(numOfDec)).roundToInt()
return "${integerDigits}.${floatDigits}"
}
Use this in your scenario
try {
if (!TextUtils.isDigitsOnly(st)) {
val rounded = Math.round(st.toFloat())
val toHex = BigInteger(rounded.toString(), 10)
val t = toHex.toString(16)
t.toString()
} else {
val toHex = BigInteger(st, 10)
val t = toHex.toString(16)
t.toString()
}
} catch (e: NumberFormatException) {
error
}

Convert 3 output to one input at NODE-RED

Question is about Node-RED for raspberry pi 3. I have 3 input that give acceleration of X,Y,Z axis. I want to make one output from these 3 inputs. For this , I use √X^2+Y^2+Z^2 formula. According to my function my output is still 3 piece and giving NaN output when i debug. What should i do in Acc to Freq function
Here is my collecting X,Y,Z info from my sql.
var str = msg.payload;
str = str[0]['IX']; // Choose last data from IX column
a = str * 10; // Scaling the value
msg.payload = a
return msg;
var str = msg.payload;
str = str[0]['IY']; // Choose last data from IY column
b = str * 10; // Scaling the value
msg.payload = b
return msg;
var str = msg.payload;
str = str[0]['IZ']; // Choose last data from IZ column
c = str * 10; // Scaling the value
msg.payload = c
return msg;
And the function that i m try to calculate one output ( Acc to Freq )
var str = msg.payload;
var a;
var b;
var c;
str = Math.pow(a^2+b^2+c^2);
d = str * 10;
msg.payload = d;
return msg;
The point to remember is that a function node runs every time a message arrives, if you send it 3 separate messages then it will run 3 times. Also each function node is totally independent of all others, you can't declare a variable in one and use it in another (well there is something called the Context, but that's not particularly useful here)
You've not actually shown your flow so we are going to have to guess a little here, but you imply that all the starting values are coming from a single SQL query that returns multiple columns. If this is the case then you have 2 options.
Just do all the calculations in one place e.g. one function node with the following:
var str = msg.payload;
var strA = str[0]['IX']; // Choose last data from IX column
var a = strA * 10; // Scaling the value
var strB = str[0]['IY']; // Choose last data from IY column
var b = strB * 10; // Scaling the value
var strC = str[0]['IZ']; // Choose last data from IZ column
var c = strC * 10; // Scaling the value
var strC = Math.pow(a^2+b^2+c^2);
var d = strC * 10;
msg.payload = d;
return msg;
You can run the output of your current 3 function nodes into a Join node set to collect 3 values. This will generate a new msg object with a payload containing an array of the 3 values. You can then modify your final function node as follows:
var a = msg.payload[0];
var b = msg.payload[1];
var c = msg.payload[2];
var d = Math.pow(a^2+b^2+c^2) * 10 ;
msg.payload = d;
return msg;

Spark reduce by

I have streaming data coming as follows
id, date, value
i1, 12-01-2016, 10
i2, 12-02-2016, 20
i1, 12-01-2016, 30
i2, 12-05-2016, 40
Want to reduce by id to get aggregate value info by date like
output required from rdd is for a given id and list(days 365)
I have to put the value in the list position based on day of year like 12-01-2016 is 336 and as there are two instances for device i1 with same date they should be aggregated
id, List [0|1|2|3|... |336| 337| |340| |365]
i1, |10+30| - this goes to 336 position
i2, 20 40 -- this goes to 337 and 340 position
Please guide the reduce or group by transformation to do this.
I'll provide you the basic code snippet with few assumptions as you haven't specified about the language, data source or data format.
JavaDStream<String> lineStream = //Your data source for stream
JavaPairDStream<String, Long> firstReduce = lineStream.mapToPair(line -> {
String[] fields = line.split(",");
String idDate = fields[0] + fields[1];
Long value = Long.valueOf(fields[2]);
return new Tuple2<String, Long>(idDate, value);
}).reduceByKey((v1, v2) -> {
return (v1+v2);
});
firstReduce.map(idDateValueTuple -> {
String idDate = idDateValueTuple._1();
Long valueSum = idDateValueTuple._2();
String id = idDate.split(",")[0];
String date = idDate.split(",")[];
//TODO parse date and put the sumValue in array as you wish
}
Can only reach this far. Am not sure how to add each element of an array in the final step. Hope this helps!!!If you get the last step or any alternate way,appreciate if you post it here!!
def getDateDifference(dateStr:String):Int = {
val startDate = "01-01-2016"
val formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy")
val oldDate = LocalDate.parse(startDate, formatter)
val currentDate = dateStr
val newDate = LocalDate.parse(currentDate, formatter)
return newDate.toEpochDay().toInt - oldDate.toEpochDay().toInt
}
def getArray(numberofDays:Int,data:Int):Iterable[Int] = {
val daysArray = new Array[Int](366)
daysArray(numberofDays) = data
return daysArray
}
val idRDD = <read from stream>
val idRDDMap = idRDD.map { rec => ((rec.split(",")(0),rec.split(",")(1)),
(getDateDifference(rec.split(",")(1)),rec.split(",")(2).toInt))}
val idRDDconsiceMap = idRDDMap.map { rec => (rec._1._1,getArray(rec._2._1, rec._2._2)) }
val finalRDD = idRDDconsiceMap.reduceByKey((acc,value)=>(???add each element of the arrays????))

Resources