Increment a variable inside a FOR loop - eclipse-emf

I'm trying to count how many times a condition is true inside a FOR loop.
I declared an additional variable for the template (FOUND : Integer), and I'm trying to increment it every time the [IF] condition is "true", but the variable increments only the first time, then it gets back to its original value.
Basically, if FOUND = 1 at the beginning, at every loop I get 2 in output.
This is the code I'm trying to use:
[template public genPartnerLinkJavaFile(aProcess : Process, varNameList : Sequence{String} .... etc)
{FOUND : Integer = 1;}]
[file ('PL'+aPartnerLink.name.toUpperFirst()+'.java', false, 'UTF-8')]
public class ['PL'+aPartnerLink.name.toUpperFirst()/] {
[for (aVariable : Variable | aProcess.eAllContents(Variable))]
[if (varNameList->includes(aVariable.name.toString() ) )]
[FOUND+1/]
[i/]
[/if]
[/for]
Do you know how could I achieve this or something similar?
Thanks

In Acceleo, all variables are final. You can use a collection to store all used values and then compute its size or you could use a Java service if you really want to use a value. I would recommend using a query to compute all the useful elements since the result of the evaluation of a query is stored in a cache, the impact on the performances will be minimal.

Related

Leave cell unchanged if condition is not met

I need a function that will allow to recopy what is already written in a cell.
I'd call it NothingHasChanged() and I'd use this way:
In a cell chosen randomly I'd type:
if(A1="Yes"; "The cell A1 contained Yes at least once"; NothingHasChanged() )
This way i'd keep history of the cell value overtime.
I tried to do a script :
function FormulaToValueV2() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getCurrentCell().offset(599, 0).activate();
spreadsheet.getCurrentCell().offset(-599, 0).copyTo(spreadsheet.getActiveRange(),
SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
spreadsheet.getCurrentCell().offset(-599, 0).activate();
spreadsheet.getCurrentCell().offset(599, 0).copyTo(spreadsheet.getActiveRange(),
SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
};
that I generated from a macro I did by copying as a value to override the formula but it throws me an error saying that I don't have the permission to "copyto".
I'm desperate actually, I'm not a programmer
Thanks for the help and stay safe
EDIT : Here is a link with no personal datas of what i'm trying to do.
https://docs.google.com/spreadsheets/d/19-Jv2kDUXxMXUid1EqDmwceZXU3w6U2Nd5uqwr3Swes/edit#gid=0
As you can see, i'd like to overcome the circular reference problem : if the condition is not met, you don't change the value that was in the cell. This way, i can keep track of the datas contained in "actual Day" into "saved Days".

Iterate over an optional list of integers ifPresent

I have an Optional list of integers. I wish to see if the list is actually present and then convert it into a stream. One way of doing this is
Optional<List<Integer>> listOfNumbers = ...
if (listOfNumbers.isPresent()) {
listOfNumbers.get().stream();
}
But, I dont wish to have that if condition. I searched and saw that ifPresent() does the same thing but when I do listOfNumbers.ifPresent(this::get)), I get the following error:
non-static variable this cannot be referenced from a static context
Can you please help me do this in an efficient manner? This is still new to me so if there's anything incorrect in my understanding please let me know.
As pointed in the comments, the cleanest way to get a Stream is to use Optional.orElse method with Collections.emptyList:
Stream<Integer> stream = listOfNumbers.orElse(Collections.emptyList()).stream();
The other possible solution with Optional.map:
Stream<Integer> stream = listOfNumbers.map(List::stream).orElse(Stream.empty());
Update Java 9 :
Since jdk9, Optional has a new method stream(), which returns either a stream of one element, or an empty stream.
Thus, going from an Optional<List<Integer>> to an Stream<Integer> becomes
Stream<Integer> streamOfNumbers = listOfNumbers.stream().flatMap(List::stream);
This is How I did that on my last Project.
Optional<List<Integer>> listOfNumbers = ...
listOfNumbers.ifPresent((numbers) -> {
...
});
The ifPresent will check if the size of your Optional variable reaches it's limit and loop through your list.
You can replace ifPresent with forEach if you want to do it separately instead.

Lazy computation of items in list until required element is found

I am trying to get my head around making this requirement as efficient as possible, because it is part of a combinatorial problem solver, so every little bit helps in the grand scheme of things.
Lets say I have a list of elements, in this case called transitions.
val possibleTransitions : List[Transition] = List[...] //coming from somewhere
I want to perform an (somewhat expensive) computation on each transition, to obtain another object, in this case called a State.
The natural way for me to do it is using a for-comprehension or a map. The former for me is more convenient because I want to filter out a few irrelevant State objects, such as those which were already processed earlier.
val newStates = for {
transition <- possibleTransitions
state <- computeExpensiveOperation(transition)
if (confirmNewState(state))
} yield state
State contains a value, lets call it value(), which indicates some kind of attractiveness of that state. If the value() is very low (attractive) I want to discard the rest of the list and use that. Since possibleTransitions could be a very long list (thousands), ideally I avoid doing that computeExpensiveOperation if for example the first State object already has the value() I want.
On the other hand, if I don't find any item with an attractive value() I want to keep all of them and add them to another list.
val newPending = pending ++ newStates
I was trying to use a Stream for this, to avoid computing all the values before processing them. If I use find() and I don't find the required item then I won't be able to get the items in the stream (since its use-once).
The only thing I can see possible at the moment is to use possibleItems.toStream() in the for-comprehension and create another collection, iterating through each item one by one until either I find the item (and discard the collection) or no (and use the collection with all items).
Am I missing some smarter more efficient way to do this?
I would use lazy views and convert them to a stream to cache the intermediate result, then you can get the information you need:
val newStates = for {
transition <- possibleTransitions.view
state <- computeExpensiveOperation(transition)
if (confirmNewState(state))
} yield state
val newStatesStream = newStates.toStream // cache results
val attractive = newStatesStream.find(isAttractive(_))
attractive match {
case Some(a) => // do whatever
case None => {
val newPending = pending ++ newStatesSteam
}
}
As the stream is lazy it will only be computed until the first element is found in the line with val attractive. If there is no attractive element the complete stream will be computed and cached and None will be returned.
When computing the new pending elements we can just append this stream to pending. (By the way: pending should probably be a Queue)

Efficiently iterating large amounts of data

Introduction
First of, I must say this is being done for an online game server, which keeps track of every object in a map, be it a player or an AI (NPC or however you want to call it).
It must not only keep track of them, but notify among the players their near players. I've solved this, and I'm currently using a multi-threaded approach, which perfectly works.
My problem
I'm storing all that objects in an hash table. We could consider that hash table to be an unordered_map, though I'm in fact using the rde::hash_map, as it is faster on inserting and fetching (self tested), though takes more RAM (not an issue now).
The thing is, that map stores a unique ID for the object (64 bits), plus the object pointer, something like:
rde::hash_map<UInt64, Object*>
My problem is:
My application (a server) must run in a loop (inside a thread) which must be called every ~50ms, as to keep things runing smooth. The loop code looks as follows:
void loop()
{
UInt32 prev = clock();
UInt32 prevSleep = 0;
while (1)
{
UInt32 diff = clock() - prev;
prev = clock();
maps.update() // Suppose map is a class, which stores the objects map
if (diff <= 50 + prevSleep)
{
prevSleep = 50 + prevSleep - diff;
sleep(prevSleep);
}
else
prevSleep = 0;
}
}
And now, to the point, the function map::update() which is the one causing the loop increasing to values of 4500ms.
Each time an update is called, the map object must check for new object being added to the store, if an object is added, that object must notify all the other objects of it being added, which I do by (pseudocode):
foreach obectsToBeAdded as joiner:
foreach objectsList as object:
joiner->notify(object);
object->notify(joiner);
Later on, an internal update of each object must be called, I do it by (pseudocode again):
foreach objectsList as object:
object->update();
And, if that was not enough, the above loop must be expanded to:
foreach objectsList as object:
object->update()
// Visit all the other objects
// Called once every 1 sec for the object, not on every call
foreach objectsList as other:
if other != object:
object->visit(other)
My attemp to optimize this
Merge the first loop (adding and notifying) with the update loop, as it follows:
foreach objectsList as object:
foreach objectsToBeAdded as joiner:
object->notify(joiner)
joiner->notify(object)
object->update()
// Called once every 1 sec for the object, not on every call
foreach objectsList as other:
if other != object
object->visit(other)
This works while the objects count is not big, as soon as it increases the loops start to take up to 4 seconds, which goes far beyond to the 50ms I'm looking for.
My question
Is there any other way of optimizing this even more? I've though about using octrees to keep track of the objects positions in the map, but then came to the conclusion that it would only worsen the problem.
I've also divided each map to 35 units (35 is the "view range", LOS) of an entity, so that a given rde::hash_map only contains units which are to be seen by each other, thus that need updates. Works as long as objects count is low...
What else could I do? Thank you!
Note
All those foreach are loops using iterators, like rde::hash_map<...>::iterator from objects.begin() to objects.end()
Other optimitzations, such as not updating if there's is no player (a real user, and not a NPC), freeing memory when no player is on a given map, and such, are already being taken into account.
The first optimization that comes to mind besides spatial segmentation so objects are only informed about changes near them (such as with a quadtree) is: Does EVERY object have to be informed about EVERY change? Why not tell each object, 'Every frame, I'll run your update method. In your update method you can look for everything you want to (for example, there might be a buffer of all changes that occurred this frame/in recent frames) and update yourself as you please'. This way you don't spend CPU cycles notifying objects about things they don't actually need to know or care about.
Also, have you run a CPU profiler on your program, and verified that the hot spots (where the most CPU time is being spent) are where you think they are?
See comments for further discussion:
|
|
\|/
V

How can a script retain its values through different script loading in Lua?

My current problem is that I have several enemies share the same A.I. script, and one other object that does something different. The function in the script is called AILogic. I want these enemies to move independently, but this is proving to be an issue. Here is what I've tried.
1) Calling dofile in the enemy's constructor, and then calling its script function in its Update function which happens in every game loop. The problem with this is that Lua just uses the script of the last enemy constructed, so all of the enemies are running the same script in the Update function. Thus, the object I described above that doesn't use the same script for it's A.I. is using the other enemies' script.
2) Calling dofile in the Update function, and then calling its script function immediately after. The problem with this is that dofile is called in every object's update function, so after the AILogic function runs and data for that script is updated, the whole thing just gets reset when dofile is called again for another enemy. My biggest question here is whether there is some way to retain the values in the script, even when I switch to running a different one.
I've read about function environments in Lua, but I'm not quite sure how to implement them correctly. Is this the right direction? Any advice is appreciated, thanks.
Edit: I've also considered creating a separate place to store that data rather than doing it in the Lua script.
Edit2: Added some sample code. (Just a test to get the functionality working).
-- Slime's Script
local count = 0;
function AILogic( Slime )
--Make the slime move in circles(err a square)
if count < 4 then
Slime:MoveDir( 0 );
elseif count < 8 then
Slime:MoveDir( 2 );
elseif count < 12 then
Slime:MoveDir( 1 );
elseif count < 16 then
Slime:MoveDir( 3 );
else
count = 0;
end
count = count + 1;
end
The lua interpreter runs each line as its own chunk which means that locals have line scope, so the example code can't be run as-is. It either needs to be run all at once (no line breaks), without locals, or run in a do ... end block.
As to the question in the OP. If you want to share the exact same function (that is the same function at runtime) then the function needs to take the data as arguments. If, however, you are ok with using the same code but different (runtime) functions than you can use closures to hold the local/individual data.
local function make_counter()
local count = 0
return function ()
local c = count
count = count + 1
return c
end
end
c1 = make_counter()
c2 = make_counter()
c3 = make_counter()
print(c1())
print(c1())
print(c1())
print(c1())
print(c2())
print(c3())
print(c2())
print(c3())
print(c2())
print(c3())
Alternatively, you could play with the environment of the function each time it is called, but that will only work correctly for some cases (depends on what the internals of the function are).
The canonical reference for this is link text. Explaining this briefly we'll work off the following code from the site:
a = 1
local newgt = {} -- create new environment
setmetatable(newgt, {__index = _G})
setfenv(1, newgt) -- set it
The first line sets up the (global) variable "a". You can view this as setting default values for your code. (Keep in mind that in Lua all variables are global unless you declare them with "local".)
The next line creates a table that will be your new environment. It is local to the function/chunk you're executing in so it won't be trashed by anything else that runs now or later.
The third line is the beginnings of the magic. To understand it you're going to have to understand metamethods In essence, however, you're using Lua's metamagic to ensure that any global names that aren't defined in your soon-to-be function environment get resolved in the context of your old global environment. Basically it means if you use a name that's not in your function environment, Lua will automagically hunt in the global environment you used to have to find the name. (In a word: inheritance.)
The fourth line is where you get what you're looking for. Setfenv(1,...) means that this changes the environment for your current function. (You could use 2 for the calling function, 3 for the calling function's caller, etc. on up the line.) The second parameter is the table you just set up, complete with inheritance of the old behaviour. Your function is now executing in a new global environment. It has all the names and values of the old environment handy (including functions and that global variable "a" you put in). If, however, you WRITE to a name it will not overwrite the global state. It will overwrite your local copy of it.
Consider the following subsequent code:
a = 10
b = 20
What you have done now is made your function environment table look like this:
{a = 10, b=20}
Your "global" environment, in short, contains two variables only: a (value 10) and b (value 20). When you access "a" later you'll get your local copy with 10 -- the old global value stored in your metatable is shadowed now and is still set to 1 -- and if you access "b" you'll get 20, despite the original global state likely not even having a variable "b" to access. And you'll still be able to access all the functions, etc. you've defined before this point as well.
Edited to add test code to debug OP's problem.
I put the following code into "junk.lua":
a = 1
local newgt = {}
setmetatable(newgt, {__index = _G})
setfenv(1, newgt)
print(a)
a = 10
print(a)
print(newgt)
The output of it is as follows:
$ lua junk.lua
1
10
table: 0x976d040
This is using Lua 5.1.4. What is the output you're seeing?