M3 model#uses: src to innerclass - rascal

Is there an easy way to translate the "src" loc of model#uses to a class?
The problem I am having is I tried to use the model#declarations to match and find the class by location, but matching between file:// and project:// (m3 model) is not 100% pure (ignoring .scheme), comparing
begin.line >=
and
end.line <=
still results in 2 classes, when a "src" line is in the innerclass.
To summarise: Is there a function that returns the class, e.g.
loc classLoc = getClass( |home:///Workspaces/Rascal/src/Fruit.java|(150,1,<11,12>,<11,13>) );
That will return |java+class://Fruit|, having line 11 be a line in class Fruit.

Sure. Consider this example Java code:
public abstract class Fruit {
private class X {
}
int main() {
X x = new X();
return 1;
}
}
and consider I stored the M3 model in m and take the use of X located at this source location l = |home:///Workspaces/Rascal/rascal/src/org/rascalmpl/courses/example-project/src/Fruit.java|(150,1,<11,12>,<11,13>);
Then this expression will tell you to which declaration the class points to:
rascal>cl = m#uses[l];
set[loc]: {|java+class:///Fruit/X|}
To find out in which other class this class is then nested we invert the containment relation and look up the parent of the nested class like so:
rascal>m#containment<to,from>[cl]
set[loc]: {|java+class:///Fruit|}

Related

Get the name of a class and method as a string

To get the name of a project as a string I can use:
loc project = |project://Test/|;<br/>
str name = project.authority;
Is there something similar available for classes or methods?
I would like to write the contents of a class/method to disk and then use its name as the filename.
To answer my own question, I needed to use;
public void testcode( loc project){
M3 model = createM3FromEclipseProject(project);
for (loc l <- classes(model)) {
println(l.path);
}
Sorry, didn't read the docs thoroughly.

How to convert an Iterable of type X to type Y Re: Iterable<WordPair> to Iterable<String>

In pubspec.yaml, I'm using english_words library to generate wordpairs:
dependencies:
flutter:
sdk: flutter
# Contains a few thousand of the most used English words
# plus some utility functions.
english_words: ^3.1.0
Now the WordPair Class is not a subtype of String and so I can't use the Iterable's lambdas or functions like cast or retype to 'cast' the 'WordPairs' to Strings.
So, I had to write the function called getWords().
See below the Dart file, Model.dart, that contains this implementation.
You'll see the old line commented out where it was returning in the getter the type Iterable.
Would there be a more efficient way to do this?
For example, I didn't want to involve a List Class in the conversion, but I can't find any other way to successfully do this.
Thanks.
---------------- Model.dart
import 'package:english_words/english_words.dart' show WordPair, generateWordPairs;
import 'dart:collection';
/// Model Class
///
class Model {
String get randomWordPair => new WordPair.random().asPascalCase;
// Iterable<WordPair> get wordPairs => generateWordPairs().take(10);
Iterable<String> get wordPairs => getWords();
Iterable<String> getWords(){
Iterable<WordPair> pairs = generateWordPairs().take(10);
ListWords<String> words = new ListWords();
for (var pair in pairs) {
words.add(pair.asString);
}
return words;
}
}
class ListWords<E> extends ListBase<E> {
final List<E> l = [];
set length(int newLength) { l.length = newLength; }
int get length => l.length;
E operator [](int index) => l[index];
void operator []=(int index, E value) { l[index] = value; }
}
In Dart 2 you can use
iterable.cast<NewType>()
but it is prone to lead to inefficiency if the resulting list is accessed often, because it wraps the original iterable into a new one and has to forward every access.
Usually more efficient are
new List<NewType>.of(oldList)
or
new List.from<NewType.from(oldList)
I was not able to derive the difference between .of() and from() from the docs though (https://api.dartlang.org/dev/2.0.0-dev.50.0/dart-core/List/List.from.html, https://api.dartlang.org/dev/2.0.0-dev.50.0/dart-core/List/List.of.html)
At first glance, a loop that is collecting the result of an expression can generally be replaced with an appropriate .map method invocation on an Iterable. See if that will help.

How do I do more complex calculations when using projections in a named query in GRAILS 2.3.x?

I am using a named query with projections in my domain class. I would like the named query to return one of the values using the following equation:
sum(x * y) / sum(y)
I am familiar with formulas in mapping and attempted to do the following:
def formVar
static mapping = {
formulaVar formula: 'sum(x * y) / sum(y)'
}
Any help here would be awesome.
I might be misunderstanding your question, but you may want to check out the beforeUpdate and beforeInsert events.
Code placed in this block will allow you to preform calculations and manipulate the domain class properties before inserting/updating them.
It is documented in the Grails manual here http://grails.org/doc/2.3.7/guide/GORM.html#eventsAutoTimestamping
OK. Got this working like this:
class SumThing {
Double sumVar
static namedQueries = {
sums { op ->
projections {
property "sumVar"
}
}
}
static mapping = {
version false
columns {
sumVar formula: 'SUM(X * Y) / SUM(Y)'//X and Y being actual column names from your database
}
}
}

getOccupiedLocations Gridworld

So basically what I have to do is add crabcritters to gridworld randomly, which I did. Then, I need to use the getOccupiedLocations method to print an array of the occupied locations as ordered pairs. Any advice? Here's what I have so far:
package projects.critters;
import info.gridworld.actor.ActorWorld;
import info.gridworld.grid.Location;
public class Lab
{
public static void main (String[] args)
{
ActorWorld world = new ActorWorld();
for (int i =0; i<10; i++)
{
world.add (new CrabCritter());
}
world.show();
}
}
OK so the method getOccupiedLocations() returns an array of Locations. I don't know exactly what you mean by ordered pairs but if you mean (x, y) then that is easy to do. By default when you print out a Location it is an ordered pair. So all you have to do is loop through the occupied locations and print each out. For example:
for(Location l : world.getGrid().getOccupiedLocations()){
System.out.println(l);
}
And that's it...as for the comment: you don't need a language tag as this is a GridWorld question which obviously applies to Java.
Expanding on John Smith's answer. If you only want to print locations occupied by CrabCritter only, you can do this:
for(Location l : world.getGrid().getOccupiedLocations()){
if(world.get(l) instanceof CrabCritter)
System.out.println(l);
}

how to join relations in-sequence in hadoop pig?

I have one line data like this:
a\tb1,b2,..,bn\tc1,c2,..,cn
in which n is uncertain. And now, I want transform it to some lines like this:
a\tb1\tc1
a\tb2\tc2
...
a\tbn\tcn
Is it possible by pig latin, or has to use UDF?
If using the script:
A = LOAD 'file' AS (a, b, c);
B = FOREACH A GENERATE a, FLATTEN(TOKENIZE(b)), FLATTEN(TOKENIZE(c));
dump B;
I will get the resulr as following:
a\tb1\tc1
a\tb1\tc2
..
a\tb1\tcn
a\tb2\tc1
a\tb2\tc2
..
a\tb2\tcn
..
It isn't the data I wanted. Does anyone have ideas?
IMO too many people who use Pig are resistant to write UDFs. In your case, the UDF you'd need to do this is fairly simple. Here's sample code (untested)
public class InSequenceJoin extends EvalFunc<DataBag>
{
public DataBag exec(Tuple input) throws IOException {
String b = (String) input.get(0);
String c = (String) input.get(1);
String[] bArray = b.split(",");
String[] cArray = c.split(",");
DataBag bag = BagFactory.getInstance().newDefaultBag();
for (int i = 0; i < bArray.length && i < cArray.length; i++) {
Tuple tuple = TupleFactory.getInstance.newTuple(2);
tuple.set(0, bArray[i]);
tuple.set(1, cArray[i]);
bag.add(tuple);
}
return bag;
}
}
define InSequenceJoin mysourcepath.InSequenceJoin();
A = LOAD 'file' AS (a, b, c);
B = FOREACH A GENERATE a, FLATTEN(InSequenceJoin(b,c));
dump B;
You could add validation on if the sizes of the arrays match if you need to in the UDF. You could replace the String split I used in example with whatever you truly require.
I'd try to use datafu's bag UDFs.
Load the data as you've done, then use Enumerate to enumerate the bag elements, then flatten (which gives you the cross join between the bag elements as you've seen) and then you can filter on the indexes added to the bag elements.
See here: https://github.com/linkedin/datafu

Resources