Why is List.sort method striked through? - sorting

I have a map of errors and the number of their occurrences in some situation. I want to have a list, which contains that information in order of descending number of errors (i. e. the most frequent error is first element, the second-most - the second etc.).
I wrote following code:
List<Map.Entry<String,Integer>> entryList = new ArrayList<>(errors.entrySet());
entryList.sort{a, b -> b.value <=> a.value}
It works fine, but the sort is striked through (in Eclipse IDE with the Groovy plugin).
Why? Is that method deperecated? If so, what is the correct way to sort a list in Groovy?

Use the Iterable version of sort instead
Because of deprecation - have a look at the docs. Some of sort methods are deprecated in favor of others.

Related

android.applicationVariants.size() always returns 0

I noticed that application.applicationVariants.size() always returns 0, although I know there are variants, since I can iterate them: android.applicationVariants.all {println it}. Because of that I am also not able to iterate the collection with each.
What am I missing here?
This is normal behavior. Notice this sentence in the changelog (v 0.5.5):
access to the variants container don't force creating the task. This
means android.[application|Library|Test]Variants will be empty during
the evaluation phase. To use it, use .all instead of .each

Ndepend find actual number of method usages

Let's say I have method A.M1.
It is called in B.M2 2 times and in B.M3 3 times.
I need to find all number of usages (like Resharper does through find usages interface). So the sum for method calls would be 5.
Following Query:
from m in Methods
where m.HasAttribute("specific attribute")
orderby m.MethodsCallingMe.Count() descending
select new { m, m.MethodsCallingMe }
gives me only 2 usages for method A.M1.
Could you please help me to find the usages number?
It's difficult or impossible to do with NDepend. NDepends shows which methods are calling specified method and not count in this situation them and even not count them recursively or through call graph.
So try to use other techniques. By first of all, why you need such metric? Some kind of method rank?
Anyway a pretty simple way to achieve it, is using RegEx experssion. You can use also NDepend API or regex and ndepend api together. For example, get all method names from source code base using nDepend API and then using regex for each method name count matches except method definition itself.

ruby shorthand for conditionals, when to use instance variables and efficiency of looping through parsed xml versus storing as hash

I'm learning ruby and have a few questions about some code I wrote for a newbie challenge. Purpose of challenge is to find country with largest population from an xml document.
I've included my code below. Questions I have are:
Is there a way to avoid having to initialize the #max_pop variable (#max_pop=0)?
Is there shorthand for combining the entire conditional block into 1 line?
Do I have to use instance vars #max_pop, #max_pop_country? Got error without them.
Which is more efficient:
Loop through each country and check if pop > max_pop (approach in code below)
Create pop hash (pop[:country]) and then find country with highest pop
Is there hash method to return key value pair for largest element in hash (to do 4.1)?
Source Code:
#max_pop=0
doc.elements.each("cia/country") do |country|
if country.attributes["population"].to_i > #max_pop
#max_pop=country.attributes["population"].to_i
#max_pop_country=country.attributes["name"]
end
end
puts "country with largest pop is #{#max_pop_country} with pop of #{#max_pop}
I am not familiar with rexml, but you ought to be able to simplify everything to something like this:
max_pop_elem = doc.elements.enum_for(:each, "cia/country").max_by { |c| c.attributes["population"].to_i }
max_pop_country = max_pop_elem.attributes["name"]
max_pop = max_pop_elem.attributes["population"].to_i
Yes, see above.
Yes, see above.
No. You should use local variables instead of instance variables when possible.
Don't worry about efficiency of CPU time until you have a slow program. Then use ruby-prof. Until then, just worry about the efficiency of coding time (do things the easy way).
Yes, just do key, value = hash.max_by{|k,v| v}.
In general, if you are going to be iterating over things you should learn about Ruby's Enumerable module. I made a reference sheet for it here.

can we use two criterias in sort

I have been using the following code for sorting a domain's results
vpisort.sort{it.price}
I was wondering If i could use something like
vpisort.sort{it.price-it?.discount}
I've found this post. You can try using this in your case:
vpisort.sort { a, b -> a.price <=> b.price ?: a?.discount <=> b?.discount }
It comapres price first and then, only if a and b are equal by price and result is zero, using Elvis operator it compares a and by by discount.
hm. This is not a grails, but a groovy question. With this in mind, the solution is simple:
open the groovy console and give your line a try. Or check out these examples:
http://groovy.codehaus.org/JN1015-Collections
there is also another question like this one on SO:
Groovy list.sort by first, second then third elements
hope that helps!
Update: If you want to have a default sort order for your domain class, take a look at this GORM feature: http://grails.org/doc/latest/guide/single.html#ormdsl (5.5.3 Default Sort Order)

Groovy 1.8 :: LINQ Applied

UPDATE 8/31/2011
Guillaume Laforge has nearly done it:
http://gaelyk.appspot.com/tutorial/app-engine-shortcuts#query
Looks like he's doing an AST transform to pull off the:
alias as Entity
bit. Cool stuff, Groovy 1.8 + AST transform = LINQ-esque queries on the JVM. GL's solution needs more work as far as I can see to pull off full query capabilities (like sub queries, join using(field) syntax and the like), but for his Gaelyk project apparently not necessary.
EDIT
As a workaround to achieving pure LINQ syntax, I have decided to def the aliases. Not a huge deal, and removes a major hurdle that would likely require complex AST transforms to pull off.
So, instead of:
from c as Composite
join t as Teams
...
I now define the aliases (note: need to cast to get auto complete on fields):
def(Teams t,Composite c,Schools s) = [Teams.new(),Composite.new(),Schools.new()]
and use map syntax for from, join, etc.
from c:Composite
join t:Teams
...
To solve issue #2 (see original below), add instance level getProperty methods to each pogo alias (whose scope is limited to ORM closure in which it is called, nice). We just return the string property name as we're building an sql statement.
[t,c,s].each{Object o-> o.metaClass.getProperty = { String k-> k } }
Making "good" progress ;-)
Now to figure out what to do about "=", that is tricky since set property is void. May have to go with eq, neq, gt, etc. but would really prefer the literal symbols, makes for closer-to-sql readability.
If interested, LINQ is doing quite a bit behind the scenes. Jon Skeet (praise his name) has a nice SO reply:
How LINQ works internally?
ORIGINAL
Have been checking out LINQ, highly impressed.
// LINQ example
var games =
from t in Teams
from g in t.Games
where g.gameID = 212
select new { g.gameDate,g.gameTime };
// Seeking Groovy Nirvana
latest { Integer teamID->
from c as Composite
join t as Teams
join s as Schools on ( schoolID = {
from Teams
where t.schoolID = s.schoolID } )
where t.teamID = "$teamID"
select c.location, c.gameType, s.schoolName
group c.gameID
order c.gameDate, c.gameTime
}
The proposed Groovy version compiles fine and if I def the aliases c,t,s with their corresponding POGO, I get strong typed IDE auocomplete on fields, nice. However, nowhere near LINQ, where there are no (visible) variable definitions other than the query itself, totally self contained and strongly typed, wow.
OK, so can it be done in Groovy? I think (hope) yes, but am hung up on 2 issues:
1) How to implicitly populate alias variable without def'ing? Currently I am overriding asType() on String so in "from c as Composite", c gets cast to Composite. Great, but the IDE "thinks" that in closure scope undefined c is a string and thus no autocomplete on POGO fields ;-(
2) Since #1 is not solved, I am def'ing the aliases as per above so I can get autocomplete. Fine, hacked (compared to LINQ), but does the trick. Problem here is that in "select c.location, c.gameType...", I'd like the fields to not be evaluated but simply return "c.location" to the ORM select method, and not null (which is its default value). getProperty() should work here, but I need it to only apply to pogo fields when called from ORM scope (e.g. orm field specific methods like select, order, group, etc.). Bit lost there, perhaps there's a way to annotate orm methods, or only invoke "special" pogo getProperty via orm method calls (which is the closure's delegate in above nirvana query).
Should point out that I am not looking to create a comprehensive LINQ for Groovy, but this one particular subset of LINQ I would love to see happen.
One of the biggest reasons for Guillaume to use an AST transform is because of the problem with "=". Even if you use == for the compare as normally done in Groovy, from the compareTo method that is called for it, you cannot make out a difference between ==, !=, <=, >=, <, >. There are two possible paths for this in later versions of Groovy that are in discussion. One is to use for each of those compares a different method, the other is to store a minimal AST which you can access at runtime. This goes in the direction of C# and is a quite powerful tool. The problem is more about how to do this efficiently.

Resources