How to find the difference between 2 NaiveDateTimes? - datetime

I am using chrono. I have now() and some other NaiveDateTime. How can I find a difference between them?
let now = Utc::now().naive_utc();
let dt1 = get_my_naive_datetime();

In more recent versions of chrono (at least as of 0.4.22, and likely earlier), you can simply subtract NaiveDateTimes:
println!("{:?}", dt1 - now);
The result is a Duration, which has methods to convert to whatever units you like, e.g. (dt1 - now).num_days().
In older versions of chrono, you must use NaiveDateTime::signed_duration_since:
println!("{:?}", dt1.signed_duration_since(now));

Related

sum(ofProperty: "amount") giving error in swift 5

I am using swift5 and I am trying to sum by property like this:
let total = realm.objects(Purchase.self).sum(ofProperty: "amount")
but i get this error:
Type of expression is ambiguous without more context
what can I do?
Probably the easist solution is to let the compiler know what kind of result the sum will be.
Like this
let total: Double = realm.objects(Purchase.self).sum(ofProperty: "orderProperty")
print(total)
This tells the compiler than total will always be a Double
As a side note, Double's are (generally) not a good type to work with for financial situations. Look into Decimal (akin to NSDecimal and Decimal128)
#Persisted var decimal: Decimal128
in newer versions

How to check for potential overflow in Ada when dealing with expression?

I am relatively new to Ada and have been using Ada 2005. However, I feel like this question is pertinent to all languages.
I am currently using static analysis tools such as Codepeer to address potential vulnerabilities in my code.
One problem I'm debating is how to handle checks before assigning an expression that may cause overflow to a variable.
This can be explained better with an example. Let's say I have a variable of type unsigned 32-bit integer. I am assigning an expression to this variable CheckMeForOverflow:
CheckMeForOverflow := (Val1 + Val2) * Val3;
My dilemma is how to efficiently check for overflow in cases such as this - which would seem to appear quite often in code. Yes, I could do this:
if ((Val1 + Val2) * Val3) < Unsigned_Int'Size then
CheckMeForOverflow := (Val1 + Val2) * Val3;
end if;
My issue with this is that this seems inefficient to check the expression and then immediately assign that same expression if there is no potential for overflow.
However, when I look online, this seems to be pretty common. Could anyone explain better alternatives or explain why this is a good choice? I don't want this scattered throughout my code.
I also realize I could make another variable of a bigger type to hold the expression, do the evaluation against the new variable, and then assign that variable's value to CheckMeForOverflow, but then again, that would mean making a new variable and using it just to perform a single check and then never using it again. This seems wasteful.
Could someone please provide some insight?
Thanks so much!
Personally I would do something like this
begin
CheckMeForOverflow := (Val1 + Val2) * Val3;
exception
when constraint_error =>
null; -- or log that it overflowed
end;
But take care that your variable couldn't have a usable value.
It's clearer than an if construct and we don't perform the calculation twice.
This is exactly the problem SPARK can help solve. It allows you to prove you won't have runtime errors given certain assumptions about the inputs to your calculations.
If you start with a simple function like No_Overflow in this package:
with Interfaces; use Interfaces;
package Show_Runtime_Errors is
type Unsigned_Int is range 0 .. 2**32 - 1;
function No_Overflow (Val1, Val2, Val3 : Unsigned_Int) return Unsigned_Int;
end Show_Runtime_Errors;
package body Show_Runtime_Errors is
function No_Overflow (Val1, Val2, Val3 : Unsigned_Int) return Unsigned_Int is
Result : constant Unsigned_Int := (Val1 + Val2) * Val3;
begin
return Result;
end No_Overflow;
end Show_Runtime_Errors;
Then when you run SPARK on it, you get the following:
Proving...
Phase 1 of 2: generation of Global contracts ...
Phase 2 of 2: flow analysis and proof ...
show_runtime_errors.adb:4:55: medium: range check might fail (e.g. when Result = 10)
show_runtime_errors.adb:4:55: medium: overflow check might fail (e.g. when
Result = 9223372039002259450 and Val1 = 4 and Val2 = 2147483646 and
Val3 = 4294967293)
gnatprove: unproved check messages considered as errors
exit status: 1
Now if you add a simple precondition to No_Overflow like this:
function No_Overflow (Val1, Val2, Val3 : Unsigned_Int) return Unsigned_Int with
Pre => Val1 < 2**15 and Val2 < 2**15 and Val3 < 2**16;
Then SPARK produces the following:
Proving...
Phase 1 of 2: generation of Global contracts ...
Phase 2 of 2: flow analysis and proof ...
Success!
Your actual preconditions on the ranges of the inputs will obviously depend on your application.
The alternatives are the solution you are assuming where you put lots of explicit guards in your code before the expression is evaluated, or to catch runtime errors via exception handling. The advantage of SPARK over these approaches is that you do not need to build your software with runtime checks if you can prove ahead of time there will be no runtime errors.
Note that preconditions are a feature of Ada 2012. You can also use pragma Assert throughout your code which SPARK can take advantage of for doing proofs.
For more on SPARK there is a tutorial here:
https://learn.adacore.com/courses/intro-to-spark/index.html
To try it yourself, you can paste the above code in the example here:
https://learn.adacore.com/courses/intro-to-spark/book/03_Proof_Of_Program_Integrity.html#runtime-errors
Incidentally, the code you suggested:
if ((Val1 + Val2) * Val3) < Unsigned_Int'Size then
CheckMeForOverflow := (Val1 + Val2) * Val3;
end if;
won't work for two reasons:
Unsigned_Int'Size is the number of bits needed to represent Unsigned_Int. You likely wanted Unsigned_Int'Last instead.
((Val1 + Val2) * Val3) can overflow before the comparison to Unsigned_Int'Last is even done. Thus you will generate an exception at this point and either crash or handle it in an exception handler.

What is the Rust equivalent of C# System.DateTime.Ticks? [duplicate]

I am using chrono. I have now() and some other NaiveDateTime. How can I find a difference between them?
let now = Utc::now().naive_utc();
let dt1 = get_my_naive_datetime();
In more recent versions of chrono (at least as of 0.4.22, and likely earlier), you can simply subtract NaiveDateTimes:
println!("{:?}", dt1 - now);
The result is a Duration, which has methods to convert to whatever units you like, e.g. (dt1 - now).num_days().
In older versions of chrono, you must use NaiveDateTime::signed_duration_since:
println!("{:?}", dt1.signed_duration_since(now));

Xquery result duplicated

I'm not getting the output I want. I don't understand why the result is duplicated. Can someone help me?
for $i in 1 to 2
let $rng:=random-number-generator()
let $rng1:=$rng('permute')(1 to 10)
let $rng:=$rng('next')()
let $rng2:=$rng('permute')(1 to 10)
let $rng:=$rng('next')()
let $rng3:=$rng('permute')(1 to 10)
return (string-join($rng1),string-join($rng2),string-join($rng3),",")
result:
23496815107
31018674529
31017684259
23496815107
31018674529
31017684259
The result is duplicated because of the initial for $i in 1 to 2, and because the variable $i is not actually used anywhere.
I edited the query based on your comment (getting 10 numbers). From what I understand, the difficulty here is to chain the calls (alternating between 'next' and 'permute'). Chaining calls can be done with a tail recursion.
declare function local:multiple-calls(
$rng as function(*),
$number-of-times as xs:integer) as item()* {
if($number-of-times le 0)
then ()
else
let $rng := $rng('next')
return ($rng('permute')(1 to 10),
local:multiple-calls($rng, $number-of-times - 1))
};
local:multiple-calls(random-number-generator(), 10)
Note: I am not sure if (1 to 10) is what needs to actually be passed to the call to $rng('permute'), or if it was an attempt to output ten numbers. In doubt, I haven't changed it.
The specification is here:
http://www.w3.org/TR/xpath-functions-31/#func-random-number-generator
It says:
Both forms of the function are ·deterministic·: calling the function
twice with the same arguments, within a single ·execution scope·,
produces the same results.
If you supply $i as the $seed argument to random-number-generator then the two sequences should be different.
I think I now understand what confuses you in this original query. One could indeed expect the random numbers to be generated differently for each iteration of $i.
However, XQuery is (to put it simply, with a few exceptions) deterministic. This means that the random generator probably gets initialized in each iteration with the same, default seed.
Thus, I have a second potential answer:
If you have a way to pass a different seed to $rng, you could slightly modify your initial query by constructing a seed based on $i and maybe current-dateTime() in each iteration before generating the numbers. But it will still be the same if you execute the query several times unless you involve the current date/time.

XQuery get milli-second part of current time

I am unable to get any in-built method for retrieving milli-second part of the given date-time.
Method current-dateTime() returns the full date & time along with milli-seconds, but I am looking for in-built one just to return millisecond.
In-built methods are available for hours, minutes and for seconds but not for milliseconds.
Please note, I do not wish to get the unix-timestamp
Indeed, such a function for getting just the milliseconds appears to be missing from XQuery, however this is most likely because if you read the spec, then seconds are modeled as a decimal rather than as two separate seconds and milliseconds components.
Another alternative to your answer is to use a regular expression:
replace(string($currentTime), ".*\.([0-9]*)[+\-].*", "$1")
As I found no default method, I used following approach to get milliseconds
let $sec := fn:seconds-from-dateTime($currentTime)
let $splitSeconds := fn:tokenize(fn:string($sec), '\.')
let $seconds := $splitSeconds[1]
let $milliSeconds := $splitSeconds[2]

Resources