I need to revise a python code (given by a programmer) which I would like to use for a genealogy project of mine. I am very new to python and start being able to read code. Yet, I do not know how to fix the following thing.
I get the following error message when executing the code:
self['gebort'] += ", Taufe: %s" % place.get_title()
KeyError: 'gebort'
The issue is that for one of the persons in my database only the date of baptism (here: Taufe) is known but not the date of birth. This is were the code fails.
This is the relevant snippet of the code basis:
birth_ref = person.get_birth_ref()
if birth_ref:
birth = database.get_event_from_handle(birth_ref.ref)
self['gjahr'] = birth.get_date_object().get_year()
if self['gjahr'] >= 1990:
self['mindj'] = True
self['gebdat'] = dd.display(birth.get_date_object())
self['plaingebdat'] = self['gebdat']
place_handle = birth.get_place_handle()
self['geborthandle'] = place_handle
place = database.get_place_from_handle(place_handle)
if place:
self['gebort'] = place.get_title()
self['plaingebort'] = self['gebort']
for eventref in person.get_event_ref_list():
event = database.get_event_from_handle(eventref.ref)
if event.get_type() in (gramps.gen.lib.EventType.CHRISTEN, gramps.gen.lib.EventType.BAPTISM):
self['gebdat'] += ", Taufe: %s" % dd.display(event.get_date_object())
place_handle = event.get_place_handle()
place = database.get_place_from_handle(place_handle)
if place:
self['gebort'] += ", Taufe: %s" % place.get_title()
Now, I do not know to add an exception handling when there is no birth date/place found so that the code would not give out any values of birth. Would somebody be able to point me to the right direction?
Instead of:
dict_name['gebort'] += ", Taufe: %s" % place.get_title()
you could write
dict_name['gebort'] = dict_name.get('gebort', '') + ", Taufe: %s" % place.get_title()
As already written, naming something self is not clever, or is the code above from a class derived from dict? Using .get you can define what is returned in case if there is no key of that name, in the exampe an empty string.
Related
Currently writing a program using an API from MarketStack.com. This is for school, so I am still learning.
I am writing a stock prediction program using Python on PyCharm and I have written the connection between the program and the API without issues. So, I can certainly get the High, Name, Symbols, etc. What I am trying to do now is call a range of dates. The API says I can call up to 30 years of historical data, so I want to call all 30 years for a date that is entered by the user. Then the program will average the high on that date in order to give a trend prediction.
So, the problem I am having is calling more than one date. As I said, I want to call all 30 dates, and then I will do the math, etc.
Can someone help me call a range of dates? I tried installing Pandas and that wasn't being accepted by PyCharm for some reason.. Any help is greatly appreciated.
import tkinter as tk
import requests
# callouts for window size
HEIGHT = 650
WIDTH = 600
# function for response
def format_response(selected_stock):
try:
name1 = selected_stock['data']['name']
symbol1 = selected_stock['data']['symbol']
high1 = selected_stock['data']['eod'][1]['high']
final_str = 'Name: %s \nSymbol: %s \nEnd of Day ($ USD): %s' % (name1, symbol1, high1)
except:
final_str = 'There was a problem retrieving that information'
return final_str
# function linking to API
def stock_data(entry):
params = {'access_key': 'xxx'}
response = requests.get('http://api.marketstack.com/v1/tickers/' + entry + '/' + 'eod', params=params)
selected_stock = response.json()
label2['text'] = format_response(selected_stock)
# function for response
def format_response2(stock_hist_data):
try:
name = stock_hist_data['data']['name']
symbol = stock_hist_data['data']['symbol']
high = stock_hist_data['data']['eod'][1]['high']
name3 = stock_hist_data['data']['name']
symbol3 = stock_hist_data['data']['symbol']
high3 = stock_hist_data['data']['eod'][1]['high']
final_str2 = 'Name: %s \nSymbol: %s \nEnd of Day ($ USD): %s' % (name, symbol, high)
final_str3 = '\nName: %s \nSymbol: %s \nEnd of Day ($ USD): %s' % (name3, symbol3, high3)
except:
final_str2 = 'There was a problem retrieving that information'
final_str3 = 'There was a problem retrieving that information'
return final_str2 + final_str3
# function for response in lower window
def stock_hist_data(entry2):
params2 = {'access_key': 'xxx'}
response2 = requests.get('http://api.marketstack.com/v1/tickers/' + entry2 + '/' + 'eod', params=params2)
hist_data = response2.json()
label4['text'] = format_response2(hist_data)
I have a script that calls a list of linux guests I am trying to tidy up. Here is the code:
#!/usr/bin/python
guests = ['guest1','guest2','guest3','guest*']
def serverCheck(guestList)
for g in guestList:
server = AdminControl.completeObjectName('cell=tstenvironment,node=guest1,name=uatenvironment,type=Server,*')
try:
status = AdminControl.getAttribute(server, 'state')
print g + status
except:
print "Error %s is down." % g
serverCheck(guests)
The problem lies in this line:
server = AdminControl.completeObjectName('cell=Afcutst,node=%s,name=afcuuat1,type=Server,*') % g
How do I use my list to populate the node variable while still being able to pass the info within the parentheses to the AdminControl function?
The argument string itself is the argument to the % operator, not the return value of the function call.
server = AdminControl.completeObjectName(
'cell=Afcutst,node=%s,name=afcuuat1,type=Server,*' % (g,)
)
Peeking into the crystal ball, Python 3.6 will allow you to write
server = AdminControl.completeObjectName(
f'cell=Afcutst,node={g},name=afcuuat1,type=Server,*'
)
embedding the variable directly into a special format string literal.
can you try like this
AdminControl.completeObjectName('cell=tstenvironment,node=%s,name=uatenvironment,type=Server,*'%g)
For more readability I would suggest this and also using the same way to format strings from variables (here I chose str.format)
guests = ['guest1','guest2','guest3','guest*']
def serverCheck(guestList)
name_tpl = 'cell=tstenvironment,node={},name=uatenvironment,type=Server,*'
for g in guestList:
obj_name = name_tpl.format(g)
server = AdminControl.completeObjectName(obj_name)
try:
status = AdminControl.getAttribute(server, 'state')
print '{}: {}'.format(g, status)
except:
print 'Error {} is down'.format(g)
serverCheck(guests)
I am trying to modify the statecounts.py from pyral examples to pull all the defined/accepted/in progress/completed stories point for each release. I am keep getting query exception error. Is there anything that I have missed?
state = 'ScheduleState'
state_values = rally.getAllowedValues('HierarchicalRequirement', state)
output = []
for rel in sorted(release_names):
for state_value in sorted(state_values):
response = rally.get(artifact_type, fetch="FormattedID", query='(Release.Name= %s ) AND %s = %s' % (rel, state, state_value),
projectScopeUp=False, projectScopeDown=False)
output.append("%20s : %16s : %5d" % (rel, state, state_value, response.resultCount))
Thanks!!!
If you are ANDing multiple terms it's easiest to create a list of terms like so:
query=['Release.Name = %s' % (rel), '%s = %s' % (state, state_value)]
Also, whitespace matters. You were missing a space before the first =.
Whis scripts read from a source with lines consisting of artist names followed by a parenthesis with information about whether the artists cancelled and which country they come from.
A normal sentence may look like:
Odd Nordstoga (NO) (Cancelled), 20-08-2012, BlÄ
As I import the data I decode them into UTF-8 and this works fine. Uncommenting the second comment in the else block of the remove_extra() method shows that all variables are of type Unicode.
However, when a value is returned and put into another variable and the value of this is tested, the majority of the variables seems to be of NoneType.
Why does this happen? And how can it be corrected? Seems to be an error happening between the method return and assignment of the new variable.
# -*- charset: utf-8 -*-
import re
f1 = open("oya_artister_2011.csv")
artister = []
navnliste = []
PATTERN = re.compile(r"(.*)(\(.*\))")
TEST_PAT = re.compile(r"\(.*\)")
def remove_extra(tekst):
if re.search(PATTERN, tekst) > 1:
after = re.findall(PATTERN, tekst)[0][0]
#print "tekst is: %s " % tekst
#print "and of type: %s" % type(tekst)
remove_extra(after)
else:
#print "will return: ", tekst
#print "of type: %s" % type(tekst)
return tekst
for line in f1:
navn, _rest = line.split(",",1)
navn = navn.decode("utf-8")
artister.append(navn)
for artist in artister:
ny_artist = remove_extra(artist)
#print "%s" % ny_artist
print "of type: %s" % type(ny_artist)
Try
return remove_extra(after)
instead of just
remove_extra(after)
I have calendar that is working fine.
Here is the function that display the full date:
def selectDate(self,date):
self.fullDate = str(date.day()) + " / " + str(date.month()) + " / " + str(date.year())
print "full date: %s" % self.fullDate
And here the code with the calendar:
def TabCalendar(self):
self.calendar = QtGui.QCalendarWidget(self.tab)
self.calendar.setGeometry(QtCore.QRect(self.x1, self.y1, self.x2, self.y2))
QtCore.QObject.connect(self.calendar, QtCore.SIGNAL("selectionChanged()"), self.selectDate)
QtCore.QObject.connect(self.calendar, QtCore.SIGNAL("clicked(QDate)"), self.selectDate)
To have direct access to selected day, I am calling the function selectDate based on connect event, and then using the 'date' to obtain the precise date.day and so on -- which is working fine.
The only awkward thing that is annoying me is that it gives the following warning..
TypeError: turbSchedule_selectDate() takes exactly 2 arguments (1 given)
Any suggestion to stop this TypeError warning?
All comments and suggestions are highly appreciated.
I guess that the slot called by the selectdate signal shouldn't have any argument. You can access the selectedDate by the corresponding calendar method.
See the c++ docs: http://doc.trolltech.com/4.3/widgets-calendarwidget.html
So your code should be something like:
def selectDate(self):
date = self.calendar.selectedDate()
self.fullDate = str(date.day()) + " / " + str(date.month()) + " / " + str(date.year())
print "full date: %s" % self.fullDate