manipulate the decimal without the main number - reactjs

I am trying to figure out how to fix this problem.
I am greeting my time in this format (15min is 25% of an hour) such as
8.75 mean 8:45
7.50 mean 7:30
I wanted to come out with a simple function to fix that issue But I wasn't successful, any thought?

This function can do it
function calc(number){
const decimal = number.toString().substring(3, 4)
parseInt(decimal)
const result = decimal*60/100
return number.toString()[0] + ':' + result + '0'
}
console.log(calc(8.75))

Related

While adding two numbers getting NAN as output in the react?

When I am trying to add two numbers, I am able to get NaN. If anyone has any advice, any help would be greatly appreciated.
This is my Code:-
var sum = parseInt(label.labellength, 10) + parseInt(label.labely, 10);
console.log("Sum of FrontRight is " + sum );
Output is:-NaN
I tried as following :
Using Number
var sum=Number(label.labellength) + Number(label.labely);
Output is:-NaN
The same issue came to me , try to use || operator and return it, it did the same and it worked for me...
const [contextOverHr,setContextOverHr=useState("")
return (
{Object.values(workHour).reduce((pre,total) => {
let totalNum = pre + total.OverHour
setContextOverHr (totalNum)
return totalNum || 0
},0)
}
)

React state not updating after it returns from function

I have some code that simulates a timer that will look at the start time, store that into localStorage and compare that to Date.now() and will correctly simulate a working timer by updating a state variable that increments on a setInterval every 1 second. It works well even after page reload.
Naturally the timer counts up in milliseconds, so i wrote a function that formats the time into hours:minutes:seconds. The issue now is that the counter, which was updating in real time when unformatted, now that it goes into a function to format, what is returned is correctly formatted but does not increment in real time, i suspect something to do with function not being called again even though the state is being incremented every second.
My question would be is there a way to call the function every time the state changes like a useEffect? Maybe a custom hook?
Here's my code:
const date = new Date()
const [time, setTime] = useState(date.getTime())
//starts timer on button click
function startTimer() {
setStart(true)
localStorage.setItem('startTime', date.getTime())
}
//converts ms time into hours:minutes:seconds
function msToTime(duration) {
let seconds = Math.floor((duration / 1000) % 60),
minutes = Math.floor((duration / (1000 * 60)) % 60),
hours = Math.floor((duration / (1000 * 60 * 60)) % 24)
hours = (hours < 10) ? "0" + hours : hours
minutes = (minutes < 10) ? "0" + minutes : minutes
seconds = (seconds < 10) ? "0" + seconds : seconds
return hours + ":" + minutes + ":" + seconds
}
//the interval that updates time state every second
useEffect(() => {
const timer = setInterval(() => {
setTime(prev => prev+1)
},1000)
return () => {
clearInterval(timer)
}
},[time])
//return the difference between start and time state and formats it
return <h3>{msToTime(Math.abs(+localStorage.getItem('startTime') - time))}</h3>
Everything is fine in your code except that you have overseen one compatibility issue. In your setTime function, the prev argument is in milliseconds, but you're adding only one millisecond to it every second. Change it to the following:
setTime(prev => prev + 1000)
You can also use:
setTime(date.getTime())

When creating a tensor with an array of timestamps, the numbers are incorrect

Looking for some kind of solution to this issue:
trying to create a tensor from an array of timestamps
[
1612892067115,
],
but here is what happens
tf.tensor([1612892067115]).arraySync()
> [ 1612892078080 ]
as you can see, the result is incorrect.
Somebody pointed out, I may need to use the datatype int64, but this doesn't seem to exist in tfjs 😭
I have also tried to divide my timestamp to a small float, but I get a similar result
tf.tensor([1.612892067115, 1.612892068341]).arraySync()
[ 1.6128920316696167, 1.6128920316696167 ]
If you know a way to work around using timestamps in a tensor, please help :)
:edit:
As an attempted workaround, I tried to remove my year, month, and date from my timestamp
Here are my subsequent input values:
[
56969701,
56969685,
56969669,
56969646,
56969607,
56969602
]
and their outputs:
[
56969700,
56969684,
56969668,
56969648,
56969608,
56969600
]
as you can see, they are still incorrect, and should be well within the acceptable range
found a solution that worked for me:
Since I only require a subset of the timestamp (just the date / hour / minute / second / ms) for my purposes, I simply truncate out the year / month:
export const subts = (ts: number) => {
// a sub timestamp which can be used over the period of a month
const yearMonth = +new Date(new Date().getFullYear(), new Date().getMonth())
return ts - yearMonth
}
then I can use this with:
subTimestamps = timestamps.map(ts => subts(ts))
const x_vals = tf.tensor(subTimestamps, [subTimestamps.length], 'int32')
now all my results work as expected.
Currently only int32 is supported with tensorflow.js, your data has gone out of the range supported by int32.
Until int64 is supported, this can be solved by using a relative timestamp. Currently a timestamp in js uses the number of ms that elapsed since 1 January 1970. A relative timestamp can be used by using another origin and compute the difference of ms that has elapsed since that date. That way, we will have a lower number that can be represented using int32. The best origin to take will be the starting date of the records
const a = Date.now() // computing a tensor out of it will give an accurate result since the number is out of range
const origin = new Date("02/01/2021").now()
const relative = a - origin
const tensor = tf.tensor(relative, undefined, 'int32')
// get back the data
const data = tensor.dataSync()[0]
// get the initial date
const initial date = new Date(data + origin)
In other scenarios, if using the ms is not of interest, using the number of s that has elapsed since the start would be better. It is called the unix time

The gof function from package btergm gives AUC value of a precision-recall greater than 1

I was trying to do out-of-sample prediction using the gof function from package btergm. When calculating the AUC value of a precision-recall curve from the testing set, I get the result of 1.012909, which seems to be theoretically impossible.
How can I interpret the result, or am I doing something wrong. Thank you! Here is my code:
network <- readRDS(url("https://www.dropbox.com/s/zxhqxa8h9awkzpd/network.rds?dl=1"))
model.3<- btergm(network[1:9]~edges+gwodegree(1, fixed=TRUE)+transitiveties + ctriple +
gwidegree(1, fixed=TRUE)+mutual+gwesp(1.5, fixed=TRUE)+ttriple+
memory(type="stability")+delrecip,R=1000)
gof.3 <-gof(model.3, nsim = 1000,target=network[[10]],formula = network[9:10]~edges+gwodegree(1,fixed=TRUE) +
transitiveties + ctriple +gwidegree(1,fixed=TRUE)+mutual+gwesp(1.5, fixed=TRUE)+ttriple+
memory(type="stability")+delrecip,coef = coef(model.3),
statistics = rocpr)
gof.3[[1]]$auc.pr

Incorrect day format returned from momentJS countdown

I used this simple script from: https://github.com/icambron/moment-countdown to make a simple countdown. The code below i'm using.
Used Code:
$interval(function(){
$scope.nextDate = moment().countdown($scope.nextDateGet,
countdown.DAYS|countdown.HOURS|countdown.MINUTES|countdown.SECONDS
);
$scope.daysCountdown = moment($scope.nextDate).format('dd');
$scope.hoursCountdown = moment($scope.nextDate).format('hh');
$scope.minutesCountdown = moment($scope.nextDate).format('mm');
$scope.secondsCountdown = moment($scope.nextDate).format('ss');
},1000,0);
This gives correct output
$scope.nextDate.toString();
But this contains one string with the remaining days,hours,minutes and seconds. So i decided i want to split this string into 4 strings by using this:
$scope.daysCountdown = moment($scope.nextDate).format('dd');
$scope.hoursCountdown = moment($scope.nextDate).format('hh');
$scope.minutesCountdown = moment($scope.nextDate).format('mm');
$scope.secondsCountdown = moment($scope.nextDate).format('ss');
Example for input
2016-10-15 10:00:00 // $scope.nextDateGet
Desired output is something like this:
0 // (days)
12 // (hours)
24 // (minutes)
30 // (seconds)
But i can't seem to format the remainings days, i get this output:
Fr // Shortcode for the day the item is scheduled => I need the remaining days in this case that would be 0. The other formatting is correct.
The following output was correct if remaining days was not 0:
$scope.daysCountdown = moment($scope.nextDate).format('D');
If remaining days was 0 it would set remaining days on 14 so this work around did the trick:
if(moment($scope.nextDate).isSame(moment(), 'day')){
$scope.daysCountdown = 0;
} else {
$scope.daysCountdown = moment($scope.nextDate).format('D');
}
Any suggestions to improve this code are always welcome.

Resources