-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathutils.py
More file actions
171 lines (130 loc) · 4.6 KB
/
utils.py
File metadata and controls
171 lines (130 loc) · 4.6 KB
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
from datetime import timedelta, datetime, date
from operator import attrgetter, methodcaller, itemgetter
import re
from collections import namedtuple
def to_minutes(durstr, duration_map):
value = durstr[:-1]
unit = durstr[-1]
return int(value) * duration_map[unit]
def listdiff(a, b):
b = set(b)
return [aa for aa in a if aa not in b]
def sparkline(values, smallest=-1, largest=-1):
"""
Treats null values are quarter breaks
"""
if len(values) == 0:
return ''
original_values = values
ticks = ['▁', '▂', '▃', '▄', '▅', '▆', '▇']
values = [float(val) for val in values if val is not None]
smallest = min(values) if smallest == -1 else smallest
largest = max(values) if largest == -1 else largest
rng = largest - smallest
scale = len(ticks) - 1
if rng == 0:
rng = largest - 0
if rng != 0:
return ''.join([ ticks[min(scale, round(((val - smallest) / rng) * scale))] if val is not None else '│'for val in original_values ])
else:
return ''.join([ticks[0] for val in original_values])
def truncate_middle(s, n):
if len(s) <= n:
# string is already short-enough
return s
# half of the size, minus the 3 .'s
n_2 = int(int(n) / 2 - 3)
# whatever's left
n_1 = int(n - n_2 - 3)
return '{0}...{1}'.format(s[:n_1], s[-n_2:])
def weeknumber(datetime):
return datetime.date().isocalendar()[1]
def fmtweek(datetime):
(year, week) = datetime.isocalendar()[:2]
return '%04dW%02d' % (year, week)
def next_available_weekday(dt):
MONDAY=0
SUNDAY=6
if dt.weekday() == MONDAY:
# Skip weekends
delta = timedelta(days=3)
elif dt.weekday() == SUNDAY:
# Skip weekends
delta = timedelta(days=2)
else:
delta = timedelta(days=1)
return dt - delta
def human_duration(total_duration, duration_categories_map, max_segments=5):
groupped_duration = dict.fromkeys(duration_categories_map.keys(), 0)
duration_categories = sorted(duration_categories_map.items(), key=itemgetter(1), reverse=True)
duration_categories = [d[0] for d in duration_categories]
for duration_cat in duration_categories:
# groupped_duration[duration_cat] = int(round(total_duration / duration_categories_map[duration_cat]))
groupped_duration[duration_cat] = total_duration // duration_categories_map[duration_cat]
total_duration -= groupped_duration[duration_cat] * duration_categories_map[duration_cat]
human_time = ' '.join(["%d%s" % (groupped_duration[cat], cat) for cat in duration_categories if groupped_duration[cat] > 0])
# Cro out low precision (this should be smarte rounding)
if max_segments < len(human_time.split(' ')):
human_time = ' '.join(human_time.split(' ')[:max_segments])
return human_time
def mean(values):
if len(values) == 0: return None
return sum(values) / len(values)
def has_optional_flag(string):
return string is not None and "M" in string
def extract_categories(string):
"""
30m
5w
Math 2w
Math 3d Jap 9w
Bio
"""
CATEGORY_REGEX = '(?P<cat>[a-zA-Z]{3,})?\s?(?P<duration>\d+(m|h|d|w|M|q))?'
categories = {}
for match in re.finditer(CATEGORY_REGEX, string):
if not (match.group('duration') is None and match.group('cat') is None):
cat = str(match.group('cat'))
categories[cat] = {}
if match.group('duration'):
dur = int(match.group('duration')[:-1])
unit = match.group('duration')[-1]
else:
dur = None
unit = None
categories[cat]['duration_value'] = dur,
categories[cat]['duration_unit'] = unit
return categories
def parse_end_date(str):
DATE_FORMAT = '%Y-%m-%d'
return datetime.strptime(str, DATE_FORMAT) if str else None
def extract_task_metadata(task):
TASK_META_MATCH_REGEX = '\[((?P<flags>M)(?![a-zA-Z])\s?)?(?P<categories>(\d+\w\s?)?(\w{3,})?(\w{3,}\s\d+\w\s?)*)(?P<end_date>\d{4}-\d{2}-\d{2})?\]$'
TaskMeta = namedtuple('TaskMeta', ['optional', 'categories', 'end_date'])
matches = re.search(TASK_META_MATCH_REGEX, task)
if matches:
optional = has_optional_flag(matches.group('flags'))
categories = extract_categories(matches.group('categories'))
end_date = parse_end_date(matches.group('end_date'))
meta = TaskMeta(
optional,
categories,
end_date
)
raw_meta = matches.group(0)
else:
raw_meta = ""
categories = {}
categories['None'] = {}
categories['None']['duration_value'] = None,
categories['None']['duration_unit'] = None
meta = TaskMeta(False, categories, None)
return (meta, raw_meta)
def weighted_sampling_without_replacement(l, n, myrandom=None):
"""Selects without replacement n random elements from a list of (weight, item) tuples."""
if myrandom:
l = sorted((myrandom.random() * x[0], x[1]) for x in l)
else:
import random
l = sorted((random.random() * x[0], x[1]) for x in l)
return l[-n:]