Skip to content

Commit b240c7f

Browse files
committed
Added docstrings to several undocumented functions.
1 parent 3f5b66c commit b240c7f

File tree

4 files changed

+136
-0
lines changed

4 files changed

+136
-0
lines changed

pdf/create_index.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,13 @@
1313

1414

1515
def main():
16+
"""
17+
This function reads the file index.html and extracts all headings from it.
18+
It then creates a dictionary with the first letter of each heading as key,
19+
and for each key, a dictionary containing all headings starting with that letter as value.
20+
The second level of dictionaries contain the actual heading
21+
text as keys and their ID's (which are also stored in another list) as values.
22+
"""
1623
html = read_file('index.html')
1724
doc = BeautifulSoup(''.join(html), 'html.parser')
1825
hhh = defaultdict(lambda: defaultdict(list))
@@ -26,6 +33,14 @@ def main():
2633

2734

2835
def print_hhh(hhh):
36+
"""
37+
Prints a table of contents for the commands in the given dictionary.
38+
39+
The keys of `hhh` are letters and each letter is mapped to another dictionary
40+
that maps command names to lists of links. The first link in each list is used as the heading for that command name, so it should be unique among all
41+
commands (and ideally short). All other links should be unique among all lists but not necessarily short. The order of letters and commands within a
42+
letter will match their order in `hhh`.
43+
"""
2944
letters = hhh.keys()
3045
for letter in sorted(letters):
3146
hh = hhh[letter]

pdf/remove_links.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,18 @@
2525

2626

2727
def main():
28+
"""
29+
Replaces all occurrences of `from_` with `to_` in the file at the given path.
30+
31+
Args:
32+
from_ (str): The string to be replaced.
33+
to_ (str): The
34+
replacement string.
35+
36+
index_path (Path): Path object representing the file that is being modified by this function call. This parameter is not
37+
optional, and it has a default value of None because we are required to pass it as an argument but we have no use for it in our code since we don't
38+
need access to its attributes or methods while calling this function; therefore, there's no sensible default value for us to provide here.
39+
"""
2840
index_path = Path('..', 'index.html')
2941
lines = read_file(index_path)
3042
out = ''.join(lines)

web/convert_table.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,39 @@
11
#!/usr/bin/env python3
22

33
def convert_table(lines):
4+
"""
5+
Convert a table from ASCII art to Unicode box drawing characters or vice versa.
6+
7+
:param lines: A list of strings representing the lines of the table.
8+
The first line is assumed to be the top border, and all other lines are assumed to be inside it (i.e., not on any side). All borders must use ``+``
9+
for corners, ``-`` for horizontal bars, and ``|`` for vertical bars; no spaces are allowed between symbols in a single border symbol (except if there
10+
is one space between two vertical bar symbols when converting from ASCII art). If there is only one line in `lines`, then it will be used as both the
11+
top and bottom borders with no interior rows or columns; this can also happen if `lines` contains an empty string at some point. This function does
12+
not check that each row has exactly as many columns as there are horizontal bar symbols in either its own border or that of its neighbor above/below
13+
it (if applicable), but such checking could easily be added by modifying how column widths are calculated below.
14+
# :type lines: list(str)
15+
# :returns
16+
out: The converted table represented by a single string containing newline characters at appropriate places so that when printed
17+
"""
418
def from_ascii():
19+
"""
20+
Convert a list of lines from an ASCII table to a reStructuredText grid table.
21+
22+
:param lines: A list of strings representing the rows in the ASCII
23+
table.
24+
:returns: A string containing the equivalent reStructuredText grid table.
25+
26+
The first line is assumed to be a header row and will be used as
27+
such in the resulting grid table, with each column separated by ``|`` characters (ASCII 124). The second line is assumed to contain column widths and
28+
will be used as such in the resulting grid table, with each width separated by ``-`` characters (ASCII 45). All subsequent lines are treated as data
29+
rows which will have their contents centered within their columns, surrounded on either side by ``|`` characters (ASCII 124) and padded on either side
30+
by blank spaces so that all data rows have an equal number of cells. Data values are converted from plain text into bold typeface using double
31+
asterisks for emphasis before being inserted into cells; this allows you to use plain text formatting within your tables without them being overridden
32+
when converting back into ASCII tables later on.
33+
34+
For example, given these three lines...
35+
+-----+--------+-------+------------------+-------------+-----------
36+
"""
537
out = []
638
first, header, third, *body, last = lines
739
first = first.translate(str.maketrans({'-': '━', '+': '┯'}))
@@ -18,6 +50,13 @@ def from_ascii():
1850
out.append(f'┗{last[1:-1]}┛')
1951
return '\n'.join(out)
2052
def from_unicode():
53+
"""
54+
Convert a Unicode box-drawing character string to ASCII.
55+
56+
:param str lines: A string of Unicode box-drawing characters.
57+
:returns str out: The same
58+
text with all the Unicode box drawing characters replaced by ASCII ones.
59+
"""
2160
out = []
2261
for line in lines:
2362
line = line.translate(str.maketrans('┏┓┗┛┠┼┨┯┷━─┃│', '+++++++++--||'))

web/update_plots.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,23 @@
1212

1313

1414
def main():
15+
"""
16+
This function scrapes the data from the web and wrangles it into a pandas DataFrame.
17+
It then creates an interactive plotly line graph of covid cases
18+
in New York State.
19+
"""
1520
print('Updating covid deaths...')
1621
update_covid_deaths()
1722
print('Updating covid cases...')
1823
update_confirmed_cases()
1924

2025

2126
def update_covid_deaths():
27+
"""
28+
Update the plot of global COVID-19 deaths over time.
29+
30+
:param df: A pandas DataFrame with columns 'Continent', 'Date', and 'Total Deaths per Million'.
31+
"""
2232
covid = pd.read_csv('https://covid.ourworldindata.org/data/owid-covid-data.csv',
2333
usecols=['iso_code', 'date', 'total_deaths', 'population'])
2434
continents = pd.read_csv('https://gist.githubusercontent.com/stevewithington/20a69c0b6d2ff'
@@ -41,19 +51,45 @@ def update_covid_deaths():
4151

4252

4353
def update_confirmed_cases():
54+
"""
55+
Update the file covid_cases.js with a plot of total cases, gold price, bitcoin price and Dow Jones index.
56+
"""
4457
def main():
58+
"""
59+
This function scrapes the data from the web and wrangles it into a pandas DataFrame.
60+
It then creates an interactive plotly line graph of covid cases
61+
in New York State.
62+
"""
4563
df = wrangle_data(*scrape_data())
4664
f = get_figure(df)
4765
update_file('covid_cases.js', f)
4866
f.layout.paper_bgcolor = 'rgb(255, 255, 255)'
4967
write_to_png_file('covid_cases.png', f, width=960, height=315)
5068

5169
def scrape_data():
70+
"""
71+
This function scrapes data from the following sources:
72+
1. Our World in Data (Total Cases)
73+
2. Yahoo Finance (Bitcoin, Gold, Dow Jones)
74+
The
75+
function returns a list of pandas Series objects containing the scraped data.
76+
"""
5277
def scrape_covid():
78+
"""
79+
This function scrapes the total number of covid cases from a csv file on the internet.
80+
"""
5381
url = 'https://covid.ourworldindata.org/data/owid-covid-data.csv'
5482
df = pd.read_csv(url, usecols=['location', 'date', 'total_cases'])
5583
return df[df.location == 'World'].set_index('date').total_cases
5684
def scrape_yahoo(slug):
85+
"""
86+
Downloads historical stock price data from Yahoo Finance.
87+
88+
:param str slug: The ticker symbol of the desired security. Expected to be a valid argument
89+
for the `yfinance` function `Ticker()`.
90+
:returns pd.Series(float): A pandas Series with timestamps as indices and adjusted closing prices as values,
91+
sorted by timestamp in ascending order.
92+
"""
5793
url = f'https://query1.finance.yahoo.com/v7/finance/download/{slug}' + \
5894
'?period1=1579651200&period2=9999999999&interval=1d&events=history'
5995
df = pd.read_csv(url, usecols=['Date', 'Close'])
@@ -63,6 +99,14 @@ def scrape_yahoo(slug):
6399
return map(pd.Series.rename, out, ['Total Cases', 'Bitcoin', 'Gold', 'Dow Jones'])
64100

65101
def wrangle_data(covid, bitcoin, gold, dow):
102+
"""
103+
This function joins the Dow Jones, Gold and Bitcoin dataframes into a single one.
104+
It then sorts them by date and interpolates missing values. It
105+
discards rows before '2020-02-23'.
106+
Finally it calculates percentages relative to day 1 of each series (Dow Jones, Gold, Bitcoin)
107+
and adds a column
108+
with covid cases. The result is returned as a new dataframe sorted by date in descending order.
109+
"""
66110
df = pd.concat([dow, gold, bitcoin], axis=1) # Joins columns on dates.
67111
df = df.sort_index().interpolate() # Sorts by date and interpolates NaN-s.
68112
yesterday = str(datetime.date.today() - datetime.timedelta(1))
@@ -72,6 +116,11 @@ def wrangle_data(covid, bitcoin, gold, dow):
72116
return df.sort_values(df.index[-1], axis=1) # Sorts columns by last day's value.
73117

74118
def get_figure(df):
119+
"""
120+
This function returns a plotly figure that shows the total cases of COVID-19 in the US and its economic
121+
indicators. The data is taken from [The New
122+
York Times](#) and retrieved using [NYT API](#).
123+
"""
75124
figure = go.Figure()
76125
for col_name in reversed(df.columns):
77126
yaxis = 'y1' if col_name == 'Total Cases' else 'y2'
@@ -97,6 +146,27 @@ def get_figure(df):
97146
#
98147

99148
def update_file(filename, figure):
149+
"""
150+
Updates the file at `filename` with the plotly figure `figure`.
151+
152+
:param filename: The path to a JSON file containing a Plotly figure.
153+
:type filename:
154+
str, required.
155+
The extension of the file must be .json or .js (for legacy reasons).
156+
157+
Note that if you are using JupyterLab and want to open
158+
your updated
159+
HTML files in an external browser window then you should save your
160+
notebook as an HTML file instead of as a Jupyter notebook.
161+
For more
162+
information see this guide on [using Jupyter with Google Colab](http://jupyter-
163+
notebook.readthedocs.io/en/stable/examples/Notebook/Running%20Code.html#Running-code).
164+
165+
If you are not using JupyterLab then it is recommended
166+
that you use .html for all types of notebooks so that they can be opened in any web browser, including Chrome, Firefox and Edge on Windows and macOS
167+
without any extra configuration needed (see below for more details). This is because some browsers do not support JavaScript which is used by default
168+
by Plotly's exporting functions to generate
169+
"""
100170
lines = read_file(filename)
101171
f_json = figure.to_json(pretty=True).replace('\n', '\n ')
102172
out = lines[:6] + [f' {f_json}\n', ' )\n', '};\n']

0 commit comments

Comments
 (0)