-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
246 lines (203 loc) · 7.35 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
from datetime import datetime
BORDER_LEN = 80
SELECT = "Enter your selection: "
TODAY = datetime.today()
# Util methods
def print_border(length=BORDER_LEN, thick=False, sign='+'):
"""Prints border with different length"""
if thick:
print(sign + '=' * length + sign)
else:
print(sign + '-' * length + sign)
def print_newline(length=BORDER_LEN, no_border=True):
"""Prints a blank space with borders"""
print_string(" ", no_border=no_border, length=length)
def format_string(string, no_border=False, length=BORDER_LEN):
"""Format string for input"""
if no_border:
return " " + string
else:
str1 = "| " + string
return str1 + " " * (length - len(str1) + 1) + "|"
def print_string(string, no_border=False, length=BORDER_LEN):
"""Prints a string with border lines"""
print(format_string(string, no_border, length))
def split_title(title, string):
"""Prints a title and another string justified to the right"""
space_length = BORDER_LEN - len(string) - len(title) - 2
print_string(title + ' ' * (space_length) + string)
def convert_date(date_obj):
"""Convert a datetime.datetime object from a query into a string
:param data_obj: datetime.datetime object
"""
return datetime.strftime(date_obj, "%b %-d %Y")
def convert_keywords(keywords, lower=True):
"""Takes in string input from user, replaces commas, and converts to list
:param keywords: list of tokenized strings
"""
keywords = keywords.replace(',','')
keywords = keywords.split()
if lower:
return [word.lower() for word in keywords]
else:
return [word for word in keywords]
def convert_timezone(tz):
"""Converts an integer to a timezone UTC string"""
return "%03d:00" % (tz)
def is_hashtag(term):
"""Return True if term is a hashtag
:param term: a keyword string
"""
return term[0] == '#'
def remove_hashtags(keywords):
"""Returns a list with hashtags removed from keywords
:param keywords: list of tokenized strings
"""
new_list = []
for word in keywords:
if is_hashtag(word):
word = word.replace('#','')
new_list.append(word)
return new_list
def valid_password(password):
"""Check that password only has alpha-numeric characters"""
for ch in password:
if not ch.isalnum():
return False
return True
def display_selections(selections, title_menu=None, length=BORDER_LEN, thick=True, no_border=False):
"""Helper method for easily displaying numbered lists
:param selections: A list containing each menu item
:param title_menu (optional): string title
"""
if title_menu:
if not no_border:
print_border(length, thick=True)
print_string(title_menu.upper(), length=length)
if not no_border:
print_border(length, thick=True, sign='|')
for i, choice in enumerate(selections, 1):
print_string("%d. %s" % (i, choice), length=length)
print_border(length, False)
def check_quit(user_input):
"""Checks if a user entered a quit message
:param: user_input: input from the user
"""
try:
return user_input.lower() in ['quit', 'q', 'exit']
except AttributeError:
return False
def exit_input(choice, menu_func):
"""Determines what to return when a user quits an input prompt
:param menu_func: the function to return to
:param choice: the user input
"""
if menu_func is None:
return choice
else:
return menu_func()
def press_enter(session, prompt="Press Enter to continue."):
"""Requires user to press enter key before continuing
:param: string message
"""
try:
input(prompt)
except KeyboardInterrupt:
session.exit()
def validate_str(prompt, session, menu_func=None, length=None, null=True):
"""Used for when user needs to input words
Commonly used for validating insert values
If you are passing a function name, make sure to not put () so it won't be called
:param prompt: string message
:param session: Session object
:param menu_func: if user enters quit, return to this function
:param length (optional): restricts the number of characters
:param null (optional): if False, doesn't accept empty string
"""
valid = False
usr_input = None
while not valid:
try:
usr_input = input(prompt)
except KeyboardInterrupt:
session.exit()
if check_quit(usr_input):
return exit_input(usr_input, menu_func)
elif not null and len(usr_input) == 0:
valid = False
elif length and len(usr_input) > length:
print("Input must be %d characters or less." % (length))
valid = False
else:
valid = True
return usr_input
def in_range(num, rnge):
"""Checks if a number is in a certain range
:param rnge: a tuple containing numbers
"""
if num >= rnge[0] and num <= rnge[1]:
return True
else:
return False
def validate_num(prompt, session, menu_func=None, size=None, num_type='int', rnge=None):
"""Used for when user needs to input a single number
Used mainly for menu selections
If you are passing a function name, make sure to not put () so it won't be called
:param prompt: string message
:param menu_func: if user enters quit, return to this function
:param size (optional): specifies range of numbers based on available selections
:param num_type (optional): validate either integer or float (default: integer)
:param session: Session object, for when user exits program
"""
assert(num_type=='int' or num_type=='float'), "type must be either int or float"
if rnge is not None:
assert(isinstance(rnge, tuple)), "rnge must be a tuple"
valid = False
choice = None
while not valid:
try:
choice = input(prompt)
if check_quit(choice):
return exit_input(choice, menu_func)
if num_type == 'int':
choice = int(choice)
else:
choice = float(choice)
if size and choice not in range(1, size+1):
raise ValueError
except ValueError:
if size:
print("Selection must be a number from 1 to %d." % (size))
else:
print("Please enter a number.")
valid = False
except KeyboardInterrupt:
session.exit()
else:
if rnge and not in_range(choice, rnge):
print("Number must be from %d to %d." % (rnge[0], rnge[1]))
valid = False
else:
valid = True
if num_type == 'int':
return int(choice)
else:
return float(choice)
def validate_yn(prompt, session):
"""Used for when prompting the user to enter either y/yes or n/no
:param prompt: string message
:param session: Session object, for when user exits program
"""
valid = False
choice = None
while not valid:
try:
choice = input(prompt)
except KeyboardInterrupt:
session.exit()
if choice.lower() not in ['y', 'n', 'yes', 'no']:
print("Enter either y/yes or n/no.")
valid = False
else:
valid = True
return choice.lower()