Quality Centre, TestSetFactory [PYTHON] - python

I have a problem with dumping testsets list from HP QC. I'm using TestSetFactory object and simple SQL query and I receive > object (I'd love to receive dictionary filled base dump. What is wrong with this code? If you have a questions about implementation some function, write.
def create(self):
self._report_connector.connect()
self.qc_test_set_factory = self._report_connector._get_factory(self._path)
test_sets = self.qc_test_set_factory.NewList("SELECT * FROM CYCLE ")
if test_sets == None:
print " no results"
for test in test_sets:
pprint.pprint(test) #<---- it print me <COMOBject <unknow>>
print len(test_sets) #<---- it print me 1

Not certain about the accuracy of the rest of the code, but you do not pass a SQL query to the TestSetFactory.NewList method. If you want everything, pass an empty string.
test_sets = self.qc_test_set_factory.NewList("")

Related

Function to transfer values in dictionary Python

I am new to Python and trying to make a function for an assignment that will transfer money from a checking to a savings account,. We were given this initial code:
class portfolio:
def __init__(self):
self.checking = {}
self.saving = {}
self.credit = {}
self.stock = {}
And then the start of this code to make the function to transfer the money:
def invest_in_savings_account(self, account_id_savings, amount, account_id_checking):
I've tried numerous code, but none will pass the test cases. Can someone explain to me why this won't work?
def invest_in_savings_account(self, account_id_savings, amount, account_id_checking):
try:
self.checking[account_id_checking] -= amount
self.saving[account_id_savings] += amount
except:
return None
If the account id doesn't exist or if there are no funds in the checking account, the function is to do nothing.
Any suggestions would be greatly appreciated! I've worked on this all day and haven't been able to solve it.
This is the test case it must pass:
myportfolio.invest_in_savings_account('discover_saving_3785', 1000, 'discover_7732')
if (myportfolio.saving == {'chase_saving_4444': 0, 'discover_saving_3785':1000}) and (myportfolio.checking == {'chase_6688': 100, 'discover_7732':5500}):
print('Pass')
else:
print('Fail')
There are a few things going on here, most simple first, always start a class with a capital letter, it isn't necessary but it's good practice:
def class Portfolio:
After reading your comments it appears you need this to work without money in the accounts. You can write the code but you won't be able to test it, so really you need to make functions to create accounts and to add / remove money. If you haven't created any accounts your dictionaries will always come back empty. If you don't put money into them then the function will never do anything, I'm confused as to how you would go about moving something that doesn't exist.
Try something like this:
def create_checking_account(self,account_id):
self.checking[account_id] = None
def add_funds_checking(self,account_id,amount):
self.checking[account_id] += amount
def invest_in_savings(self, account_id_savings, amount, account_id_checking):
if self.checking[account_id_checking] >= amount:
self.checking[account_id_checking] -= amount
self.savings[account_id_savings] += amount
else:
print('error')

Python Update random field choice function from OrderedDict Class

I'm trying to do a script that choose a string and update a current field, but for some reason the code doesn't update the last value when calling my changerandom function in the Greeting class.
...[snip]...
class Greeting(Packet):
fields = OrderedDict([
("Morning", "Hi"),
("Afternoon", "Good Afternoon!"),
("Evening", "Good Evening!"),
])
def change(self):
self.fields["Morning"] = "Good morning!"
def changerandom(self, n = 1):
function=[
{self.fields["Morning"]: "Hello!"},
{self.fields["Morning"]: "Bonjorno!"},
{self.fields["Morning"]: "Hola!"},
]
result = {}
for i in range(n):
result.update(choice(function))
print "Updated string:",result
return result
text = Greeting()
print text
text.change()
print text
text.changerandom()
print text
My code return the following:
Hi
Good morning!
Updated string: {'Good morning!': 'Hola!'}
Good morning!
While it should have returned:
Hi
Good morning!
Hola!
I'm not sure what i'm missing here, I don't see why I cannot update the last field.
Any help would be greatly appreciated!
The problem is that you're returning a result, without assigning it anywhere.
You also use the value of fields, rather than the key. So, your code should be something like
def changerandom(self, n = 1):
function=[
{"Morning": "Hello!"},
{"Morning": "Bonjorno!"},
{"Morning": "Hola!"},
]
for i in range(n):
result = choice(function)
self.fields.update(result)
print "Updated string:",result
return result
Note that we're using self.fields.update, and we're no longer returning anything.
Generally, it's good practice for your functions and methods to return something, or change something, but never both.

python: changing from print to return does not process items right

I created a program that reads a couchDB to list followers and friends ids of a single twitter user. Friends are identified under the group “friend_edges” and followers under “follower_edges”.
I use the intersection operation between sets -set1.intersection(set.2)- in order to obtain the list of those who are both friends and followers.
When I use print to see the outputs, the results are correct. But when I change to return to process the results, it only processes friends, not followers.
Can somebody give me a clue of what I'm doing wrong and how to improve the code?.... thanks in advance.
from twitter_login import oauth_login
from twitter_DB import load_from_DB
from sets import Set
def friends_and_followers(doc):
if 'friend_edges' in doc.keys():
flist = []
for x in doc['friend_edges']:
flist.append(x)
#print "Number of friends: ", len(flist) <-- shows the right number of items
return flist
else:
return []
if 'follower_edges' in doc.keys():
followlist = []
for x in doc['follower_edges']:
followlist.append(x)
#print "Number of followers: ", len(followlist) <-- shows the right number of items
return followlist
else:
return []
flist = Set(flist)
followlist = Set(followlist)
return flist.intersection(followlist)
if __name__ == '__main__':
twitter_api = oauth_login()
DBname = 'users-aguy-+-only'
ff_results = load_from_DB(DBname)
print 'number loaded', len(ff_results)
for doc in ff_results:
together = friends_and_followers(doc)
print "Friends and followers of a guy: ", together
A return statement stops execution of that method and returns to the calling method, so by adding a return statement you are saying, "Stop here and go back to where you came from"
You need to store both the values you want returned in variables and return them at the same time at the end of your method:
return value1, value2
You will call this with something like this:
val1, val2 = get_value1_and_value2(input)
It might make more sense to just break that up into two separate methods that each return the correct value though.

How to save a function with python (3.2)

Just started learning python (3.2) and have a question. I have created a some code that creates some stats (as in health, magic etc etc) and the numbers are randomly generated. Here is the code...
def stats ():
print ()
print ('Some text.')
done = False
while not done :
charname = input(str('What is the name of the character? '))
hp = random.randint(5,20)
mp = random.randint(4,20)
stre = random.randint(3,20)
agi = random.randint(3,20)
spd = random.randint(3,20)
wis = random.randint(3,20)
intel = random.randint(3,20)
cha = random.randint(3,20)
print (charname)
print ('HP:',hp)
print ('Mana:',mp)
print ('Strength:',stre)
print ('Agility:',agi)
print ('Speed:',spd)
print ('Wisdom:',wis)
print ('Intelligence:',intel)
print ('Charisma:',cha)
print ()
done = input('All done? yes/no ')
if( done == 'yes' ):
done = True
elif(done == 'no'):
done = False
while done :
print ()
print ('Now that your stats are done, you can go on your adventure!')
done = False
Now this works fine, but how could I call on this function again in case I wanted to view the stats again with it keeping the same stats it randomly generated before?
Sorry if the question is bit off. Still all new to programming.
Thank you.
Since you're new to programming, here's some advice on a different way to store your data (without actually coding it for you).
First, define a Character class, with attributes for HP, mana, etc. I don't know if you know about classes yet, but here's an intro. There are various tricks you can do to get around having to explicitly write in the names for HP, mana, etc, but for learning's sake, it's probably better to do them all manually for now.
Then def a random_character() function that creates a Character object with random attributes, defined like how you're doing now, but instead of saving them in different variables that Python doesn't know have anything to do with one another, puts them in a single Character.
Add a __str__ method to the Character class, so that if char is a Character, print(char) prints out the attributes.
If you want to be able to keep track of characters, use pickle to store it in files.
If you have questions about any part of this, just ask. :)
Your function now uses local variables to record the stats you've generated. You'll need to bundle them together into either a dictionary or an object so that you can pass them around as a value.
For example:
def get_stats():
stats = {}
stats['charname'] = input(str('What is the name of the character? '))
stats['hp'] = random.randint(5,20)
stats['mp'] = random.randint(4,20)
stats['stre'] = random.randint(3,20)
stats['agi'] = random.randint(3,20)
stats['spd'] = random.randint(3,20)
stats['wis'] = random.randint(3,20)
stats['intel'] = random.randint(3,20)
stats['cha'] = random.randint(3,20)
return stats
def print_stats(stats):
print (stats['charname'])
print ('HP:',stats['hp'])
print ('Mana:',stats['mp'])
print ('Strength:',stats['stre'])
print ('Agility:',stats['agi'])
print ('Speed:',stats['spd'])
print ('Wisdom:',stats['wis'])
print ('Intelligence:',stats['intel'])
print ('Charisma:',stats['cha'])
print ()
you can use def keyword to declare functions . Def
def stat():
you can call the function like this in your desired location. stat()
If you want easy storage in an external file, you can use the pickle module, and a dictionary of the values you wish to store.
for example:
import pickle
stats={}
stats['hp'] = random.randint(5,20)
stats['mp'] = random.randint(4,20)
stats['stre'] = random.randint(3,20)
stats['agi'] = random.randint(3,20)
stats['spd'] = random.randint(3,20)
stats['wis'] = random.randint(3,20)
stats['intel'] = random.randint(3,20)
stats['cha'] = random.randint(3,20)
#save the stats into the file by using:
pickle.dump(stats,yourstatfile.pkl)
#then to load it again from any program just use:
stats=pickle.load(yourstatfile.pkl) #you assign it to a variable, so if i used the variable 'lol' i would use it as lol['hp'] not stats['hp'] like it was originally used when saving.
#then you can use it just like any other dictionary:
print "your hp: "+str(stats['hp'])

how to get entities which don't have certain attribute in datastore

I'm trying to make an appraisal system
This is my class
class Goal(db.Expando):
GID = db.IntegerProperty(required=True)
description = db.TextProperty(required=True)
time = db.FloatProperty(required=True)
weight = db.IntegerProperty(required=True)
Emp = db.UserProperty(auto_current_user=True)
Status = db.BooleanProperty(default=False)
Following things are given by employee,
class SubmitGoal(webapp.RequestHandler):
def post(self):
dtw = simplejson.loads(self.request.body)
try:
maxid = Goal.all().order("-GID").get().GID + 1
except:
maxid = 1
try:
g = Goal(GID=maxid, description=dtw[0], time=float(dtw[1]), weight=int(dtw[2]))
g.put()
self.response.out.write(simplejson.dumps("Submitted"))
except:
self.response.out.write(simplejson.dumps("Error"))
Now, here Manager checks the goals and approve it or not.. if approved then status will be stored as true in datastore else false
idsta = simplejson.loads(self.request.body)
try:
g = db.Query(Goal).filter("GID =", int(idsta[0])).get()
if g:
if idsta[1]:
g.Status=True
try:
del g.Comments
except:
None
else:
g.Status=False
g.Comments=idsta[2]
db.put(g)
self.response.out.write(simplejson.dumps("Submitted"))
except:
self.response.out.write(simplejson.dumps("Error"))
Now, this is where im stuck..."filter('status=',True)".. this is returning all the entities which has status true.. means which are approved.. i want those entities which are approved AND which have not been assessed by employee yet..
def get(self):
t = []
for g in Goal.all().filter("Status = ",True):
t.append([g.GID, g.description, g.time, g.weight, g.Emp])
self.response.out.write(simplejson.dumps(t))
def post(self):
idasm = simplejson.loads(self.request.body)
try:
g = db.Query(Goal).filter("GID =", int(idasm[0])).get()
if g:
g.AsmEmp=idasm[1]
db.put(g)
self.response.out.write(simplejson.dumps("Submitted"))
except:
self.response.out.write(simplejson.dumps("Error"))
How am I supposed to do this? as I know that if I add another filter like "filter('AsmEmp =', not None)" this will only return those entities which have the AsmEmp attribute what I need is vice versa.
You explicitly can't do this. As the documentation states:
It is not possible to query for entities that are missing a given property.
Instead, create a property for is_assessed which defaults to False, and query on that.
could you not simply add another field for when employee_assessed = db.user...
and only populate this at the time when it is assessed?
The records do not lack the attribute in the datastore, it's simply set to None. You can query for those records with Goal.all().filter('status =', True).filter('AsmEmp =', None).
A few incidental suggestions about your code:
'Status' is a rather unintuitive name for a boolean.
It's generally good Python style to begin properties and attributes with a lower-case letter.
You shouldn't iterate over a query directly. This fetches results in batches, and is much less efficient than doing an explicit fetch. Instead, fetch the number of results you need with .fetch(n).
A try/except with no exception class specified and no action taken when an exception occurs is a very bad idea, and can mask a wide variety of issues.
Edit: I didn't notice that you were using an Expando - in which case #Daniel's answer is correct. There doesn't seem to be any good reason to use Expando here, though. Adding the property to the model (and updating existing entities) would be the easiest solution here.

Categories