How to use the instance name as a string in Modelica code? - stream

I have a Modelica simulation model composed by some models connected to each other.
I would like to save some data of some of the model instances in my simulation model at a given time using the built-in function
Modelica.Utilities.Streams.writeRealMatrix();
To be sure which instance writes which file, I would like to include the instance name in the writeRealMatrix() output file name, e.g., in case I have an instance called myModel, using the name:
myModelOut.mat.
To do this, I need a way to get the instance name and put it into a string.
I know that Modelica allows using instance names in model icons, through a Text record, using the keyword "%name", but I don't know how to do the same in a regular string (I mean outside any record or icon annotation).
Does anyone know if there is a way to do this?
Thank you in advance.

In your case I think the function getInstanceName() should be a good approach. Using it will need you to edit the model, but given you are writing information from with the class using writeRealMatrix() this shouldn't be an issue.
I have created a small example package with a constant block, that stores its name into final parameter of type String. The example then writes the string to the console at the termination of the simulation:
package GetName
block ConstantNamed "Generate constant signal of type Real"
extends Modelica.Blocks.Sources.Constant;
final parameter String name = getInstanceName();
end ConstantNamed;
model Example
extends Modelica.Icons.Example;
ConstantNamed myConst(k=23) annotation (Placement(transformation(extent={{-10,-10},{10,10}})));
equation
when terminal() then
Modelica.Utilities.Streams.print("### Here is the models full path: '" + myConst.name + "'");
end when;
end Example;
annotation (uses(Modelica(version="4.0.0")));
end GetName;
This should result in a simulation log containing the path of the instance of ConstantNamed, which is Example.myConst:
Note: The print function is added to Example in the above code. It could be added to the ConstantNamed as well. For the case from the question, the print shouldn't be necessary anyways...
Besides that, in case you are using Dymola, there is the ModelManagement library, which contains some functions like ModelManagement.Structure.AST.Classes.ComponentsInClass. But these are more intended to be applied from "outside" to a given model.

Related

How to access object field in qaf step from stored variable

In my previous question I was looking for a way to access and store return value of the function in qaf step. I was provided with the following:
When create new user using "{'name':'user1','password':'user123'}"
And store into 'newUser'
Then system should have user '${newUser}'
Now, I'd like to know how to get value from object/collection stored.
If it is a simple object named newUser which has field Id. How would I pass Id on next step?
And, if return is List, how to get by index from stored list?
Resolved issue on my own. If anyone faces same unknowns, here is how I solved it.
For requirements to work around response data, parsing same stored objects in properties by specific fields or collecting data from other structures such as Maps or Lists, create common functions with #QAFTestStep annotation to get data for class member name, map by key or list by index and so on... Add those in common steps and then write stepname text in gherkin format with parameters specified. Let me know if someone needs help, always ready to help out...

How to update value in angular ui typeahead directive if no matching option is found

I've an array of objects containing title and salary which is used in typeahead directive.
I display department name and get entire object as value.
If none of the options match, I want user entered string to be converted to object still. Is there any way to update that?
This answer is pretty late, but I would just use ng-blur (to trap the end of the users input) along with a variable bound to typeahead-no-results. Then test if the variable is true in the method bound to ng-blur, and, if so, make an object out of the String supplied by the user and push it to your data source. Simple example found here.

Using Variables for Model Names in Active Record

I am writing a seed file that will make several API calls via HTTParty in order to populate the database. I am pulling the same information for several different models and I would like to be able to use a single method for all of them. However, I cannot figure out how to reference the model name through a variable. Specifically I am having difficulties because each of these must belong to another model. I have tried the following:
def create_assets(subject, model, geokit_hoods)
response = HTTParty.get("https://raw.githubusercontent.com/benbalter/dc-maps/master/maps/#{subject}.geojson")
parsed = JSON.parse(response)
collection = parsed["features"]
collection.each do |station|
coordinates = station["geometry"]["coordinates"].reverse
point = Geokit::LatLng.new(coordinates[0], coordinates[1])
geokit_hoods.each do |hood|
if hood[1].contains?(point)
hood[0][model].create(coordinates: coordinates, name: station["properties"]["NAME"], address: station["properties"]["ADDRESS"])
break
end
end
end
end
Which I called via the following:
create_assets("metro-stations-district", "metros", geokit_hoods)
hood[0] refers to an existing neighborhood model, and hood[1] is the polygon associated with that neighborhood. The code works when referring to hood[0].metros.create(...), but I am looking for a way to make this method useful across many models.
Any ideas would be appreciated!
For now I'm going to assume that what you have in the variable is a String that is the name of the class in table-name format. eg in your example you have metros in the variable... from that I assume you have a Metro class which you are trying to create.
If so... you first need to convert your lowercase table-name style variable ("metros") into a class name-style eg "Metro"
Note: this is title cased and singular (rather than plural).
Rails has a method to do this to strings for exactly the purpose you want: classify eg you could use it thus:
model_name = hood[0][model] # 'metros'
model_name.classify # 'Metro'
Note that it's still just a string, and you can't call create on a string.. so how do you make it the real class? constantize
Use this to turn the string into the actual model-class you're trying to find... which you can then call create on eg:
model_name = hood[0][model] # 'metros'
the_klass = model_name.classify.constantize # Metro
your_instance = the_klass.create(...)

Custom wrapper for log4j2

I want to build a wrapper around log4j2 to do the below:
1) There are around 6 mandatory fields like event_name, action, desc etc
2) Some fields, i want to make them use only certain values, like enum
3) log should be created in key value pairs for Splunk.
Below is my approach:
1) Created a class called CustomLogger accepeting the mandatory fields, logger and variable fields as key value
2) Users can call methods like below:
CustomLogger.info(logger, transactionId, app_name, event_name,
"inside the loop", "inside the loop of the sample app",
CustomLogger.Result.success, "looped in", "loop_count",
String.valueOf(i));
Method definition:
public static String log(LogLevel logLevel, Logger logger,
String transactionId, String app_name, String event_name,
String action, String desc, Result result, String reason,
String... addtnlFields)
Issues with the approach:
1) Not extending the log4j, not sure if this is the right way
2) need to pass the logger from every class. If that can be avoided
3) method and line number is lost since it is getting called from a different method
This will be widely used across my internal applications, so want to do it right. Is this approach ok or is there a better approach?
Take a look at the code generator attached to this Jira: https://issues.apache.org/jira/browse/LOG4J2-519
Perhaps you can use that as a base class? Gives you a slightly nicer API.
(I still need to update this to reflect some API changes in log4j-2.0-rc2...)
UPDATE
A different approach is to have a custom implementation of the Message interface defined in the log4j2 api module. Your custom message would have a constructor with all fields you define as required, and the toString method (and perhaps some other methods too) would format these fields as you require into key-value pairs.

Objective-C get a class property from string

I've heard a number of similar questions for other languages, but I'm looking for a specific scenario.
My app has a Core Data model called "Record", which has a number of columns/properties like "date, column1 and column2". To keep the programming clean so I can adapt my app to multiple scenarios, input fields are mapped to a Core Data property inside a plist (so for example, I have a string variable called "dataToGet" with a value of 'column1'.
How can I retrieve the property "column1" from the Record class by using the dataToGet variable?
The Key Value Coding mechanism allows you to interact with a class's properties using string representations of the property names. So, for example, if your Record class has a property called column1, you can access that property as follows:
NSString* dataToGet = #"column1";
id value = [myRecord valueForKey:dataToGet];
You can adapt that principle to your specific needs.

Resources