I am trying to get this calculation to work in OCL, it has to say that if there is a cancelation present, it should give 'geannuleerd' and if there is a betaaldatum present it should give 'definitief'.
My question is: I need for this if-else-then statement a boolean, but I can't find out whether self.annuleringsdatum-> notEmpty() is enough or that there should be an = TRUE behind it.
What I have now is underneath, if you know whether this should work or whether the boolean statement is not correct yet, please answer :)
ontext Reservering::status
derive: if self.annuleringsdatum -> notEmpty()
then self.status = 'geannuleerd'
if self.betaaldatum -> notEmpty()
then self.status = 'definitief'
else self.status = 'voorlopig'
endif
Certainly not "= TRUE" unless "TRUE" is defined by your metamodel. You could do "= true" if you like typing, but it is redundant since notEmpty() has a Boolean return type. I suspect that you are being confused by the nested "if"s that each require their own "endif". (Eclipse OCL prototypes an "elseif" that would make your example more readable and the multiple "endif"s unnecessary.)
Related
There are two types of if function codes:
condition1 ? function1 : condition2 ? function2 : function3;
if (condition1) {
function1
} else {
if (condition2) {
function2
} else {
function3
}
}
I don't know what is the correct way to use the if else function code, I hope everyone can tell me.
Feel free to leave a comment if you need more information.
Which if else code should I use, single line or multiple lines? I would appreciate any help. Thank you in advance!
Those two are not "different styles of if".
The first one is the ternary operator. As the term operator suggests, it is used to produce a value.
The second one is the flow control statement if. It does not produce any value, it changes your program's flow.
So which one should you use? The one that fits your goal best. Do you need a value? The operator. Do you need to change your program flow? The flow control statement.
Try to reproduce this if statement with a ternary operator:
if (trafficlight.current == red) {
stopVehicle();
}
You cannot. Not without adding pointless waste. Because this is flow control.
On the other hand, this:
var newSpeed = (trafficlight.current == red) ? 0 : this.MaxSpeed;
Would be very convoluted to write as an if statement. Because it is generating a value.
So pick what is best for your program. It's not a "style" to follow blindly. It is a decision you should make for every one of those instances.
I have to return true or false based on field value in inner set item. My loops is as follow
myChoice.category.foreach(category => {
category.flavours.foreach(flavour=> {
if (flavour.available) true
})
})
false
It shoudld break and return true as soon as I have true on available but its returning false all the time. Any suggestion?
I don't have your dataset to work with, but perhaps this might do it.
myChoice.category.exists(_.flavours.exists(_.available))
Scala doesn't have continue or break. Because it is a fully functional language, every expression (including a loop) must have a value. Moreover, it tries to break out of the imperative style of initializing variables and mutating them over the course of a loop. Instead, scala encourages you to use a functional style, i.e. use methods that apply to data structures as a whole to transform/search for the desired result.
For your case, you're clearly looking to see if any of the flavors have their available field set to true. Thus you could flatMap the whole nested collection to a List of Boolean, and take the or of the whole collection:
val anyAvaliable = myChoice.category.flatMap(a => a.flavours).reduce( (flavour1,flavour2) => flavour1.available || flavour2.available)
jwvh's solution is even more concise. There are many ways of accomplishing essentially the same thing. Don't fight the language, have it fight for you!
Disclaimer: the below solution is provided for completeness, but jwvh's answer should be preferred for this case and generally speaking there are better alternatives. In particular, note that return from inside a lambda is implemented using exceptions, so 1) it may perform much worse than normal method calls; 2) if you are careless you can accidentally catch it.
If this is the last thing you need to do in the method, you can just use return:
myChoice.category.foreach(category => {
category.flavours.foreach(flavour=> {
if (flavour.available) return true
})
})
false
If it isn't, you can extract a method (including a local one):
def foo = {
...
val myChoice = ...
def hasAvailableFlavorsMethod() = {
myChoice.category.foreach(category => {
category.flavours.foreach(flavour=> {
if (flavour.available) return true
})
})
false
}
val hasAvailableFlavors = hasAvailableFlavorsMethod()
...
}
I'm fairly new to lua and have the following problem with an assignment from a class:
We currently extend lua to support objects and inheritance. The Syntax for that is
Class{'MyClass',
attribute1 = String,
attribute2 = Number
}
Class{'MySubClass', MyClass,
attribute3 = Number
}
This works perfectly fine. The real problem lies within the next task: We should support "recursive types", that means a call like
Class{'MyClass', attribute = MyClass}
should result in an class with a field of the same type as the class. When this "class-constructor" is called the variable MyClass is nil, thats why the parameter table doesnt't have an entry attribute. How is it possible to access this attribute?
My first thought was using some kind of nil-table which gets returned every time the global __index is called with an unset key. This nil-table should behave like the normal nil, but can be checked for in the "class-constructor". The problem with this approach are comparisons like nil == unknown. This should return true, but as the __eq meta method of the nil-table is never called we cannot return true.
Is there another approach I'm currently just ignoring? Any hint is greatly appreciated.
Thanks in advance.
Edit:
Here the relevant part of the "testfile". The test by which the code is rated in class is another one and gets published later.
three = 3
print( three == 3 , "Should be true")
print( unknown == nil , "Should be true" )
Class{'AClass', name = String, ref = AClass}
function AClass:write()
print("AClass:write(), name of AClass:", self.name)
end
aclass = AClass:create("A. Class")
aclass:write()
Since MyClass is just a lookup in the global table (_G), you could mess with its metatable's __index to return a newly-defined MyClass object (which you would later need to fill with the details).
However, while feasible, such an implementation is
wildly unsafe, as you could end up with an undefined class (or worse, you may end up inadvertantly creating an infinite lookup loop. Trust me, I've been there)
very hard to debug, as every _G lookup for a non-existing variable will now return a newly created class object instead of nil (this problem could somewhat be reduced by requiring that class names start with an uppercase character)
If you go that route, be sure to also override __newindex.
How about providing the argument in string form?
Class{'MyClass', attribute = 'MyClass'}
Detect strings inside the implementation of Class and process them with _G[string] after creating the class
Or alternatively, use a function to delay the lookup:
Class{'MyClass', attribute = function() return MyClass end}
I'm having an object as below:
class License{
private field1;
private field2;
private boolean active;
private String activeMessage;
private boolean processed = false;
//Getter and setter methods
}
What I'm trying to do is, based on the values of field1, and field2, I need to set the isActive flag and a corresponding message. However, if either the rule for field1 or field2 is fired, I need to stop the rules processing. That is, I need to execute only 1 successful rule.
I read on a post that doing ksession.fireAllRules(1) will solve this. But the fireAllRules() method is not available in Drools 6. I also tried putting a return; statement at the end of each rule. That didn't help me either.
Finally, I ended up adding an additional field to my object called processed. So whenever I execute any rule, I set the processed flag to true. And if the flag is already set, then I do not execute any rule. This is my rules file:
rule "Check field1"
when
$obj : License(getField1() == "abc" && isProcessed() == false)
then
System.out.println("isProcessed >>>>>> "+$obj.isProcessed());
$obj.setActive(true);
$order.setActiveMessage("...");
$order.setProcessed(true);
end
rule "Check field2"
when
$obj : License(getField2() == "def" && isProcessed() == false)
then
System.out.println("isProcessed >>>>>> "+$obj.isProcessed());
$obj.setActive(true);
$order.setActiveMessage("...");
$order.setProcessed(true);
end
However, I see that even now both my rules are being fired. When I try to print the value of isProcessed(), it says true, even though I enter the rule only if isProcessed() is false.
This is how I'm calling the drools engine:
kieService = KieServices.Factory.get();
kContainer = kieService.getKieClasspathContainer();
kSession = kContainer.newStatelessKieSession();
kSession.execute(licenseObj);
It is not just 2 rules, I have a lot of rules, so controlling the rules execution by changing the order of the rules in the drl file is not an option. What is happening here? How can I solve this problem? I am sort of new to Drools, so I might be missing something here.
Thanks.
Your question contains a number of errors.
It is definitely not true that fireAllRules has disappeared in Drools 6. You might have looked at the javadoc index, to find four (4!) overloaded versions of this method in package org.kie.api.runtime.rule in the interface StatefulRuleSession.
You might easily avoid the problem of firing just one out of two rules by combining the triggering constraint:
rule "Check field1 and field2"
when
$lic: License(getField1() == "abc" || getField2() == "def" )
//...
then
$lic.setXxx(...);
end
You complain that both of your rules fire in spite of setting the processed flag in the fact. Here you are missing a fundamental point (which is covered in the Drools reference manual), i.e., the necessity of notifying the Engine whenever you change fact data. You should have used modify on the right hand side of your rules.
But even that would not have been good enough. Whenever an update is made due to some properties, a constraint should be added to avoid running the update over and over again. You might have written:
rule "Check field1 and field2"
when
$lic: License(getField1() == "abc" || getField2() == "def",
! active )
//...
then
modify( $lic ){ setActive( true ) }
end
You might even write this in two distinct rules, one for each field, and only one of these rules will fire...
Double.TryParse returns a value, and I don't need a value. I need to be able to tell if a string is numeric and just return a bool.
is there a way to do this?
I would consider exactly what you need to determine. "Is numeric" is vaguer than it sounds at first. Consider the following strings, and whether you'd want to consider them numeric:
"NaN"
"Nan"
"Infinity"
"0.000000000000000000000000000000000000000000000000001"
"1e5"
"1e500"
"1,000"
"+1"
Using Double.TryParse (with an en-GB culture - don't forget about cultural issues!) will give you True, False, True, True (despite it not being representable), True, False. True, True.
If you want to tell whether a later call to Double.TryParse would succeed, calling it here will be the most accurate solution. If you're using some other criteria, a regular expression may well be more appropriate. An example of the criteria you might use:
The can be a + or -, but only in the first character
There can be a single period at any character. You may want to avoid one at the end - should "1." be valid?
Other than the above, all characters must be digits
That would disallow all but the fourth and last examples above.
EDIT: I've now noticed the title of the question includes "integer". That pretty much reduces the specification checks to:
Do you want to allow leading zeroes (e.g. -00012)?
What is the range?
Do you only need decimals (instead of hex etc)?
Do you need to accept thousands separators?
What's your policy on leading/trailing whitespace?
Well, you could use a regular expression, but why not just discard the value from Double.TryParse and move on? I don't think it will be worth the effort trying to duplicate this code.
One way is to add a reference to Microsoft.VisualBasic and then use Information.IsNumeric().
using Microsoft.VisualBasic;
...
if (Information.IsNumeric("1233434.0"))
{
Console.WriteLine("Yes");
}
How about a regular expression?
string s = "13.2";
bool bIsDecimal = Regex.IsMatch("^-?\d+(\.\d+)?$");
should test whether it is a decimal value. What it won't tell you is whether it is a valid decimal, as in, will the number fit in the range of a decimal.
I just fired up Visual Studio Express (both 2005 and 2008). The Intellisense says that the return value of Double.TryParse() is a bool. The following worked for me under limited testing...
double res; // you must be under very resource-constrained
// conditions if you can't just declare a double
// and forget about it
if (Double.TryParse(textBox1.Text, out res)) {
label1.Text = "it's a number";
} else {
label1.Text = "not a number";
}
try this isnumeric:
public static bool IsNumeric(object Expression)
{
bool isNum;
double retNum;
isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any,System.Globalization.NumberFormatInfo.InvariantInfo, out retNum );
return isNum;
}