suppress list elements that have already been encountered - velocity

Hi I have a velocity template that I am trying to edit
it currently has a block that looks like
#foreach( $element in $myList )
$element.field1 ($element.field2) issued by $element.field ($element.field4 )
<br><br>
#end
the problem is some elements in the list are duplicated and I need to suppress the duplicates.
psuedo code for what I want is
for each element in list
if element is not in displayed
display element
add element to displayed
endif
endfor
can someone point me in the right direction?

This kind of logic (de-duplication) is probably something to be avoided in your view (Velocity) layer. Following Model-View-Controller, it would be better to have this logic managed by controller classes, leaving the Velocity template to simply render the data structure it is passed.
For example, by using a data structure such as a java.util.Set, duplicates would not be admitted and so there would be no need for the template to de-duplicate.
Personally I found Rob Harrop's Pro Jakarta Velocity a really good guide to MVC, especially Chapter 4 "Using Velocity in an MVC environment".
Have the model use a Set, have your controller code populate the set, and then the simple loop in your template code can be used as it is now.
In general, the less logic you implement in your view layer, the better. It will also make your code easier to test, so you can verify its behaviour without having to fire up the presentation components, app servers etc etc.
If there really is no choice and the logic absolutely must be written in the template, then the following implements the psuedocode presented:
#set($displayed = [])
#foreach( $element in $myList )
#if(!$displayed.contains($element))
$element.field1 ($element.field2) issued by $element.field ($element.field4 )
<br><br>
#set($ignore = $displayed.add($element))
#end
#end
Note the messiness with #set($ignore = $displayed.add($element)) - this has to be done to suppress the output from java.util.List's add() method (boolean) from being output. Another reason not to write this in template code!
Of course, you would also need to make sure that equals() is correctly implemented on the type added to the list so that the List operations - contains() and add() work correctly.
Definitely an inferior solution to the MVC approach above, but presented as an option of last resort.

Related

How to prevent empty list errors in in clause in sql?

One common problem we have in our codebase is that people forget to check if a list is empty before using it in an in clause.
For example (in Scala with Anorm):
def exists(element: String, list: List[String]): Boolean =
SQL("select {element} in {list} as result")
.on('element -> element, 'list -> list)
.as(SqlParser.bool("result").single)
This code works perfectly well as long as list has at least one element.
If it has 0 elements, you get a syntax error, which is weird if you're used to other programming languages that would allow this empty list case.
So, my question is: what's the best way to prevent this error from happening?
Initially, we did this:
def exists(element: String, list: List[String]): Boolean =
if (list.nonEmpty) {
SQL("select {element} in {list} as result")
.on('element -> element, 'list -> list)
.as(SqlParser.bool("result").single)
} else {
false
}
This works perfectly well, and has the added advantage that it doesn't hit the database at all.
Unfortunately, we don't remember to do this every time, and it seems that 1-2 times a month we're fixing an issue related to this.
An alternate solution we came up with was to use a NonEmptyList class instead of a standard List. This class must have at least one element. This works excellent, but again, people have not been diligent with always using this class.
So I'm wondering if there's an approach I'm missing that prevent this type of error better?
It looks like you've already found a way to resolve this problem - you have an exists() function which handles an empty list cleanly. The problem is that people are writing their own exists() functions which don't do that.
You need to make sure that your function is accessible as a utility function, so that you can reuse it whenever you need to, rather than having to rewrite the function.
Your problem is an encapsulation problem: the Anorm API is like an open flame and people can burn themselves. If you rely just on people to take precautions, someone will get burnt.
The solution is to restrict the access to the Anorm API to a limited module/package/area of your code:
Anorm API will be private and accessible only from very few places, where it is going to be easy to perform the necessary controls. This part of the code will expose an API
Every other part of the code will need to go through that API, effectively using Anorm in the "safe" way

.bind vs string interpolation in aurelia

In our code base we have a mixture of the following:
attribute="${something}", attribute="${something | converter}", etc.
attribute.bind="something", attribute.bind="something | converter"
I find the latter easier to read.
The examples I'm referring to are exactly like the above; i.e., they do not add any additional string content.
I think that it's easier on Aurelia too. Am I correct?
Also, for these specific cases where no actual interpolation is
involved, is there any benefit to the first form? (other than it is
two characters less to type.)
Given the examples you have shown, I would recommend using option 2. It really isn't "easier on Aurelia," but it is more explicit that you are binding the value of that attribute to the property listed.
Original Answer Below
The benefit of the first option is when you have, for example, an attribute that accepts many values but as a single string. The most common example of this is the class attribute. The class attribute accepts multiple classes in a space-separated list:
<div class="foo bar baz"></div>
Imagine we only want to add or remove the class baz from this list based on a prop on our VM someProp while leaving the other classes. To do this using the .bind syntax, we would have to create a property on our VM that has the full list but adds or removes baz as determined by the value of someProp. But using the string interpolated binding, this becomes much simpler:
<div class="foo bar ${someProp ? 'baz' : ''}"></div>
You can imagine how this could be extended with multiple classes being added or removed. You could maybe create a value converter to do this using the .bind syntax, but it might end up with something that wasn't as readable.
I could imagine a value converter being created that might look something like this in use:
<div class.bind="someProp | toggleClass:'baz':'foo':bar'"></div>
I really think this is much less readable than using the string interpolation syntax.
By the way, the value converter I imagined above would look like this:
export class ToggleClassValueConverter {
toView(value, toggledClass, ...otherProps) {
return `${otherProps.join(' ')} ${value ? toggledClass : ''}`;
}
}
The best part is that I'm still using string interpolation in the value converter :-)
After wading through the tabs I'd already opened I found this. Although it's not quite the same thing, and it's a bit old, there's a similar thing talked about on https://github.com/aurelia/templating-binding/issues/24#issuecomment-168112829 by Mr Danyow (emphasis mine)
yep, the symbol for binding behaviors is & (as opposed to | for value converters).
<input type="text" data-original="${name & oneTime}" value.bind="name" />
Here's the standard way to write a one-time binding. This will be a bit more light-weight in terms of parsing and binding:
<input type="text" data-original.one-time="name" value.bind="name" />
I don't know if it applies to the .bind/${name} case as well as the oneTime one in the example, but perhaps if it comes to his attention he can say either way.
Given this isn't a cut and dry answer, I'll be marking Ashley's as the answer as it confirms the legibility question and provides useful information on other use cases should anyone else search on similar terms.

Proper error propagation in clojure

I'm currently working on my first major project in clojure and have run into a question regarding coding style and the most "clojure-esque" way of doing something. Basically I have a function I'm writing which takes in a data structure and a template that the function will try to massage the data structure into. The template structure will look something like this:
{
:key1 (:string (:opt :param))
:key2 (:int (:opt :param))
:key3 (:obj (:tpl :template-structure))
:key4 (:list (:tpl :template-structure))
}
Each key is an atom that will be searched for in the given data structure, and it's value will be attempted to be matched to the type given in the template structure. So it would look for :key1 and check that it's a string, for instance. The return value would be a map that has :key1 pointing to the value from the given data structure (the function could potentially change the value depending on the options given).
In the case of :obj it takes in another template structure, and recursively calls itself on that value and the template structure, and places the result from that in the return. However, if there's an error I want that error returned directly.
Similarly for lists I want it to basically do a map of the function again, except in the case of an error which I want returned directly.
My question is what is the best way to handle these errors? Some simple exception handling would be the easiest way, but I feel that it's not the most functional way. I could try and babysit the errors all the way up the chain with tons of if statements, but that also doesn't seem very sporting. Is there something simple I'm missing or is this just an ugly problem?
You might be interested in schematic, which does pretty similar stuff. You can see how it's used in the tests, and the implementation.
Basically I defined an error function, which returns nil for correctly-formatted data, or a string describing the error. Doing it with exceptions instead would make the plumbing easier, but would make it harder to get the detailed error messages like "[person: [first_name: expected string, got integer]]".

Is it meaningful to verifyText() on an element that has just had type() executed on it?

I'm curious about whether the following functional test is possible. I'm working with PHPUnit_Extensions_SeleniumTestCase with Selenium-RC here, but the principle (I think) should apply everywhere.
Suppose I execute the following command on a particular div:
function testInput() {
$locator = $this->get_magic_locator(); // for the sake of abstraction
$this->type( $locator, "Beatles" ); // Selenium API call
$this->verifyText( $locator, "Beatles" ); // Selenium API call
}
Conceptually, I feel that this test should work. I'm entering data into a particular field, and I simply want to verify that the text now exists as entered.
However, the results of my test (the verifyText assertion fails) suggest that the content of the $locator element are empty, even after input.
There was 1 failure:
1) test::testInput
Failed asserting that <string:> matches PCRE pattern "/Beatles/".`
Has anyone else tried anything like this? Should it work? Am I making a simple mistake?
You should use verifyValue(locator,texttoverify) rather than verifyText(locator,value) for validating the textbox values
To answer your initial question ("Is it meaningful ..."), well, maybe. What you're testing at that point is the browser's ability to respond to keystrokes, which would be sort of lame. Unless you've got some JavaScript code wired to some of the field's properties, in which case it might be sort of important.
Standard programmer's answer - "It depends".

Iteration-scoped variable in JSF / Richfaces iteration?

OK, this should be an interesting one I think. I want to minimize the number of invocations to my Seam component inside an iteration. I am using Seam 2.2.1.CR1, Richfaces 3.3.3.Final, JSF 1.2 and Facelets.
Please take a look the following Facelet snippet:
<rich:datatable value="#{myBean.products}" var="prod">
<rich:column rowspan="#{rowspan.calcHomePageProductRowspan(prod)}">
#{prod.name}
</rich:column>
<rich:column rowspan="#{rowspan.calcHomePageProductRowspan(prod)}">
#{prod.number}
</rich:column>
...
<rich:column rowspan="#{rowspan.calcHomePageProductRowspan(prod)}">
#{prod.somethingElse1}
</rich:column>
<rich:column rowspan="#{rowspan.calcHomePageProductRowspan(prod)}">
#{prod.somethingElse2}
</rich:column>
...
<rich:column rowspan="#{rowspan.calcHomePageProductRowspan(prod)}">
#{prod.somethingElse3}
</rich:column>
</rich:datatable>
In the above code I am computing an attribute (here the rowspan, but that doesn't really matter, it could be any attribute or value at all, so please don't focus on that) by evaluating an EL expression. As you can see, the method that calculates the value takes the current prod as an argument.
I have made an internal optimization in the rowspan Seam component, and it keeps in a HashMap all the already computed values for products. So, when the the EL expression is evaluated at the second rich:column, the rowspan first looks up in the HashMap the already computed value, and returns that, instead of re-computing all over again.
Although this is better that re-computing all over again, I still have to make an invocation to a Seam component. Is there a way to somehow invoke the Seam component only once, and somehow retain the computed value for the current iteration?
The analogous to Java would be to define a variable inside the loop at each iteration, and reuse it throughout the iteration.
Note: I have already made other Seam-oriented optimizations such as #BypassInterceptors, the Seam component is in the EVENT scope, so no hierarchical lookups take place etc.
Is there a way to somehow invoke the Seam component only once, and somehow retain the computed value for the current iteration?
Sure, in theory.
But I am not sure I fully understand your question. Which seam component are you talking about? rowspan?
If that is the case, then yeah, its invoked each time you call it, which makes sense. You are looping through a dataTable, and for each row you call it.
Without knowing more details about what you are trying to do, its difficult to suggest an answer. Is the code slow? Is that why you need to optimize further?
Update
Try this, though I am not sure if it works
<rich:dataTable value="#{myBean.products}" var="prod">
<ui:param name="myrowspan" value="#{rowspan.calcHomePageProductRowspan(prod)}"/>
<rich:column rowspan="#{myrowspan}">
#{prod.name}
</rich:column>
</rich:dataTable>
Second update
So if you don't change your code to be a #Out, #Factory, #Unwrap or similar, then this will always be evaluated each time it runs. This is just how JSF works.
That's why they say that you should do this in your getters, because JSF will call this for each JSF Phase.
public List<Foo> getFoo() {
if(this.field != null) { 
field = (List)entityManager.createQuery("from Foo").getResultList();
}
return this.field;
}
If you wouldn't have cached the list, and checking for null, JSF would hit the database for each phase and for each row in the data table.
Thus this is just something you have to live with.