-
Notifications
You must be signed in to change notification settings - Fork 0
/
process_utils.py
46 lines (40 loc) · 1.27 KB
/
process_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
import re
# Determines if a file has the requisite file extension(s).
def allowed_file(filename):
ALLOWED_EXTENSIONS = set(['txt', 'csv'])
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# Splits a string into chunks of size n.
def split_into_chunks(str, size):
return re.findall('.' * size, str)
# Converts a string into an integer if possible (is not None or empty), otherwise returns 0.
def int_if_possible(str):
# Strip of whitespace.
str = str.strip()
if str is None or len(str) == 0:
return 0
else:
try:
return int(str)
except ValueError:
return 0
# Safely escapes a string into encoded HTML characters, converting commas, <, >, etc. to safe characters.
def html_encode(str):
str = re.sub('&', '&', str)
str = re.sub(',', ',', str)
str = re.sub('<', '<', str)
str = re.sub('>', '>', str)
str = re.sub('\'', ''', str)
str = re.sub('"', '"', str)
return str
# Returns the mean for an array of numbers.
def mean(numbers):
return float(sum(numbers)) / max(len(numbers), 1)
# Returns the median for an array of numbers.
def median(numbers):
n = len(numbers)
if n < 1:
return None
if n % 2 == 1:
return sorted(numbers)[n // 2]
else:
return sum(sorted(numbers)[(n // 2 - 1):(n // 2 + 1)]) / 2.0