how to assign value in scala conditionally in template of play2.1 - templates

I am doing some conditional coding in scala template.
just tell me how to write following java logic into scala.html template.
String temp = "";
if(!cityName.equals(temp)){
temp=cityName;
}
else{
//do something..
}

Scala views allows you to define some variables with #defining block (see Reausable values), however it doesn't allow you to re-assignate it, so your pseudocode won't work as expected.
In such case you need to write custom getter in your model, which will return a valid value, instead doing it with temporary values in the views. You can also access any static Java method which will process your incoming string according to some conditions.
I must to say, that I have no idea what exactly you want to achieve, however I think, that can be solved with solutions proposed above.

Related

How to automatically initialize component parameters?

While doing a game engine that uses .lua files in order to read parameter values, I got stuck when I had to read these values and assign them to the parameters of each component in C++. I tried to investigate the way Unity does it, but I didn't find it (and I'm starting to doubt that Unity has to do it at all).
I want the parameters to be initialized automatically, without the user having to do the process of
myComponentParameter = readFromLuaFile("myParameterName")
for each one of the parameters.
My initial idea is to use the std::variant type, and storing an array of variants in order to read them automatically. My problems with this are:
First of all, I don't know how to know the type that std::variant is storing at the moment (tried with std::variant::type, but it didn't work for the template), in order to cast from the untyped .lua value to the C++ value. For reference, my component initialization looks like this:
bool init(luabridge::LuaRef parameterTable)
{
myIntParameter = readVariable<int>(parameterTable, "myIntParameter");
myStringParameter = readVariable<std::string>(parameterTable, "myStringParameter");
return true;
}
(readVariable function is already written in this question, in case you're curious)
The second problem is that the user would have to write std::get(myIntParameter); whenever they want to access to the value stored by the variant, and that sounds like something worse than making the user read the parameter value.
The third problem is that I can't create an array of std::variant<any type>, which is what I would like to do in order to automatically initialize the parameters.
Is there any good solution for this kind of situation where I want the init function to not be necessary, and the user doesn't need to manually set up the parameter values?
Thanks in advance.
Let's expand my comment. In a nutshell, you need to get from
"I have some things entered by the user in some file"
to:
"the client code can read the value without std::get"
…which roughly translates to:
"input validation was done, and values are ready for direct use."
…which implies you do not store your variables in variants.
In the end it is a design question. One module somewhere must have the knowledge of which variable names exist, and the type of each, and the valid values.
The input of that module will be unverified values.
The output of the module will probably be some regular c++ struct.
And the body of that module will likely have a bunch of those:
config.foo = readVariable<int>("foo");
config.bar = readVariable<std::string>("bar");
// you also want to validate values there - all ints may not be valid values for foo,
// maybe bar must follow some specific rules, etc
assuming somewhere else it was defined as:
struct Configuration {
int fooVariable;
std::string bar;
};
Where that module lives depends on your application. If all expected types are known, there is no reason to ever use a variant, just parse right away.
You would read to variants if some things do not make sense until later. For instance if you want to read configuration values that will be used by plugins, so you cannot make sense of them yet.
(actually even then simply re-parsing the file later, or just saving values as text for later parsing would work)

C++ dynamic code generation based on input parameter

I have the following function:
void scan(DataRow& input) {
if(input.isRaw()) {
...
}
if(input.isExternal()) {
...
}
if(input.hasMultipleFields()) {
...
for(auto& field: input.fields()) {
if(field.size() == 2) {
...
}
}
}
}
The DataRow class has many sub-classes and all the is functions above are virtual.
This function is used to scan several large groups of data rows. For each group, all data row instances will have the same property (e.g., all raw, all external).
So instead of having all these if/else logics in the scan function, I am thinking if there is a way to generate ad-hoc code. For example, now I already know my next group are all raw (or all not), then I can get rid of the first if branch.
In Java, I used to do such kind of things by generating byte code for class and dynamically load the generated class in JVM. I know the same trick does not work for C++ but I have little experience how to do this. Can anyone give some hint? Thanks!
You cannot easily manipulate executable code during runtime. But your question doesn’t look like you’d have to go down that road anway.
You have groups of rows with similar properties and special processing logic for each group. Also, there seems to be a small fixed number of different kinds of groups.
You have all necessary information to split up your code at compile time – “programming time” actually. Split the scan() function into one function for each kind of group and call scan_raw(), scan_external(), etc. accordingly.
This reduces the number of if condition checks from once per row to once per group. As an added benefit the separate scan functions can use the appropriate derived class as their parameter type and you can get rid of the whole isSomething() machinery.
Hm, at this point I’m tempted to point you towards std::variant and std::visit (or their Boost equivalents). That could be a larger refactoring, though. Because when using them you’d ideally use them as a complete replacement for your current inheritance based polymorphism approach.

Does ember.js function.property() always succeed a function with a return statement?

I've noticed that all the cases in ember.js the function.property() is found in a function with a return statement. Is that always true? If not, can you give me a case where a function that doesn't have a return statement but has a .property()?
You need to see a property as a attribute. Ember doesn't make a distinction between functions and attributes. If you have a property it must return a value, since it acts like an attribute.
If you're looking not to return a value, but you want something to change based on another property, you'd use the observable pattern. Have a look in the guide for more information.

Iterate and update BindingList items using a one-liner

I have a BindingList I want to update certain items,but in order to use the Foreach available only for the List<> I have to initialize a new List with the BindingList items. like this:
new List<ScanData>(ScanDataList)
.FindAll(i => i.Badge == badge)
.ForEach(x =>x.EmpName = empname);
And that's the simplest way I found to do it, but I don't want to start with the New keyword, is there any other simpler way to Iterate over the BindingList items and update them using a one-liner like the above? (I put it in three lines for readability).
Id like just to remove the New keyword but that just doesn't work,
if a new function helps that is also acceptable, if its generic for any BindingList would be perfect.
Note: Im using compact framework 2.0
I don't want to initialize a variable Im not gonna use.
Thanks.
This question is a bit silly. There's no reason you have to do it in one line of code and avoid declaring a variable. If you use the new operator you are initializing an instance of an object, regardless of whether you are declaring a variable for it or not.
That being said, I do not know what your ScanDataList is... There's a linq expression equivalent to FindAll called Where which may be more efficient than FindAll (because it doesn't have to create a new list, it just lazily iterates). If your ScanDataList is already IEnumerable then you can probably do something like this...
ScanDataList.Where(i => i.Badge == badge).ToList().ForEach(x=>x.EmpName = empname);
Even if your ScanDataList is not enumerable, you could implement an extension method of your own to help you accomplish this, but it seems like a lot of work for something that can easily be achieved without arbitrary unnecessary constraints (no new, no variables, etc).
So to clarify, I would probably use .Where LINQ expression because it is probably a bit more efficient because it doesn't need to create a new List. However, using that same logic, I'd probably avoid ToList() and separate your code into two lines with something like.
foreach(Employee emp in ScanDataList.Where(i => i.badge == badge))
emp.EmpName = empname;
This way, no additional list is created.

Replace giant switch statement with what?

I have a code that parses some template files and when it finds a placeholder, it replaces it with a value. Something like:
<html>
<head>
<title>%title%</title>
</head>
<body bgcolor="%color%">
...etc.
In code, the parser finds those, calls this function:
string getContent(const string& name)
{
if (name == "title")
return page->getTitle();
else if (name == "color")
return getBodyColor();
...etc.
}
and then replaces the original placeholder with returned value.
In real case, it is not a dummy web page, and there are many (50+) different placeholders that can occur.
My code is C++, but I guess this problem exists with any language. It's more about algorithms and OO design I guess. Only important thing is that this must be compiled, even if I wanted I couldn't have any dynamic/eval'd code.
I though about implementing Chain of Responsibility pattern, but it doesn't seem it would improve the situation much.
UPDATE: and I'm also concerned about this comment in another thread. Should I care about it?
Use a dictionary that maps tag names to a tag handler.
You want replace conditional with polymorphism. Roughly:
string getContent(const string& name) {
myType obj = factory.getObjForName(name);
obj.doStuff();
}
where doStuff is overloaded.
Have you considered XSLT? It's very well suited to this kind of thing. I developed a content management system that did the exact same thing and found XSLT to be very effective. The parser does a lot of the work for you.
UPDATE: Steven's comment raises an important point- you'll want your templates to be valid XHTML if you decide to go the XSLT route.
Also- I would use a different delimiter for your replacement tokens. Something less likely to occur naturally. I used #!PLACEHOLDER#! in my CMS.
i'll combine 3 ideas:
(from Steven Hugig): use a factory method that gets you a different class for each selector.
(from Neil Butterworth): inside the factory, use a dictionary so you get rid of the big switch(){}.
(mine): add a setup() method to each handler class, that adds itself (or a new class instance) to the dictionary.
explaining a bit:
make an abstract class that has a static dict, and methods to register an instance with a selector string.
on each subclass the setup() method registers itself with the superclass' dict
the factory method is little more than a dictionary read
Rather than parsing, have tried just reading the template into a string and then just performing replaces.
fileContents = fileContents.Replace("%title%", page->getTitle());
fileContents = fileContents.Replace("%color%", getBodyColor());
As "Uncle" Bob Martin mentioned in a previous podacast with Joel and Jeff, pretty much anything you come up with is going to essentially be reproducing the big switch statement.
If you feel better implementing one of the solutions selected above, that's fine. It may make your code prettier, but under the covers, it's essentially equivalent.
The important thing is to ensure that there is only one instance of your big switch statement. Your switch statement or dictionary should determine which class handles this tag, and then subsequent determinations should be handled using polymorphism.