Second map value is always null, even if it prints out 1 - groovy

I have some code getting data and then selecting it in order. For this I use simple maps that I may later access with ease (I thought..).
I use the following code within a loop to insert maps to another map named "companies":
def x = [:]
x.put(it.category[i], it.amount[i])
companies.put(it.company, x)
And I can surely write the result out: [Microsoft:[Food:1], Apple:[Food:1]]
But then, when I am about to get the food value of each company it always is null. This is the code I use to get the values:
def val = companies.get(it.company).get(key.toString())
def val = companies[it.company][key] // doesn't make a difference
Val is always null. Can someone help and / or explain why I have this error. What am I doing wrong? I mean, I can clearly see the 1 when I print it out..

My guess is that it.category[i] and key are completely different types...
One thing you could try is:
x.put(it.category[i].toString(), it.amount[i])
and then
def val = companies[it.company][key.toString()] // doesn't make a difference

The solution was simple to make the category as a string:
x.put(it.category[i].toString(), it.amount[i])
And after that little fix it all works as expected.

Related

.get_dummies() works alone but doesnt save within function

I have a dataset and I want to make a function that does the .get_dummies() so I can use it in a pipeline for specific columns.
When I run dataset = pd.get_dummies(dataset, columns=['Embarked','Sex'], drop_first=True)
alone it works, as in, when I run df.head() I can still see the dummified columns but when I have a function like this,
def dummies(df):
df = pd.get_dummies(df, columns=['Embarked','Sex'], drop_first=True)
return df
Once I run dummies(dataset) it shows me the dummified columsn in that same cell but when I try to dataset.head() it isn't dummified anymore.
What am I doing wrong?
thanks.
You should assign the result of the function to df, call the function like:
dataset=dummies(dataset)
function inside them have their own independent namespace for variable defined there either in the signature or inside
for example
a = 0
def fun(a):
a=23
return a
fun(a)
print("a is",a) #a is 0
here you might think that a will have the value 23 at the end, but that is not the case because the a inside of fun is not the same a outside, when you call fun(a) what happens is that you pass into the function a reference to the real object that is somewhere in memory so the a inside will have the same reference and thus the same value.
With a=23 you're changing what this a points to, which in this example is 23.
And with fun(a) the function itself return a value, but without this being saved somewhere that result get lost.
To update the variable outside you need to reassigned to the result of the function
a = 0
def fun(a):
a=23
return a
a = fun(a)
print("a is",a) #a is 23
which in your case it would be dataset=dummies(dataset)
If you want that your function make changes in-place to the object it receive, you can't use =, you need to use something that the object itself provide to allow modifications in place, for example
this would not work
a = []
def fun2(a):
a=[23]
return a
fun2(a)
print("a is",a) #a is []
but this would
a = []
def fun2(a):
a.append(23)
return a
fun2(a)
print("a is",a) #a is [23]
because we are using a in-place modification method that the object provided, in this example that would be the append method form list
But such modification in place can result in unforeseen result, specially if the object being modify is shared between processes, so I rather recomend the previous approach

How to return a variable from a python function with a single parameter

I have the following function:
def test(crew):
crew1 = crew_data['CrewEquipType1']
crew2 = crew_data['CrewEquipType2']
crew3 = crew_data['CrewEquipType3']
return
test('crew1')
I would like to be able to use any one of the 3 variables as an argument and return the output accordingly to use as a reference later in my code. FYI, each of the variables above is a Pandas series from a DataFrame.
I can create functions without a parameter, but for reason I can't quite get the concept of how to use parameters effectively such as that above, instead I find myself writing individual functions rather then writing a single one and adding a parameter.
If someone could provide a solution to the above that would be greatly appreciated.
Assumption: You problem seems to be that you want to return the corresponding variable crew1, crew2 or crew3 based on your input to the function test.
Some test cases based on my understanding of your problem
test('crew1') should return crew_data['CrewEquipType1']
test('crew2') should return crew_data['CrewEquipType2']
test('crew3') should return crew_data['CrewEquipType3']
To accomplish this you can implement a function like this
def test(crew):
if crew=='crew1':
return crew_data['CrewEquipType1']
elif crew=='crew2':
return crew_data['CrewEquipType2']
elif crew=='crew3':
return crew_data['CrewEquipType3']
...
... # add as many cases you would like
...
else:
# You could handle incorrect value for `crew` parameter here
Hope this helps!
Drop a comment if not

getting "none" as result and don't uderstand why

I am learning how to program in python 3 and today i was praticing until i start to struggle with this.
I was trying to make a function to get to know the total square meters of wood that i'll use in one project, but i keep get the none result and i don't know why, even reading almost every post about it that i found here.
Anyway, here's the code:
from math import pi
def acirc(r):
pi*r**2
def madeiratotal(r1,r2,r3,r4,r5):
a = acirc(r1)
b = acirc(r2)
c = acirc(r3)
d = acirc(r4)
e = acirc(r5)
print (a+b+c+d+e)
madeiratotal(0.15,0.09,0.175,0.1,0.115)
I already try defining the "acirc" function inside the "madeiratotal" function, try to print all numbers separated and them suming then... I just don't know what else to do please help
You need to return value from acirc function otherwise return type is None
def acirc(r):
return pi*r**2

map built from string value extraction - cannot recover value

I'm currently trying to manipulate a map in groovy but I'm facing a problem that I can't work out.
I build a map in order to have an id as key and a name as value
I have to store it as a string, then recover it and rebuild the map.
My keys look like id:my:device, names look like
When I build my map, I end up having something like
mymap = [id:my:device: ...etc.] which does not cause any problem for recovery, mymap[id:my:device] gives my device name.
EDIT :
I build the map doing name_uid_map[measure.uid] =jSonResponse.value for every map element and, at the end of my testCase, I store it doing testRunner.testCase.setPropertyValue("name_uid_map", name_uid_map.toString()
After storage and recovery, as it is stored as a string, it becomes uneasy to decypher. I modify the string in order to have "id:my:device"='my device name', then I rebuild the map doing the following (otherwise it splits from the first ':')
mymap = map.split(",\\s*").collectEntries{
def keyAndVal = it.split("=")
[(keyAndVal[0]):keyAndVal[1]]
}
The problem is now my rebuilt map looks like
{"id:my:device"='my device name' ... }
If I do
mymap.each{
key, value ->
log.info key
log.info value
}
I obtain
key : "id:my:device"
value : my device name
which is correct. When I want to recover value from the key, I encounter my problem, ie:
mymap["id:my:device"] = null
If I try to get the type of the value I get :
my value = class org.codehaus.groovy.runtime.NullObject
I'm not easy at all with handling maps in groovy and I'm sure I've done something wrong, but I can't figure it out, could someone help me ?
Alex
Well,
Actually I found another way to fulfill my needs
In the testStep where I build my initial map I do the following:
import groovy.json.JsonBuilder
and I store my map in a custom property like this, to make sure it's a valid JSON
testRunner.testCase.setPropertyValue("name_uid_map", new JsonBuilder(name_uid_map).toString())
In the next testStep, I do the following (simple extraction of JSON):
def name_uid_map = context.expand( '${#TestCase#name_uid_map}' )
def jsonSlurper = new groovy.json.JsonSlurper()
map = jsonSlurper.parseText(name_uid_map)
and it works fine.

groovy returning different node count

I am trying to get the count of result nodes in soapUI using groovy and the below code gave me the correct count
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def holder = groovyUtils.getXmlHolder("StepName#ResponseAsXml")
def cnt = holder["count(//Results/ResultSet/Row)"]
but when i tried the below i got a count of 1. How are the two different?
def cnt = holder["count('//Results/ResultSet/Row')"]
Though I've never used SoapUI, in the second one, you are passing a String (wrapped in '...') to count.
The first passes a path which I guess gets evaluated into a list of nodes.
All the examples I can find do not wrap the path in a String, so my guess is the first example is the way to do it ;-)
EDIT
Refer Tips and Tricks for most of the SoapUI and Groovy related questions. And count in xpath.

Resources