elements not getting added in list groovy script - groovy

The weird thing is happening while adding elements in list in groovy.
Scenario-
There are two List list1 and list2. List1 contains Object of X type and List2 is empty. List1 is getting populated from java file and while iterating List1 in groovy script, I am adding objects in List2.
But what happening is elements are not getting added. List2 remains empty.
If I debug the line and evaluate the expression/line it then it is getting added. But while normal debugging while executing this line, it suddenly jump to any random line.
No exception is coming.
Have created list as below:
List<X> dataToBeRemoved = new ArrayList<>()
Iterating the list as below:
for (X data in XList) {
if(something) {
dataToBeRemoved.add(data)
}
}
I am new to Groovy and If any one have ever faced this kind of issue. Please guide. Thanks.

You didn't ask, but type parameters don't get you much.
List elementsToRemove = []
And, in this case even better:
List elementsToRemove = allElements.findAll { ...some condition... }
After that, it's impossible to tell from your code. Questions such as "Why doesn't Groovy work?" are hard to answer.

You can define the an empty list by simply using
def mySmallList = []
and you may also use findAll to filter out the list
mySmallList = myBigList.findAll {//some condition }
Please check the link https://groovyconsole.appspot.com/script/5127180895911936

Related

Building a std::map and issue with using std::emplace

Code:
std::map<CString, S_DISCUSSION_HIST_ITEM> mapHistory;
// History list is in ascending date order
for (auto& sHistItem : m_listDiscussionItemHist)
{
if (m_bFullHistoryMode)
mapHistory.emplace(sHistItem.strName, sHistItem);
else if (sHistItem.eSchool == m_eActiveSchool)
mapHistory.emplace(sHistItem.strName, sHistItem);
}
// The map is sorted by Name (so reset by date later)
// The map has the latest assignment info for each Name now
Observation:
I now understand that std::emplace behaves like this:
The insertion only takes place if no other element in the container has a key equivalent to the one being emplaced (keys in a map container are unique).
Therefore my code is flawed. What I was hoping to acheive (in pseudo code) is:
For Each History Item
Is the name in the map?
No, so add to map with sHitItem
Yes, so replace the sHistItem with this one
End Loop
By the end of this loop iteration I want to have the most recent sHitItem, for each person. But as it is, it is only adding an entry into the map if the name does not exist.
What is the simplest way to get around this?
Use insert_or_assign method if the item is assignable. It will be assigned if it already exists. Or use [] operator followed by assignment, it will default-construct item if it does not exist.
For non-assignable types I'm afraid there's no convenient way.

How can I remove a key:value pair wherever the chosen key occurs in a deeply nested dictionary? [duplicate]

This question already has an answer here:
How can I replace a key:value pair by its value wherever the chosen key occurs in a deeply nested dictionary?
(1 answer)
Closed 1 year ago.
About
This question is about the most basic problem of deleting a key:value pair at a found key, iterating over a whole dictionary.
Other questions
Deleting a key:value pair should happen much more often than the special problem of replacing the key:value pair by its value at How can I replace a key:value pair by its value whereever the chosen key occurs in a deeply nested dictionary?. Saying that these two problems are different enough may not sound so plausible at first since the wording seems almost the same, but then, please check the code solutions and test it. There is a reason why it took some hour to find it out.
The 2011 question Modifying a Python dict while iterating over it (85k views) does not even seem to have found a working answer, though it is also outdated, admittedly.
Before:
I have a dictionary that is nested many times.
{
"key0": {
"key1a": {
"sub_key2a": "sub_value2a",
"sub_key2b": "sub_value2b"
},
"key1b": {
"key_XYZ": {
"sub_key2a": "sub_value2a",
"sub_key2b": "sub_value2b"
}
}
}
}
After:
The result should look like this, deleting all "sub_key2a" keys with their values:
{
"key0": {
"key1a": {
"sub_key2b": "sub_value2b"
},
"key1b": {
"key_XYZ": {
"sub_key2b": "sub_value2b"
}
}
}
}
Modifying a Python dict while iterating over it
When I looped through the items of the dictionary to delete, I got the error
RuntimeError: dictionary changed size during iteration
which needs somehow to be avoided.
How can I remove the "sub_key2a": SOME_VALUE key-value pair each time the key "sub_key2a" occurs somewhere in the dictionary?
Trick
The trick is to find out in advance whether a target_key is among the next children (= this_dict[key] = the values of the current dict iteration) before you reach the child level recursively. Only then you can still delete a key:value pair of the child level while iterating over a dictionary. Once you have reached the same level as the key to be deleted and then try to delete it from there, you get the error:
RuntimeError: dictionary changed size during iteration
Code
Thus, the code looks as follows:
import copy
def find_remove(this_dict, target_key, bln_overwrite_dict=False):
if not bln_overwrite_dict:
this_dict = copy.deepcopy(this_dict)
for key in this_dict:
# if the current value is a dict, dive into it
if isinstance(this_dict[key], dict):
if target_key in this_dict[key]:
this_dict[key].pop(target_key)
this_dict[key] = find_remove(this_dict[key], target_key)
return this_dict
dict_nested_new = find_remove(nested_dict, "sub_key2a")
Credits
This is almost a copy of the spin-off How can I replace a key:value pair by its value wherever the chosen key occurs in a deeply nested dictionary?. But it took me a while to change that answer so that it would delete a key:value by its key. That is why I am sharing this, please mind that 95% of the credits go to the link!
The main added value over the "spun-off answer" is that you search for the target_key in the values in advance of entering the next recursion level by checking if target_key in this_dict[key]:.
Side note: Formatting the output
If you want to print or save the dictionary nicely, see How do I write JSON data to a file?.
delete a["key_"]["key0a"]["sub_key2a"]

Data appended to multiple dict values instead of one

driver_data_form = {
'forc_day_off':[],
'pref_day_off':[],
'pref_shift':{"day"+str(i):None for i in range(1,15)},
'route_data':[]
}
So I am creating the dict driver_data (seen below) by using driver_data_form (seen above)
driver_data = {str(i):driver_data_form for i in range(1,12)}
and accordingly populating it :
loop_list = [str(i) for i in range(1,13)]
1 for specific_driver in loop_list:
2 for driver in forced_day_off_data:
3 for day in driver:
4 if driver[day]=='1' and day != "driverid":
5 driver_data[specific_driver]['forc_day_off'].append(day)
forced_day_off_data looks like:
But for some reason, after the above loop is executed once (lines 2-5), and by placing a break point in line 2, I am getting all 11 values of my driver_data[forc_day_off] dictionary populated, instead of only the first one. It appears that the values of the first key are copied to all the rest of the values:
I debugged this piece of code many times and this behavior makes no sence to me? What could be causing this and how can I fix it?
The problem with your code is that python is using references to dicts and lists. When you do this
driver_data = {str(i):driver_data_form for i in range(1,12)}
It basically sets the same dict reference for all your keys so when you change one value you actually update for all the other keys since it's the same dict
For your code to work you need to do this:
driver_data = {str(i):{
'forc_day_off':[],
'pref_day_off':[],
'pref_shift':{"day"+str(j):None for j in range(1,15)},
'route_data':[]
} for i in range(1,12)}
This way you create a new dict for each element and you will update only the specific dict.
See this this link to better understand the difference.

(Groovy) Add multiple values to an ArrayList

like the title says, I want to add multiple values to my arrayList in Groovy.
But it is not accepted.
Collection<String> actorCollection = new ArrayList<>();
actorCollection.add("first","second");
If there is only a single value, it works perfectly.
Thanks in advance!
Use addAll: actorCollection.addAll("first","second")
Note: Groovy's list literal will give you an array list. So could just write def actorCollection = [] or even ... = ["first", "second"] to fill the list with the values right from the beginning.

groovy only grabbing first element of loop

I've got a very straightforward code snippet. That for some reason is
only grabbing the first element of the loop when I try to output it in
my jsp. JcrUtils.getChildNodes returns a NodeIterator that I thought would loop through
each property. Here is the code:
def headerNode = JcrUtils.getChildNodes(LINKS).find{
it.hasProperty("headerTitle")
it.hasProperty("headerMeta")
}
selectHeaderTitle = headerNode.getProperty("headerTitle").getString()
selectHeaderMeta = headerNode.getProperty("headerMeta").getString()
JSP:
${header.selectHeaderTitle}
${header.selectHeaderMeta}
Any help is greatly appreciated!
You want a list of Properties? You'd need findAll, also you need to && your hasProperty calls:
def headerNode = JcrUtils.getChildNodes(LINKS).findAll {
it.hasProperty("headerTitle") && it.hasProperty("headerMeta")
}
Groovy find only returns the first match.
See http://groovy.codehaus.org/Iterator+Tricks

Resources