CAPL on sysvar_change procedure with sysvar of custom struct data type - capl

according to the manual,
The procedure on sysVar is called only when the value of the variable
changes. It can also be written as on sysVar_change. If you want to be
notified of value updates to the variable which don’t change the
value, you should use on sysVar_update instead.
In my example scenario, I have a system variable s::sysv of custom Struct Data Type X, where X has two fields: A and B.
In my CAPL script I put the following:
on sysvar_change s::sysv.A
{
// do stuff
}
Expected output is to do stuff only when s::sysv.A changes. However, since s::sysv.B is often updated when my simulation is running, then the procedure on sysvar_change s::sysv.A is called a lot more times than I expect, even if A doesn't change its value.
I don't understand why, and I'm putting a lot of workaround in place to avoid this, can anybody help?
Edit:
according to one reply, the event handler is not the struct element, but still the variable. However, the keyword this is now pointing to the struct element and not to the variable.
This bit of the manual is also relevant:
You can also react in the same way to value changes of specific
elements of a system variable of type struct or generic array. For
this, add the element to the name of the variable.

I have tried this functionality in the latest CANoe and it works as expected. The following is my code.
on key 'a'
{
#sysvar::Var_Struct1.StructMem1++;
}
on key 'b'
{
#sysvar::Var_Struct1.StructMem2++;
}
on sysvar_change Var_Struct1.StructMem1
{
write("StructMem1 value changed");
}
on sysvar_change Var_Struct1.StructMem2
{
write("StructMem2 value changed");
}
Whenever I press the key 'a' or 'b', the corresponding event is triggered.

Your variable is s::sysv. The event handler is called whenever the value of the variable changes. No matter whether A or B changes.
There is no way to restrict it only to certain changes of the value.
This is similar to the fact that you can also not be notified when, e.g. only the 3rd bit of an integer changes.
To me, it seems best to reconsider your setup and ask yourself, whether using the struct is the right approach, or whether it might be better to use two separate system variables A and B.

Related

request.object.previous() is not working in beforeSave()

I'm trying to check the current and previous value of an attribute in the beforeSave(). So i tried to use request.object.previous("attribute_name") but it is still returning the current changed value. Although the .ditry() is returning TRUE which means that the value is changed. Any idea what is wrong here ? I appreciate your feedback.
I think the .previous() isn't actually part of the Parse.com sdk, but simply inherited from backbone.
In a beforeSave handler, I have something like:
if(object.dirty("attr")) {
console.log("After: " + object.get("attr") + ", Before: " + object.previous("attr")); }
The value returned by 'previous' is always the same. Is this functionality actually
implemented? I've seen a few threads elsewhere that imply it's not -
if so, can you remove it from the API docs until it's done?
If it doesn't work, is the correct workaround to query the previous
object? Or does 'changedAttributes' work?
Oh, I now see that 'previous' is some cruft from Backbone.
source1
previous is a method inherited from Backbone.Model. It won't return the previous value of a field in Cloud Code.
source2
Might not be the answer you're looking for, so as a way to workaround the lack of the .previous implementation this this out:
Don't know if this is helpful or if it would be considered too costly
of a workaround, but you could add a column to the object that is
being updated that stores the previous value of the original column.
This would allow you to access the previous value in the AfterSave
function.

How do I pass a can.compute into a can.Component?

How can I pass computes into components, such that changing the value in selected in one component will affect a value in a different component.
Example
http://jsbin.com/feleko/1/edit?html,js,console,output
I'm trying to set it up so that selecting a value in the first select changes the options available in the second. I think listening for dom change events should be straightforward, but I don't seem to be getting a compute I can update, or have access to the parent scope in order to use an attribute name to update it. Likewise the max value isn't an active object that receives updates.
I've found an obtrusive way. can.mustache provides a data helper that puts the current context on the element's data.
<select {{data 'context'}} value="a">
Then in the init event I can capture the element data and assign it to the scope so it's available to scope functions.
events: {
init: function(el, opt) {
opt.scope.context = el.data('context')
}
}
Looking up values is then possible if awkward.
this.context[this.attr('value')]

With boost::msm eUML, if I give attributes_ << to the state machine or state, how do I (re)set them?

If I add attributes to an event, I know I can then use the event name like a function...
BOOST_MSM_EUML_EVENT_WITH_ATTRIBUTES(*someEvent*, *someAttributeList*)
someStateMachine.process_event(
someEvent (
valueOfSomeAttribute1, // sets the attribute value here
valueOfSomeAttribute2))
and that inside an action I can this back by writing
evt.get_attribute(someAttribute1); // retrieve the attribute value
Now, if I set an attribute for an entire machine, like so:
BOOST_MSM_EUML_DECLARE_STATE_MACHINE((transition_table,
init_ << initState,
Entry_Action,
Exit_Action,
attributes_ << someAttribute1 << someAttribute2,
configure_<< someConfigurationStuff ),
newStateMachineType)
How do I go about setting a value for someAttribute1?
Same question for states:
BOOST_MSM_EUML_STATE(
(someEntryAction,
someExitAction,
attributes_ << someAttribute1,
configure_<< someConfigurationStuff)
,newStateName)
How do I go about setting a value for someAttribute1?
Finally,
Is there a way to change the attributes after the object is created?
For instance, I'd like to have an attribute for the state machine, and in one of my states, remember some piece of information that I can store in the state machine. (In this case, I want to store a socket.)
Thanks.
How do I go about setting a value for someAttribute1?
You can:
change the reference you just got (get_attribute returns a reference): ++evt.get_attribute(someAttribute1).
use the functors to write the attribute in your table directly. For example, following action is possible: /++fsm_(someAttribute1)
For states, you can do the same. And for state machines, well, ditto.
Again, you can either use the Fsm template parameter in your actions, or the functors (fsm_, event_, etc.)
You can find good example of all in the examples or tests (for example test/CompositeEuml.cpp or test/AnonymousEuml.cpp).
HTH,
Christophe

Deciding whether or not a run a function, which way is better?

I have some data being loaded from a server, but there's no guarantee that I'll have it all when the UI starts to display it to the user. Every frame there's a tick function. When new data is received a flag is set so I know that it's time to load it into my data structure. Which of the following ways is a more sane way to decide when to actually run the function?
AddNewStuffToList()
{
// Clear the list and reload it with new data
}
Foo_Tick()
{
if (updated)
AddNewStuffToList();
// Rest of tick function
}
Versus:
AddNewStuffToList()
{
if (updated)
{
// Clear the list and reload it with new data
}
}
Foo_Tick()
{
AddNewStuffToList();
// Rest of tick function
}
I've omitted a lot of the irrelevant details for the sake of the example.
IMHO first one. This version separates:
when to update data (Foo_Tick)
FROM
how to loading data (AddNewStuffToList()).
2nd option just mixing all things together.
You should probably not run the function until it is updated. That way, the function can be used for more purposes.
Let's say you have 2 calls that both are going to come and put in data to the list. With the first set up, checking the variable inside of the function, you could only check if one call has came in. Instead, if you check it in the function that calls the data, you can have as many input sources as you want, without having to change the beginning function.
Functions should be really precise on what they are doing, and should avoid needing information created by another function unless it is passed in.
In the first version the simple variable check "updated" will be checked each time and only if true would AddNewStuffToList be called.
With the second version you will call AddNewStuffToList followed by a check to "updated" every time.
In this particular instance, given that function calls are generally expensive compared to a variable check I personally prefer the first version.
However, there are situations when a check inside the function would be better.
e.g.
doSomething(Pointer *p){
p->doSomethingElse();
}
FooTick(){
Pointer *p = new Pointer();
// do stuff ...
// lets do something
if (p){
doSomething(p);
}
}
This is clumbsy because every time you call doSomething you should really check you're
not passing in a bad pointer. What if this is forgotten? we could get an access violation.
In this case, the following is better as you're only writing the check in one place and
there is no extra overhead added because we always want to ensure we're not passing in a bad pointer.
doSomething(Pointer *p){
if (p){
p->doSomethingElse();
}
}
So in general, it depends on the situation. There are no right and wrong answers, just pros and cons here.

Avoiding duplicate code in input validation

Suppose you have a subsystem that does some kind of work. It could be anything. Obviously, at the entry point(s) to this subsystem there will be certain restrictions on the input. Suppose this subsystem is primarily called by a GUI. The subsystem needs to check all the input it recieves to make sure it's valid. We wouldn't want to FireTheMissles() if there was invalid input. The UI is also interested in the validation though, because it needs to report what went wrong. Maybe the user forgot to specify a target or targetted the missles at the launchpad itself. Of course, you can just return a null value or throw an exception, but that doesn't tell the user SPECIFICALLY what went wrong (unless, of course, you write a separate exception class for each error, which I'm fine with if that's the best practice).
Of course, even with exceptions, you have a problem. The user might want to know if input is valid BEFORE clicking the "Fire Missles!" button. You could write a separate validation function (of course IsValid() doesn't really help much because it doesn't tell you what went wrong), but then you'll be calling it from the button click handler and again from the FireTheMissles() function (I really don't know how this changed from a vague subsystem to a missle-firing program). Certainly, this isn't the end of the world, but it seems silly to call the same validation function twice in a row without anything having changed, especially if this validation function requires, say, computing the hash of a 1gb file.
If the preconditions of the function are clear, the GUI can do its own input validation, but then we're just duplicating the input validation logic, and a change in one might not be reflected in the other. Sure, we may add a check to the GUI to make sure the missle target is not within an allied nation, but then if we forget to copy it to the FireTheMissles() routine, we'll accidentally blow up our allies when we switch to a console interface.
So, in short, how do you achieve the following:
Input validation that tells you not just that something went wrong, but what specifically went wrong.
The ability to run this input validation without calling the function which relies on it.
No double validation.
No duplicate code.
Also, and I just thought of this, but error messages should not be written in the FireTheMissles() method. The GUI is responsible for picking appropriate error messages, not the code the GUI is calling.
"The subsystem needs to check all the input it receives to make sure it's valid"
Think of the inputs not so much as a list of arguments, but as a message, it gets easier after that.
The message class has an IsValid member function, it remembers if IsValid was called and what the result was. It also remembers its state, if the state changes then it needs to be re validated. This message class also keeps a list of validation errors.
Now, the UI builds a TargetMissiles message, and the UI can validate it, or pass it directly to the MissileFiring subsystem, it checks to see if the message was validated, if not it validates it, and proceeds / fails depending.
The UI gets the message back, with the list of validations already populated.
The messages with their validation sit in a separate library. No code is duplicated.
This sound OK?
This is what Model-View-Controller is all about.
You build up a model (a launch which is composed of coordinates, missile types and number of missiles) and the model has a validate method which returns a list of errors/warnings. When you update the model (on key-up, <ENTER>, button-press) you call the validate method and show the user any warnings, errors, etc. (Eclipse has a little area just under the tools bar in a dialog that does this, you might want to look at that.)
When the model is valid, you activate the launch missiles button so that the user knows that they can launch the missiles. If you have an update event that is called particularly frequently or a part of the validation that is particularly costly, you can have a validate_light method on the model that you use for validating only the parts that are easy to do.
When you switch to a console based UI you build up the model from the command line arguments, call the same validate method (and report errors to stderr) and then launch the missiles.
Double the validation. In many case the validation is trebled (FKs and not null fields in the DB for example). Depending on your platform it may be possible to code the validation rules once. For example your front end and backend code could share C# business classes. Alternatively you could store the validation rule as metadata that both the backend and front end can access an apply.
In reality the fact that you need different responses to a validation problem (for example the Fire Missile button shouldn't even be enabled until the other inputs are valid) there will be different code associated with the same rule.
I'd suggest an input validation class, which takes the input type (an enumeration) in its' constructor, and provides a public IsValid method.
The IsValid method should return a boolean TRUE for valid and FALSE for invalid. It should also have an OUT parameter that takes a string and assigns a status message to that string. The caller will be free to ignore that message if it wants to, or report it up to the GUI if that's appropriate for the context.
So, in pseudocode (forgive the Delphi-like syntax, but it should be readable to anybody):
//different types of data we might want to validate
TValidationType = (vtMissileLaunchCodes, vtFirstName,
vtLastName, vtSSN);
TInputValidator = class
public
//call the constructor with the validation type
constructor Create(ValidationType: TValidationType);
//this should probably be ABSTRACT, implemented by descendants
//if you took that approach, then you'd have 1 descendant class
//for each validation type, instead of an enumeration
function IsValid(InputData: string; var msg: string): boolean;
And then to use it, you'd do something like this:
procedure ValidateForm;
var
validator: TInputValidator;
begin
validator := TInputValidator.Create(vtSSN);
if validator.IsValid(edtSSN.Text,labelErrorMsg.Text) then
SaveData; //it's valid, so save it!
//if it wasn't valid, then the error msg is in the GUI in "labelErrorMsg".
end;
Each piece of data has its own meta data (type, format, unit, mask, range etc.). Unfortunately this is not always specified.
The GUI controlls need to check the input with the metadata and give warnings/errors if the data is invalid.
Example: a number has a range. The range is provided by the metadata, but the range check is provided by the control.

Resources