-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCommon.py
517 lines (396 loc) · 17.4 KB
/
Common.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
import random
import tinydb
# Common functions to be used throughout the project
def CleanedFileName(FileName):
"""Takes Path String and returns a cleaned version of the string that can be used as a file name
Args:
FileName (str): file name to be cleaned NOT WHOLE PATH NOR EXTENSION
Returns:
str: Cleaned file name
"""
FileName = FileName.replace(" ", "_")
FileName = FileName.replace("/", "-")
FileName = FileName.replace("\\", "-")
FileName = FileName.replace(":", "-")
FileName = FileName.replace("*", "-")
FileName = FileName.replace("?", "-")
FileName = FileName.replace('"', "-")
FileName = FileName.replace("<", "-")
FileName = FileName.replace(">", "-")
FileName = FileName.replace("|", "-")
FileName = FileName.replace(".", "-") # Remove false file extension
return FileName
class Decimal: # Replacement for a float that has no floating point error
def __init__(self, Number=0):
"""
Args:
Number (Int, String, Decimal): Number to be held as a decimal)
"""
self.value = 0 # Holds the value of the decimal
self.power = 0 # Holds the power of the decimal ie value * 10^power
if type(Number) == int:
self.value = Number
elif type(Number) == str:
if "." in Number:
while Number[-1] == "0": # Remove trailing zeros
Number = Number[:-1] # Remove last digit
self.power = (
Number.index(".") - len(Number) + 1
) # Negative power as decimal is less than 1
self.value = int(Number.replace(".", ""))
else:
self.value = int(Number)
elif type(Number) == Decimal:
self.value = Number.value
self.power = Number.power
elif type(Number) == float:
StringFloat = str(Number)
if "." in StringFloat:
self.value = int(StringFloat.replace(".", ""))
self.power = StringFloat.index(".") - len(StringFloat) + 1
else:
self.value = int(StringFloat)
else:
print(Number)
raise TypeError # If the type is not supported raise an error
self.Simplify() # Simplify the decimal
def Simplify(self):
"""Simplifies the decimal by removing trailing zeros
Returns:
Decimal: Simplified decimal
"""
if self.value == 0: # If the value is 0 the power is 0
self.power = 0
return self
while self.value % 10 == 0:
self.value /= 10
self.power += 1
self.value = int(self.value)
return self
def __str__(self) -> str: # Returns the decimal as a string
Digits = []
if self.value == 0: # If the value is 0 return 0
return "0"
if self.power > 0: # If the power is positive multiply the value by 10^power
MutatedValue = self.value * (10**self.power)
else:
MutatedValue = self.value
for i in range(len(str(abs(MutatedValue)))): # Add each digit to the list
Digits.append(str(self.get_digit(MutatedValue, i)))
if self.power < 0: # If the power is negative add a decimal point
Digits.insert(len(Digits) + self.power, ".")
if self.value < 0: # If the value is negative add a negative sign
Digits.insert(0, "-")
return "".join(Digits)
def __float__(self) -> float: # Returns the decimal as a float
return float(self.value * 10**self.power)
def __int__(self) -> int: # Returns the decimal as an int
return int(self.value * 10**self.power)
def get_digit(self, number, n):
"""Returns the nth digit of a number
Args:
number (int): Number to get the digit from
n (int): Digit to get
Returns:
int: nth digit of number
"""
if n < 0:
raise IndexError # If n is negative raise an error
if n >= len(str(abs(number))):
raise IndexError # If n is greater than the number of digits in number raise an error
number = abs(
number
) # Make the number positive so that the index does not include a negative sign
return int(str(number)[n])
def add(self, Number2=0):
"""Adds the value of Number2 to the value of the decimal
Args:
Number2 (Int, String, Decimal): Number to be added to the decimal
Returns:
Decimal: Decimal with the value of Number2 added to it
"""
if not type(Number2) == Decimal:
Number2 = Decimal(Number2)
if (
not self.power == Number2.power
): # If the powers are not equal make them equal by multiplying by 10^difference
if self.power > Number2.power:
Copy1 = Decimal(self)
Copy1.value *= 10 ** (self.power - Number2.power)
Copy1.power = Number2.power
Copy2 = Decimal(Number2)
else:
Copy2 = Decimal(Number2)
Copy2.value *= 10 ** (Number2.power - self.power)
Copy2.power = self.power
Copy1 = Decimal(self)
else:
Copy1 = Decimal(self)
Copy2 = Decimal(Number2)
self.value = Copy1.value + Copy2.value
self.power = Copy1.power
self.Simplify() # Simplify the decimal
# return self
def subtract(self, Number2=0):
"""Subtracts the value of Number2 from the value of the decimal
Args:
Number2 (Int, String, Decimal): Number to be subtracted from the decimal
Returns:
Decimal: Decimal with the value of Number2 subtracted from it
"""
if not type(Number2) == Decimal:
Number2 = Decimal(Number2)
if (
not self.power == Number2.power
): # If the powers are not equal make them equal by multiplying by 10^difference
if self.power > Number2.power:
Copy1 = Decimal(self)
Copy1.value *= 10 ** (self.power - Number2.power)
Copy1.power = Number2.power
Copy2 = Decimal(Number2)
else:
Copy2 = Decimal(Number2)
Copy2.value *= 10 ** (Number2.power - self.power)
Copy2.power = self.power
Copy1 = Decimal(self)
else:
Copy1 = Decimal(self)
Copy2 = Decimal(Number2)
self.value = Copy1.value - Copy2.value
self.power = Copy1.power
self.Simplify() # Simplify the decimal
# return self
def multiply(self, Number2=0):
"""Multiplies the value of the decimal by the value of Number2
Args:
Number2 (Int, String, Decimal): Number to be multiplied by the decimal
Returns:
Decimal: Decimal with the value of Number2 multiplied by it
"""
if not type(Number2) == Decimal: # If Number2 is not a decimal make it one
Number2 = Decimal(Number2)
self.value *= Number2.value # Multiply the values
self.power += Number2.power # Add the powers
self.Simplify() # Simplify the decimal
# return self
def divide(self, Number2=1, Accuracy=2):
"""Divides the value of the decimal by the value of Number2
Args:
Number2 (Int, String, Decimal): Number to be divided by the decimal
Accuracy (int, optional): Number of additional decimal places to calculate past the decimals of the two numbers. Defaults to 2.
Returns:
Decimal: Decimal with the value of itself divided by Number2
"""
if not type(Number2) == Decimal: # If Number2 is not a decimal make it one
Number2 = Decimal(Number2)
if Number2.value == 0:
raise ZeroDivisionError # If Number2 is 0 raise an error
if self.value % Number2.value == 0: # If the value is evenly divisible
self.value /= Number2.value
self.power -= Number2.power
self.Simplify()
return self
# Divide with accuracy given for passes of long division
ResultantDigits = [] # List of digits in the resultant decimal
Dividend = self.get_digit(self.value, 0) # First digit of the dividend to be divided
UsedAccuracy = 0 # Number of digits of accuracy used in loop
ExtraPower = (
-1
) # Power of the decimal to be added to the resultant decimal (is positive to show decimal place is moved x places to the left: 10^(-x))
Number1Index = 0 # Index of the digit of the dividend that has been used in the loop
while UsedAccuracy < Accuracy:
if Dividend == 0: # If the dividend is 0
break # Break out of the loop as the division is complete
if (
Dividend // Number2.value >= 1
): # If the dividend is wholely divisible by the divisor
ResultantDigits.append(
Dividend // Number2.value
) # Add the result of the division to the resultant decimal
Dividend = (
Dividend % Number2.value
) # Set the dividend to the remainder of the division
else: # If the dividend is not wholely divisible by the divisor
ResultantDigits.append(0) # Add a 0 to the resultant decimal
if (
Number1Index < len(str(self.value)) - 1
): # If there are more digits of the dividend to be used
Number1Index += 1 # Increment the index of the digit of the dividend to be used
Dividend *= 10 # Multiply the dividend by 10 to add the next digit
Dividend += self.get_digit(
self.value, Number1Index
) # Add the next digit of the dividend to the dividend
else: # If there are no more digits of the dividend to be used
ExtraPower += (
1 # Increment the power of the decimal to be added to the resultant decimal
)
UsedAccuracy += 1 # Increment the number of digits of accuracy used in the loop
Dividend *= 10 # Multiply the dividend by 10 to add a 0 to the dividend
OriginalValue = self.value # Store the original value of the decimal
self.value = int(
"".join(map(str, ResultantDigits))
) # Set the value of the decimal to the resultant decimal
if (
OriginalValue < 0 ^ Number2.value < 0
): # If the original value of the decimal was negative or the divisor was negative
self.value *= -1 # Make the resultant decimal negative
self.power -= (
Number2.power + ExtraPower
) # Set the power of the decimal to the resultant decimal
# return self
def MonetaryAdd(Number1, Number2):
"""Adds two monetary values together with correct rounding for USD. (2 decimal places)
Args:
Number1 (Int, String, Decimal(Common/Class)): First Number to be added
Number2 (Int, String, Decimal(Common/Class)): Second Number to be added
Returns:
Float: Sum of the two numbers
"""
if not type(Number1) == Decimal:
Number1 = Decimal(Number1)
if not type(Number2) == Decimal:
Number2 = Decimal(Number2)
Number1.add(Number2)
return round(Number1.__float__(), 2)
def MonetarySubtract(Number1, Number2):
"""Subtracts two monetary values together with correct rounding for USD. (2 decimal places)
Args:
Number1 (Int, String, Decimal(Common/Class)): First Number to be subtracted
Number2 (Int, String, Decimal(Common/Class)): Second Number to be subtracted
Returns:
Float: Difference of the two numbers
"""
if not type(Number1) == Decimal:
Number1 = Decimal(Number1)
if not type(Number2) == Decimal:
Number2 = Decimal(Number2)
Number1.subtract(Number2)
return round(Number1.__float__(), 2)
def MonetaryMultiply(Number1, Number2):
"""Multiplies two monetary values together with correct rounding for USD. (2 decimal places)
Args:
Number1 (Int, String, Decimal(Common/Class)): First Number to be multiplied
Number2 (Int, String, Decimal(Common/Class)): Second Number to be multiplied
Returns:
Float: Product of the two numbers
"""
if not type(Number1) == Decimal:
Number1 = Decimal(Number1)
if not type(Number2) == Decimal:
Number2 = Decimal(Number2)
Number1.multiply(Number2)
return round(Number1.__float__(), 2)
def MonetaryDivide(Number1, Number2):
"""Divides two monetary values together with correct rounding for USD. (2 decimal places)
Args:
Number1 (Int, String, Decimal(Common/Class)): First Number to be divided
Number2 (Int, String, Decimal(Common/Class)): Second Number to be divided
Returns:
Float: Quotient of the two numbers
"""
if not type(Number1) == Decimal:
Number1 = Decimal(Number1)
if not type(Number2) == Decimal:
Number2 = Decimal(Number2)
Number1.divide(Number2, 10)
return round(Number1.__float__(), 2)
def MonetarySummation(List):
"""Sums a list of monetary values together with correct rounding for USD. (2 decimal places)
Args:
List (List[Int, String(May Include a $, Skipped if "NA"), Decimal(Common/Class)]): List of numbers to be summed
Returns:
Float: Sum of the numbers in the list
"""
Sum = Decimal()
for Number in List:
if Number == "NA":
continue
if not type(Number) == Decimal:
if type(Number) == str: # If the number is a string
Number = Decimal(Number.replace("$", "")) # Remove the dollar sign if it is present
Number = Decimal(Number)
Sum.add(Number)
return round(Sum.__float__(), 2)
def MonetaryAverage(List):
"""Finds the average of a list of monetary values together with correct rounding for USD. (2 decimal places)
Args:
List (List[Int, String, Decimal(Common/Class)]): List of numbers to be averaged
Returns:
Float: Average of the numbers in the list
"""
Sum = Decimal(0)
for Number in List:
if not type(Number) == Decimal:
Number = Decimal(Number)
Sum = Sum.add(Number)
return round(Sum.divide(len(List)).__float__(), 2)
# UID Functions
def MakeUIDs(order_items, ItemCount):
"""Makes a list of random and UNIQUE UIDs
Args:
order_items (TinyDB/Table/OrderItems): Table of order items to check for UIDs
ItemCount (Int): Number of UIDs to make
Returns:
List[Int]: List of random and unique UIDs
"""
allUIDs = []
order_items = order_items.search(tinydb.Query().process_status == "UTILIZE") # Get all items
if order_items == []: # If there are no items in the database, return a list of random UIDs
returnUIDs = []
returnUIDs.append(random.randint(1000000, 9999999))
for i in range(ItemCount):
UID = random.randint(1000000, 9999999)
while UID in returnUIDs:
UID = random.randint(1000000, 9999999)
returnUIDs.append(UID)
return returnUIDs
for item in order_items:
allUIDs.append(item["item_UID"]) # Add all UIDs to a list
returnUIDs = []
for i in range(ItemCount):
UID = random.randint(1000000, 9999999) # Generate a random UID
while UID in allUIDs: # If the UID is already in the database, generate a new one
UID = random.randint(1000000, 9999999) # Generate a random UID
returnUIDs.append(UID)
return returnUIDs # Return the list of UIDs
def MakeOrderID(orders):
"""Makes a random and UNIQUE order ID
Args:
orders (TinyDB/Table/Orders): Table of orders to check for order IDs
Returns:
Int: Random and unique order ID
"""
allIDs = []
AvailableOrders = orders.search(tinydb.Query().process_status == "UTILIZE") # Get all orders
for order in AvailableOrders:
# Add all order IDs to a list
allIDs.append(int(order["order_number"]))
order_ID = 112
while order_ID in allIDs: # If the order ID is already in the database, generate a new one
order_ID += 1
return order_ID
# Text Alignment Functions
def ColumnAlignment(Rows=[[], []]):
"""Aligns the columns of a list of rows by the longest string in each column
Args:
Rows (list, optional): Row array of columns. Defaults to [[],[]].
Returns:
list: Aligned rows as strings including whitespace
"""
if Rows == [] or Rows == [[]] or Rows == [[], []]: # If there are no rows, return an empty list
return []
maxLengths = []
for i in range(len(Rows[0])): # create a length for each column
maxLengths.append(0)
for row in Rows: # find the longest string in each column
for i in range(len(row)):
if len(str(row[i])) > maxLengths[i]:
maxLengths[i] = len(str(row[i]))
returnRows = []
for row in Rows: # add whitespace to each string to make them the same length
returnRow = []
for i in range(len(row)):
returnRow.append(str(row[i]) + " " * (maxLengths[i] - len(str(row[i]))))
returnRows.append(" ".join(returnRow))
print(returnRows)
return returnRows