Jodatime LenientChronology parser double counting - parsing

The following Scala code returns 121,000ms instead of the expected 61,000ms. This applies to other fields (e.g. hour of day) as well, and seems to be caused by double-counting the out-of-range value twice. The documentation and tests for LenientChronology don't seem to throw any light on this behaviour, so was wondering if anyone know of or could provide an explaination for this behaviour.
import org.joda.time.chrono.{ISOChronology, LenientChronology}
import org.joda.time.format.DateTimeFormatterBuilder
val secondNumber = "61"
val lenientChronology = LenientChronology.getInstance(ISOChronology.getInstanceUTC)
val lenientParser = new DateTimeFormatterBuilder()
.appendSecondOfMinute(1).toFormatter.withChronology(lenientChronology)
lenientParser.parseMillis(secondNumber)

We can also use PeriodFormatterBuilder instead:
import org.joda.time.format.PeriodFormatterBuilder
val hoursMinutes =
new PeriodFormatterBuilder().appendHours().appendLiteral(":").appendMinutes().appendLiteral(":").appendSeconds().toFormatter
val duration = hoursMinutes.parsePeriod("40:50:23").toStandardDuration
duration.getMillis
It handles LenientChronology on the fly

Related

using a string in a math equation in Dart

I store various formulas in Postgres and I want to use those formulas in my code. It would look something like this:
var amount = 100;
var formula = '5/105'; // normally something I would fetch from Postgres
var total = amount * formula; // should return 4.76
Is there a way to evaluate the string in this manner?
As far as I'm aware, there isn't a formula solver package developed for Dart yet. (If one exists or gets created after this post, we can edit it into the answer.)
EDIT: Mattia in the comments points out the math_expressions package, which looks pretty robust and easy to use.
There is a way to execute arbitrary Dart code as a string, but it has several problems. A] It's very roundabout and convoluted; B] it becomes a massive security issue; and C] it only works if the Dart is compiled in JIT mode (so in Flutter this means it will only work in debug builds, not release builds).
So the answer is that unfortunately, you will have to implement it yourself. The good news is that, for simple 4-function arithmetic, this is pretty straight-forward, and you can follow a tutorial on writing a calculator app like this one to see how it's done.
Of course, if all your formulas only contain two terms with an operator between them like in your example snippet, it becomes even easier. You can do the whole thing in just a few lines of code:
void main() {
final amount = 100;
final formula = '5/105';
final pattern = RegExp(r'(\d+)([\/+*-])(\d+)');
final match = pattern.firstMatch(formula);
final value = process(num.parse(match[1]), match[2], num.parse(match[3]));
final total = amount * value;
print(total); // Prints: 4.761904761904762
}
num process(num a, String operator, num b) {
switch (operator) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
}
throw ArgumentError(operator);
}
There are a few packages that can be used to accomplish this:
pub.dev/packages/function_tree
pub.dev/packages/math_expressions
pub.dev/packages/expressions
I used function_tree as follows:
double amount = 100.55;
String formula = '5/105*.5'; // From Postgres
final tax = amount * formula.interpret();
I haven't tried it, but using math_expressions it should look like this:
double amount = 100.55;
String formula = '5/105*.5'; // From Postgres
Parser p = Parser();
// Context is used to evaluate variables, can be empty in this case.
ContextModel cm = ContextModel();
Expression exp = p.parse(formula) * p.parse(amount.toString());
// or..
//Expression exp = p.parse(formula) * Number(amount);
double result = exp.evaluate(EvaluationType.REAL, cm);
// Result: 2.394047619047619
print('Result: ${result}');
Thanks to fkleon for the math_expressions help.

Groovy variable double substitution

I would like to perform double substitution.
When printing:
def y = "\${x}"
def x = "world"
def z = "Hello ${y}"
println z
It prints:
Hello ${x}
When I would like it to print Hello World, I tried performing a double evaluation ${${}}, casting it to org.codehaus.groovy.runtime.GStringImpl, and a desperate ${y.toStrin()}
Edit:
To be more clear I mean this, but in Groovy:
https://unix.stackexchange.com/questions/68042/double-and-triple-substitution-in-bash-and-zsh
https://unix.stackexchange.com/questions/68035/foo-and-zsh
(Why I am doing this?: Because we have some text files that we need evaluate with groovy variables; the variables are many and in different part of the code are different, therefore I would like to have a solution working across all cases, not to have to bind each time each variable, not adding many lines of code)
So with what you have you're escaping the $ so it is just interpreted as a string.
For what you are looking to do I would look into Groovys's templating engines:
http://docs.groovy-lang.org/docs/next/html/documentation/template-engines.html
After reading your comment I played around with a few ideas and came up with this contrived answer, which is also probably not quite what you are looking for:
import groovy.lang.GroovyShell
class test{
String x = "world"
String y = "\${x}"
void function(){
GroovyShell shell = new GroovyShell();
Closure c = shell.evaluate("""{->"Hello $y"}""")
c.delegate = this
c.resolveStrategry = Closure.DELEGATE_FIRST
String z = c.call()
println z
}
}
new test().function()
But it was the closest thing I could come up with, and may lead you to something...
If I understand right, you are reading y from somewhere else. So you want to evaluate y as a GString after y and then x have been loaded. groovy.util.Eval will do this for simple cases. In this case, you have just one binding variable: x.
def y = '${x}'
def x = 'world'
def script = "Hello ${y}"
def z = Eval.me('x', x, '"' + script + '".toString()') // create a new GString expression from the string value of "script" and evaluate it to interpolate the value of "x"
println z

Incomplete structured construct

i am new with f# , will be great if some 1 can help , nearly half a day gone solving this problem Thank you
module Certificate =
type T = {
Id: int
IsECert: bool
IsPrintCert: bool
CertifiedBy: string
Categories: Category.T list
}
let createPending now toZonedDateTime toBeCertifiedByName (job: Models.Job.T) (certificateType: Models.CertificateType.T) (pendingCertificate: Models.PendingCertificate.T) visualization (categories: Category.T list) =
let forCompletion = Models.PendingCertificate.getCertificateForCompletion pendingCertificate
{
Id = forCompletion.Id |> CertificateId.toInt
IsECert = Models.PendingCertificate.isECertificate pendingCertificate
IsPrintCert = Models.PendingCertificate.isPrintCertificate pendingCertificate
CertifiedBy = toBeCertifiedByName
Categories = categories}
i am getting an error in "Incomplete structured construct at or before this point"
Your formatting is all off. I will assume here that this is just a result of posting to StackOverflow, and your actual code is well indented.
The error comes from the definition of createPending: this function does not have a result. All its body consists of defining a forCompletion value, but there is nothing after it. Here's a simpler example that has the same problem:
let f x =
let y = 5
This function will produce the same error, because it also doesn't have a result. In F#, every function has to return something. The body cannot contain only definitions of helper functions or values. For example, I could fix my broken function above like this:
let f x =
let y = 5
x + y
This function first defines a helper value y, then adds it to its argument x, and returns the result.
> f 2
> 7
>
> f 0
> 5
How exactly you need to fix your function depends on what exactly you want it to mean. I can't help you here, because you haven't provided that information.

Error adding containts to solver in z3

assign wfwe = wb_acc & (adr_i == 2'b10) & ack_o & we_i;
For the above assign statement which is in verilog, i getting error while implememting it in z3
My code:
BitVecExpr[] wfwe = new BitVecExpr[1];
BitVecExpr[] wb_acc = new BitVecExpr[1];
BitVecExpr[] adr_i = new BitVecExpr[1];
BitVecExpr[] ack_o = new BitVecExpr[1];
BitVecExpr[] we_i = new BitVecExpr[1];
wfwe[0] = ctx.mkBVConst("wfwe",1);
wb_acc[0] = ctx.mkBVConst("wb_acc",1);
adr_i[0] = ctx.mkBVConst("adr_i",2);
ack_o[0] = ctx.mkBVConst("ack_o",1);
we_i[0] = ctx.mkBVConst("we_i",1);
Solver s = ctx.mkSolver();
s.add(ctx.mkBVAND(wb_acc[0],ctx.mkEq(adr_i[0],ctx.mkNumeral("2",2)),ack_o[0],we_i[0]));
I am getting error in above add statement:
error: method mkBVAND in class Context cannot be applied to given types;
required: BitVecExpr,BitVecExpr
found: BitVecExpr,BoolExpr
Which is true. Can anyone suggest me workaround. Am i implementing it incorrectly please let me know.
This error is reported because the second argument of mkBVAND is a Boolean expression (ctx.mkEq ...). Note that Booleans and BitVectors of size 1 are not the same thing, and they will not be converted automatically. The easiest way to convert between them is an if-then-else the selects the right values.
These are the problems with this example:
1) ctx.mkNumeral("2",2) is incorrect. I guess the intention was to create a bv-numeral of 2 bits with value 2; the easiest way to achieve that is ctx.mkBV(2, 2)
2) The 2nd argument of mkBVAND needs to be converted from Bool to BitVector, e.g., like so:
BoolExpr c = ctx.mkEq(adr_i[0], ctx.mkBV(2, 2));
BitVecExpr e = (BitVecExpr) ctx.mkITE(c, ctx.mkBV(1, 1), ctx.mkBV(0, 1));
e being the result.
3) ctx.mkBVAND takes exactly 2 arguments, no more and no less. Thus, the BVAND expression needs to be rewritten, e.g., like so:
ctx.mkBVAND(ctx.mkBVAND(wb_acc[0], e), ctx.mkBVAND(ack_o[0], we_i[0])))
4) The result needs to be converted to a Boolean expression again, e.g.
ctx.mkEq(q, ctx.mkBV(1, 1))
where q is the result of the BVAND.

Any max and argmax?

I want to use max and argmax on collections. I saw an issue for max but not argmax and it looks different to what I had in mind. Everything here is also applicable to min and argmin. Example of code with equivalent behaviour (minus error handling):
import 'dart:html';
import 'dart:math' as math;
void main() {
final nums = [3, 1, 2];
final animalNames = ['cat', 'turtle', 'sheep'];
final highest = nums.reduce(nums[0], (stored, curr) => math.max(stored, curr));
final longest = animalNames.reduce(animalNames[0], longerString);
print('highest: $highest');
print('longest: $longest');
}
String longerString(final String first, final String second) {
if (first.length < second.length) {
return second;
} else {
return first;
}
}
I've been searching the API but haven't find anything like:
final highest = nums.max;
final longest = animalNames.argmax((name) => name.length);
Similar to Ruby max and max_by.
Questions:
Are there API calls like these already (under some name I haven't checked)?
Are there any plans to make them?
Should I raise an issue?
I don't think there is, but here's a pretty trivial implementation based on your example:
animalNames.reduce("", (prev, cur) => prev.length > cur.length ? prev : cur);
This is faster than sorting if you only want to look it up once, but this can get a little unwieldy if you have complex logic for your argmax.
In one of the Dartisans videos, one of the devs mentioned how they're trying to make a lot of the common patterns easy, so I think something like this would have a pretty good chance of making it into the standard library if you make a good enough case for it.

Resources