import os
import traceback
from itertools import chain
import re
import random
import string

#
def unique(lst):
try:
return list(set(lst))
except:
try:
unique_lst = []
for i in lst:
if i not in unique_lst:
unique_lst.append(i)
return sorted(unique_lst)
except:
traceback.print_exc()
return 0


#
def valid_path(inp, typ):
#
from C0R3.utils.file_mngr import is_path_exist
if not inp:
inp = None
elif inp[0] == "~":
inp = os.path.join(os.path.expanduser("~"), inp[1:])
elif not "/" == inp[0]:
inp = os.path.join(os.path.expanduser("~"), inp)
if "exist" in typ and (not inp or not is_path_exist(inp, empty=1)):
inp = None
return inp


#
def is_digit(num):
try:
return float(num)
except:
return num


#
def is_int(par):
if type(par) == str and par.isnumeric():
return int(par)

else:
try:
if int(par) == par:
return int(par)
except ValueError:
pass
return None


#
def is_bool(par):
if type(par) == str:
par = par.lower()
par = 1 if par in ['1', 'true', 't', 'y', 'yes', 1, True] else 0 if par in ['0', 'false', 'f', 'n', 'no', 0,
False] else None
return par


#
def ip_range_list(lst, new_ip_range):
for n in range(len(lst)):
if any(1 for i in new_ip_range if i in range(lst[n][0], lst[n][1])) or any(
1 for i in lst[n] if i in range(new_ip_range[0], new_ip_range[1])):
lst[n][0] = min(new_ip_range[0], lst[n][0])
lst[n][1] = max(new_ip_range[1], lst[n][1])
return 0
lst.append(new_ip_range)
return 0


#
def list_2d_1d(lst):
return list(chain.from_iterable(lst))


# convert list to dictionary
def list_to_dict(rcnd):
it1 = dict()
[it1.update({c: d}) if not c in it1.keys() else it1.update({c: it1[c] + d}) for rcnditem in rcnd[1] for (c, d) in
rcnditem.items()]
return [rcnd[0], it1]


#
def in_list(string, lst, partially=0):
lst = list(lst)
nlst = [k.upper() for k in lst]
lst = [lst[c] for c in range(len(nlst)) if string.upper() == nlst[c] or (re.match("^" + string, nlst[c], re.I) and
partially)]
return lst


#
def non_empty_list(lst):
return [l for l in lst if l]
while 1:
if not lst[-1]:
lst = lst[:-1]
else:
return lst




def get_random_string(length):
letters = string.ascii_lowercase + string.ascii_uppercase + "0123456789 "
return ''.join(random.choice(letters) for i in range(length))



def sorted_list(lst, column=0, reverse=False):
return sorted(lst, key=lambda l: l[column], reverse=reverse)


def number_to_ordered_string(num):
s = ""
if num < 0:
s, num = "minus",abs(num)
s += "0" if num == 0 else "1st" if num == 1 else "2nd" if num == 2 else "3rd" if num == 3 else str(num) + "th"
return s