-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutilities.py
307 lines (215 loc) · 7.04 KB
/
utilities.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
"""
Provides utility/helper functions for use in other files.
"""
from __future__ import print_function
import re
import sys
import os
#remap input function if necessary
if int(sys.version[0]) >= 3:
raw_input = input
def debug(function):
"""
Decorator that starts pdb before calling the function.
"""
def inner(*args, **kwargs):
import pdb
pdb.set_trace()
return function(*args, **kwargs)
return inner
def get_input(prompt, valid=None, list=False, wait=True, preserve_case=False):
"""
Requests input from stdin until a valid response is given.
Prompts the user and keeps doing so (with appropriate error
message) until a valid response is given (i.e. one that is
specified in valid). If valid is None, any response except
whitespace or an empty string will be accepted. A space
will be added after the prompt if one is not present. If
`list` is specified as True, validity of input will be
determined character by character, otherwise, it will be
determined by word. If `wait` is True, will wait for the
user to press return. Otherwise, will accept first
typed character as input (using getch).
For example:::
get_input("enter your name:")
enter your name: monty
(returns monty)
.
.
.
colors = [
"green",
"blue",
"brown",
"grey"
"hazel"
]
get_input("enter your eye color:", colors)
enter your eye color: red
That is not a valid response. Please try again.
enter your eye color: green
(returns green)
"""
input_function = raw_input
#add quit option and redefine raw_input if we're not waiting
if not wait:
valid.add("q")
#returns the result of using getch with a prompt
def _getch_input(prompt_str):
print(prompt_str, end="")
to_return = _getch()
print("")
return to_return
input_function = _getch_input
#add a space after the prompt for readability
if not prompt.endswith(" "):
prompt = prompt + " "
response = input_function(prompt)
#add spaces and commas to the valid characters for a list
if list:
valid.add(",")
valid.add(" ")
#keep asking for input until a valid response is given
while (valid and
(any(char not in valid for char in response.lower()) or not list)
and (response.lower() not in valid or list)
or response.strip() == ""):
print("That is not a valid response. Please try again.")
response = input_function(prompt)
to_return = response.lower()
#give response as typed if preserve case specified
if preserve_case:
to_return = response
return to_return
def readin(filename):
"""
Returns the content of filename as a list of lines.
"""
return open(filename, "r").read()
def writeout(filename, content, append=False):
"""
Writes content to file filename.
"""
mode = "w"
#append to the file instead of overwriting
if append:
mode = "a"
#write content
with open(filename, mode) as out:
out.write(content)
def get_line_lengths(content):
"""
Returns a list of the total number of bytes before the end of each line in content.
"""
lengths = [0]
total = 0
#go through every line
for i, line in enumerate(content.split("\n")):
length = len(line)
total += length + 1 #account for missing newlines
lengths.append(total)
return lengths
def unpack_list(first, second, *rest):
"""
Simulates Python 3's extended iterable unpacking.
Usage:
my_list = [1,2,3,4]
unpack_list(*my_list) #returns (1, 2, (3, 4))
"""
return first, second, rest
def get_last_line(fname):
"""
Returns the last line in file `fname`.
"""
all_lines = ""
last_line = ""
#file is empty, return empty string
if os.stat(fname).st_size == 0:
return ""
#get last line
with open(fname, "r+") as file:
all_lines = file.readlines()
last_line = all_lines[-1]
#if the last line is a number, delete it
try:
int(last_line)
#write back all the lines except the last one
with open(fname, "w+") as file:
for line in all_lines[:-1]:
file.write(line + "\n")
except ValueError:
pass
return last_line
def remove_inner_whitespace(line):
"""
Removes any repeated spaces from inside `line` (after the first word character) and returns the new string.
"""
stripped = line.lstrip()
leading_space = len(line) - len(stripped)
stripped = re.sub(r' {2,}', ' ', stripped)
return ' ' * leading_space + stripped
def find_line(byte, line_lengths):
"""
Determines which line the character `byte` bytes from the start of the file occurs on using a binary search.
"""
return _find_line_helper(byte, line_lengths, 0, len(line_lengths) - 1)
#uses recursive binary-search-esque algorithm to find what line the given byte is on
def _find_line_helper(byte, line_lengths, start, end):
mid = (start + end) // 2
if line_lengths[mid] == byte:
return mid+1
next_start = start
next_end = end
#target byte is less than mid
if byte < line_lengths[mid]:
left = mid - 1
#target byte between left and mid
if line_lengths[left] < byte:
return mid
next_end = left
#target byte is between mid and right
if line_lengths[mid] <= byte:
right = mid + 1
if line_lengths[right] == byte:
return right + 1
#if we're out of bounds, it's on the last possible line
if right >= end:
return end
#target byte between mid and right
if byte < line_lengths[right]:
return right
next_start = right
return _find_line_helper(byte, line_lengths, next_start, next_end)
class _Getch:
"""
Gets a single character from standard input. Does not echo to the screen.
From http://code.activestate.com/recipes/134892/
By Danny Yoo
"""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix:
def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
print(ch, end="")
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
_getch = _Getch()