Skip to content

Instantly share code, notes, and snippets.

@robjwells
Created July 15, 2015 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robjwells/9bcdb0cac8d234d1ab7e to your computer and use it in GitHub Desktop.
Save robjwells/9bcdb0cac8d234d1ab7e to your computer and use it in GitHub Desktop.
Pythonista UI script that converts a dollar amount for a given year to current dollars
from __future__ import division
from datetime import date
from xml.etree import ElementTree
import requests
import ui
def calculate_amount(sender):
"""Convert given dollar amount for given year to current dollars"""
amount = view['amount'].text
year = view['year'].text
if not (amount and year):
return
api_key = 'YOUR API KEY HERE'
api_url = 'http://api.wolframalpha.com/v2/query'
query_template = '${amount} ({past_year} US dollars) in {current_year}'
query = query_template.format(amount=amount,
past_year=year,
current_year=date.today().year)
parameters = {'appid': api_key,
'input': query,
'format': 'plaintext',
'podtitle': 'Result'}
response = requests.get(api_url, params=parameters)
xml_soup = ElementTree.fromstring(response.content)
new_amount = xml_soup.find('pod/subpod/plaintext').text.splitlines()[0]
view['result'].text = new_amount
def setup_view():
view = ui.View()
view.name = 'Historical Dollars'
view.background_color = 'white'
view.width, view.height = ui.get_screen_size()
amount_field = ui.TextField()
amount_field.name = 'amount'
amount_field.keyboard_type = ui.KEYBOARD_DECIMAL_PAD
amount_field.placeholder = 'Dollar amount'
amount_field.width *= 2
amount_field.height /= 2
year_field = ui.TextField()
year_field.name = 'year'
year_field.keyboard_type = ui.KEYBOARD_NUMBER_PAD
year_field.placeholder = 'Year'
year_field.width *= 2
year_field.height /= 2
button = ui.Button(title='Calculate')
button.action = calculate_amount
result_label = ui.Label()
result_label.name = 'result'
result_label.width = view.width
result_label.alignment = ui.ALIGN_CENTER
horizontal_centre = view.width * 0.5
field_spacing = amount_field.height * 1.5
amount_field.center = (horizontal_centre, amount_field.height)
year_field.center = (horizontal_centre,
amount_field.center[1] + field_spacing)
button.center = (horizontal_centre,
year_field.center[1] + field_spacing * 0.75)
result_label.center = (horizontal_centre,
button.centre[1] + field_spacing * 0.75)
view.add_subview(amount_field)
view.add_subview(year_field)
view.add_subview(button)
view.add_subview(result_label)
return view
view = setup_view()
view.present('sheet')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment