-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.py
295 lines (194 loc) · 8.68 KB
/
util.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
# -*- coding: utf-8 -*-
"""
Created on Wed May 16 12:44:42 2018
@author: CYRUS DSOUZA
"""
#----------------------------------------------------------------------------------#
import traceback
import random
import sys
import re
import string
import itertools
import time
import globs as gb
#----------------------------------------------------------------------------------#
def id_generator(size = 10):
return "".join(random.choice('0123456789ABCDEF') for i in range(size))
#----------------------------------------------------------------------------------#
def find_ngrams(input_list, n):
return zip(*[input_list[i:] for i in range(n)])
#----------------------------------------------------------------------------------#
def peek(iterable):
#used to iterate through generators
try:
first = next(iterable)
except StopIteration:
return None
return first, itertools.chain([first], iterable)
def resolve_symbols(string):
if not string.strip():
return string
name = ""
tokens = list(string.split())
for token in tokens:
if gb.DECIMAL_DELIM in token:
token = token.replace(gb.DECIMAL_DELIM,".")
if gb.LESSTHAN_DELIM in string:
token = token.replace(gb.LESSTHAN_DELIM,"<")
if gb.GREATERTHAN_DELIM in string:
token = token.replace(gb.GREATERTHAN_DELIM,">")
if gb.PERCENTAGE_DELIM in string:
token = token.replace(gb.PERCENTAGE_DELIM,"%")
if gb.DOLLAR_DELIM in string:
token = token.replace(gb.DOLLAR_DELIM,"$")
name += token + " "
return name.strip()
def odb_number_formatter(string, from_name_formatter= False):
"""
Check whether a string is a number, decimal, greaterthan, lessthan, percentage
and other symbols
"""
if not string.strip():
return string
tokens = list(string.split())
#Check if the end of the string is a decimal vs punctuation
name = ""
if "." in tokens[-1]:
if list(tokens[-1])[-1] == '.':
tokens[-1] = tokens[-1].replace(".","")
for token in tokens:
character_token = list(token)
if "." in character_token:
token = token.replace(".",gb.DECIMAL_DELIM)
if "<" in character_token:
token = token.replace("<",gb.LESSTHAN_DELIM)
if ">" in character_token:
token = token.replace(">",gb.GREATERTHAN_DELIM)
if "%" in character_token:
token = token.replace("%", gb.PERCENTAGE_DELIM)
if "$" in character_token:
token = token.replace("$", gb.DOLLAR_DELIM)
if "," in character_token:
comma = character_token.index(",")
if comma == len(character_token)-1:
token = token.replace(",","")
elif character_token[comma-1].isdigit() and \
character_token[comma+1].isdigit():
token = token.replace(",", "")
name += token + " "
return name.strip()
def odb_name_formatter(name, sentence = False):
"""
OrientDB requires class names to be only character based and does not allow
the class to start with the number as well as it should not have spaces in them
>>> odb_name_formatter("2017 ABC plan")
>>> '#_2017'_ABC_plan'
>>> odb_name_formatter("ABC plan plc")
>>> "ABC_plan_plc"
"""
original_name = name
refined_order = {}
#check for spaces in the string
if " " in name:
newname = odb_number_formatter(name, from_name_formatter = True)
try:
name = newname.translate(string.punctuation)
except Exception as e:
name = newname
# print e
name = "_".join(name.split())
else:
name = odb_number_formatter(name)
#check if a number exists in the string
if any(char.isdigit() for char in name):
dig_find = re.compile(r"[\d]+")
word_find = re.compile(r"[A-Za-z]+")
space_find = re.compile(r"[_]")
for dig_matcher in dig_find.finditer(name):
dm,dg = dig_matcher.start(), dig_matcher.group()
refined_order[dm] = dg
for word_matcher in word_find.finditer(name):
wm,wg = word_matcher.start(), word_matcher.group()
refined_order[wm] = wg
for space_matcher in space_find.finditer(name):
sm, sg = space_matcher.start(), space_matcher.group()
refined_order[sm] = sg
#check if the first element is a number
if 0 in refined_order and refined_order[0].isdigit():
refined_order[0] = gb.CLASSNAME_DELIM + refined_order[0]
#sort the list to get the order of the string
refined_order_list = sorted(refined_order.iteritems())
final_refined_order_list = {}
skip_list = []
#To make sure we dont separate numbers within words like 'EC4'
#Earlier this used to be separated like ec_4 instead of ec4
for i in range(len(refined_order_list)):
if i == len(refined_order_list)-1:
if refined_order_list[i] in skip_list:
continue
if refined_order_list[i][1].isdigit():
if sentence:
old_value = refined_order_list[i][1]
final_refined_order_list[refined_order_list[i][0]] = old_value
else:
break
old_value = refined_order_list[i][1]
final_refined_order_list[refined_order_list[i][0]] = old_value
break
if refined_order_list[i] in skip_list:
continue
if refined_order_list[i][1] == "_":
continue
if refined_order_list[i+1][1] != "_":
new_value = refined_order_list[i][1] + refined_order_list[i+1][1]
final_refined_order_list[refined_order_list[i][0]] = new_value
skip_list.append(refined_order_list[i+1])
else:
old_value = refined_order_list[i][1]
final_refined_order_list[refined_order_list[i][0]] = old_value
final_refined_order_list = sorted(final_refined_order_list.iteritems())
refined_name = "_".join([a[1].lower() for a in final_refined_order_list if a[1] != "_"])
else:
refined_name = name
return refined_name
#----------------------------------------------------------------------------------#
def timecheck(method):
"""Check the time it takes to execute a function"""
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
if 'log_time' in kw:
name = kw.get('log_name', method.__name__.upper())
kw['log_time'][name] = int((te - ts) * 1000)
else:
print '%r %2.2f ms' % \
(method.__name__, (te - ts) * 1000)
return result
return timed
#----------------------------------------------------------------------------------#
def errorcheck(method):
"""Check the errors for custom functions"""
def check(*args, **kw):
try:
result = method(*args, **kw)
return result
except Exception as e:
print(format_exception(e))
print("Error occured in '{}' with error - [{}].\n Check Traceback for further details : -->".format(method.__name__,e))
print(format_exception(e))
#
return check
#----------------------------------------------------------------------------------#
def format_exception(e):
exception_list = traceback.format_stack()
exception_list = exception_list[:-2]
exception_list.extend(traceback.format_tb(sys.exc_info()[2]))
exception_list.extend(traceback.format_exception_only(sys.exc_info()[0], sys.exc_info()[1]))
exception_str = "Traceback (most recent call last):\n"
exception_str += "".join(exception_list)
# Removing the last \n
exception_str = exception_str[:-1]
return exception_str
#----------------------------------------------------------------------------------#