Esempio n. 1
0
    def __datetime_addtime__(self, dt, secs, neg=False, days=0):

        chk1 = __dtobj_check__(self, dt, 'dt')
        if (not chk1):
            return False

        test = check.type_test_print(secs, int, 'secs', '__datetime_addtime__')
        if (not test):
            return test
        test = check.type_test_print(days, int, 'days', '__datetime_addtime__')
        if (not test):
            return test

        if (neg):
            coef = -1
        else:
            coef = 1

        try:
            delt_t = datetime.timedelta(days, secs)
            final_dt = dt + coef * delt_t
        except:
            print(
                "[__datetime_addtime__] Error: adding 'secs' to datetime object 'dt' failed"
            )
            return False

        return final_dt
Esempio n. 2
0
def flat_file_write(file_out, add_list=[], par=False, ptype='w+'):
    '''
    flat_file_write(file_out, add_list = [], par=False, ptype='w')

    Description: Writes a list of strings to an output file, various options for parsing

    (e.g.)

        flat_file_write('file.in',["This is the first line!","This is line #2!"])

    Variables:
    
        'file_out': file string pathway, if only a single node is given, current (path) directory is assumed

        'add_list': [*] list of strings, each string is a separate line, order denoted by the index. 

        'ptype': [*] a string in found in the ptype_write list.         

        'par': [*] True if endline character is to be added to each output string, else False. 

    Output: Success Boolean         

    '''

    # Testing proper variable types
    test = __io_opt_test__(ptype, 'write', par=par)
    if (not test):
        return False

    test = check.type_test_print(file_out, str, 'file_out', 'flat_file_write')
    if (not test):
        return False
    test = check.type_test_print(add_list, list, 'add_list', 'flat_file_write')
    if (not test):
        return False

    n = len(add_list)
    for i in range(n):
        test = check.type_test_print(add_list[i], str,
                                     'add_list[' + str(i) + ']',
                                     'flat_file_write')
        if (not test):
            return False

    # Print content to file
    try:
        with open(file_out, ptype) as fout:
            for i in add_list:
                if (par):
                    fout.write(i + "\n")
                else:
                    fout.write(i)
        return True
    except:
        print(
            "[flat_file_write] Error: 'add_list' lines could not be printed to file"
        )
        __attempt_path_print__(file_out, 'file_out')
        return False
Esempio n. 3
0
def __grab_list_test__(grab_list, n, m, repeat=False, change_list=None):

    test = check.type_test_print(grab_list, list, 'grab_list',
                                 '__grab_list_test__')
    if (not test):
        return False

    if (n > 0):
        for i in range(n):
            test = check.type_test_print(grab_list[i], int,
                                         'grab_list[' + str(i) + ']',
                                         '__grab_list_test__')
            if (not test):
                return False

    if (repeat):
        saut = grab_list[1:-1]
        test = __dup_check__(saut)
        if (test):
            print("[__grab_list_test__] Error: 'saut' values must be unique")
            return False
    else:
        test = __dup_check__(grab_list)
        if (test):
            print(
                "[__grab_list_test__] Error: 'grab_list' values must be unique"
            )
            return False

    if (n > m):
        print(
            "[__grab_list_test__] Error: 'grab_list' is longer than the number of file lines"
        )
        return False
    if (m < (max(grab_list) + 1)):
        print(
            "[__grab_list_test__] Error: replacement line number greater than the max number of files lines"
        )
        return False

    if (change_list != None):
        if (len(grab_list) != len(change_list)):
            print(
                "[__grab_list_test__] Error: 'grab_list' and 'change_list' must have the same length"
            )
            return False

        for i in range(len(change_list)):
            test = check.type_test_print(change_list[i], str,
                                         'change_list[' + str(i) + ']',
                                         'flat_file_replace')
            if (not test):
                return False
    return True
Esempio n. 4
0
def array_duplicate_return(array, inverse=False):
    '''
    Description: Checks for duplicates in an array-like object 
                 If duplicates are found, a list of the duplicate values is returned 
                 Else an empty list is returned
    '''
    test = __check__.type_test_print(array,
                                     'arr',
                                     var_name='array',
                                     func_name='array_duplicate_check')
    if (not test):
        return False
    s = set()
    list_dup = []
    for i in array:
        if i in s:
            if (i not in list_dup):
                list_dup.append(i)
        else:
            s.add(i)
    if (inverse):
        output = s - set(list_dup)
        return list(output)
    else:
        return list_dup
Esempio n. 5
0
    def __date_list_to_str__(self, array):
        test = check.type_test_print(array, list, 'array',
                                     '__date_list_to_str__')
        if (not test):
            return test

        string = array[1] + '-' + array[2] + '-' + array[0]
        return string
Esempio n. 6
0
    def __date_str_to_str__(self, string):
        test = check.type_test_print(string, list, 'string',
                                     '__date_str_to_str__')
        if (not test):
            return test

        array = string.split('-')
        string = array[1] + '-' + array[2] + '-' + array[0]
        return string
Esempio n. 7
0
    def __str_to_date_list__(self, string, delim='-'):
        test = check.type_test_print(string, str, 'string',
                                     '__str_to_date_list__')
        if (not test):
            return test

        array = string.split(delim)
        date_list = [int(array[2]), int(array[0]), int(array[1])]
        return date_list
Esempio n. 8
0
    def get_time(self, time=None, heure=None):

        if (time != None):
            array_bool = check.type_test_print(time,
                                               'arr',
                                               name='time',
                                               func_name='get_time')
            if (isinstance(time, list) or isinstance(time, tuple)):
                hour = int(time[0])
                minute = int(time[1])
                second = int(time[2])
            elif (isinstance(time, str)):
                time_array = time.split(':')
                hour = int(time_array[0])
                minute = int(time_array[1])
                second = int(time_array[2])
            else:
                print(
                    "[get_time] Error: 'time' object must be string or list/tuple; not a "
                    + str(type(time)))
                return False
        else:
            cdt = self.get_datetime('Time', 'list')
            hour = int(cdt[0])
            minute = int(cdt[1])
            second = int(round(float(cdt[2]), 0))

        if (heure == None or heure == '24' or heure == ''):
            if (second < 10):
                second = '0' + str(second)
            else:
                second = str(second)
            if (minute < 10):
                minute = '0' + str(minute)
            else:
                minute = str(minute)
            if (hour < 10):
                hour = '0' + str(hour)
            else:
                hour = str(hour)
            time_str = str(hour) + ':' + str(minute) + ':' + str(second)
        elif (heure == '18'):
            time_str = __convert_clock_18hr__(hour, minute, second)
        elif (heure == '16hs'):
            time_str = __convert_clock_16hr_hs__(hour, minute, second)
        elif (heure == '15'):
            time_str = __convert_clock_15hr__(hour, minute, second)
        elif (heure == '12'):
            time_str = __convert_clock_12hr__(hour, minute, second)
        elif (heure == '6'):
            time_str = __convert_clock_6hr__(hour, minute, second)
        else:
            print("[] Error: 'heure' hour parameter, " + str(heure) +
                  " not recognized")
            return False
        return time_str
Esempio n. 9
0
def __io_opt_test__(ptype, io, par=False, count_offset=False):

    success = True

    if (ptype not in ptype_list):
        success = False
        try:
            print("[__io_opt_test__] Error: 'ptype', '" + str(ptype) +
                  "' is not a valid 'ptype' option")
        except:
            print(
                "[__io_opt_test__] Error: 'ptype', could not be parsed as a valid 'ptype' option string"
            )

    if (io == 'read'):
        if (ptype not in ptype_read):
            success = False
            print("[__io_opt_test__] Error: ptype, '" + str(ptype) +
                  "' is not a valid read option")
    elif (io == 'write'):
        if (ptype not in ptype_write):
            success = False
            print("[__io_opt_test__] Error: ptype, '" + str(ptype) +
                  "' is not a valid write option")
    else:
        success = False
        print(
            "[__io_opt_test__] Error: option 'io' must be either 'read' or 'write'"
        )

    test = check.type_test_print(par, bool, 'par', '__io_opt_test__')
    if (not test):
        success = False

    test = check.type_test_print(count_offset, bool, 'count_offset',
                                 '__io_opt_test__')
    if (not test):
        success = False

    return success
Esempio n. 10
0
    def __date_list_to_ordate__(self, array):
        test = check.type_test_print(array, list, 'array',
                                     '__date_list_to_ordate__')
        if (not test):
            return test

        try:
            dateobj = datetime.date(int(array[0]), int(array[1]),
                                    int(array[2]))
            ordate = dateobj.toordinal()
            return ordate
        except:
            print(
                "[__date_list_to_ordate__] Error: input array could not be parsed as a date_list"
            )
            return False
Esempio n. 11
0
def array_duplicate_check(array):
    '''
    Description: Checks for duplicates in an array-like object 
                 If duplicates are found, True is returned 
                 Else False is returned
    '''
    test = __check__.type_test_print(array,
                                     'arr',
                                     var_name='array',
                                     func_name='array_duplicate_check')
    if (not test):
        return False
    s = set()
    for i in array:
        if i in s:
            return True
        else:
            s.add(i)
    return False
Esempio n. 12
0
 def __str_to_time_list__(self, string, output=list):
     test = check.type_test_print(string, str, 'string',
                                  '__str_to_time_list__')
     if (not test):
         return test
     string_split = string.split(':')
     hour = string_split[0]
     minute = string_split[1]
     second = string_split[2]
     if (output == list):
         array = [int(float(hour)), int(float(minute)), int(float(second))]
         return array
     elif (output == tuple):
         array = (int(float(hour)), int(float(minute)), int(float(second)))
         return array
     else:
         print("[__str_to_time_list__] Error: 'output' value, " +
               str(output) + " not recognized")
         return False
Esempio n. 13
0
    def get_weekday(self, string):
        test = check.type_test_print(string, str, 'string', 'get_weekday')
        if (not test):
            return test

        date_list = self.__str_to_date_list__(string)
        if (date_list == False):
            return False

        year, month, day = date_list

        weekday_nums = [i for i in range(7)]
        weekday_names = [
            'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday',
            'Sunday', 'Sunday'
        ]
        weekday_dict = dict(zip(weekday_nums, weekday_names))

        weekday_val = datetime.date(year, month, day).weekday()
        return weekday_dict[weekday_val]
Esempio n. 14
0
def flat_file_read(file_in, ptype='r'):
    '''
    flat_file_read(file_in, ptype='r')

    Description: Writes a list of strings (1 line per string) from an input file, various options for parsing
      
    (e.g.) :
    
        flat_file_read('file.in', ptype='rb')   

    Variables:
    
        'file_in': file string pathway, if only a single node is given, current (path) directory is assumed

        'ptype': [*] a string in found in the 'ptype_read list'.         

    Output: List of Strings; Output: Success Boolean              
     
    '''

    test = __io_opt_test__(ptype, 'read')
    if (not test):
        return False

    test = check.type_test_print(file_in, str, 'file_in', 'flat_file_read')
    if (not test):
        return False

    try:
        with open(file_in, ptype) as file_in:
            file_lines = file_in.readlines()
        return file_lines
    except:
        print("[flat_file_read] Error: File could not be read")
        __attempt_path_print__(file_in)
        return False
Esempio n. 15
0
    def get_datetime(self, value='datetime', form='str', indt=None):

        if (indt == None):
            datetime_now = datetime.datetime.now()
        else:
            test = check.type_test_print(indt, 'arr', 'indt', 'get_datetime')
            if (not test):
                return test
            if (len(indt) < 2):
                print(
                    "[get_datetime] Error: 'indt' should be an array with a length of 2"
                )
                return False
            for i in indt:
                test = check.type_test_print(i, str, 'indt', 'get_datetime')
                if (not test):
                    print(
                        "[get_datetime] Error: 'indt' should contain two strings; corrosponding to date and time"
                    )
                    return test
            dstr = indt[0]
            tstr = indt[1]
            datetime_now = self.__str_to_datetime__(dstr, tstr)

        date_now = datetime_now.date()
        time_now = datetime_now.time()

        datevals = ['DATE', 'Date', 'date']
        timevals = ['TIME', 'Time', 'time']
        datetimevals = ['DATETIME', 'Datetime', 'datetime']

        time_str = str(datetime_now).split(' ')[1]
        time_list = time_str.split(':')
        time_int = [
            int(time_list[0]),
            int(time_list[1]),
            int(round(float(time_list[2]), 0))
        ]
        time_num = [int(time_list[0]), int(time_list[1]), float(time_list[2])]

        if (value in timevals):
            if (form == 'raw'):
                return time_now
            elif (form == 'int'):
                return time_int
            elif (form == 'num'):
                return time_num
            elif (form == 'list'):
                return time_list
            elif (form == 'str'):
                return time_str
            else:
                print("[get_datetime] Error: 'form' value, " + form +
                      " not recognized")
                return False

        date_str = str(datetime_now).split(' ')[0]
        date_list = date_str.split('-')
        date_str = self.__date_list_to_str__(date_list)
        date_list = [date_list[1], date_list[2], date_list[0]]
        date_int = [int(date_list[0]), int(date_list[1]), int(date_list[2])]

        if (value in datevals):
            if (form == 'raw'):
                return date_now
            elif (form == 'int' or form == 'num'):
                return date_int
            elif (form == 'list'):
                return date_list
            elif (form == 'str'):
                return date_str
            else:
                print("[get_datetime] Error: 'form' value, " + form +
                      " not recognized")
                return False

        dt_int = (date_int, time_int)
        dt_num = (date_int, time_num)
        dt_list = (date_list, time_list)
        dt_str = (date_str, time_str)

        if (value in datetimevals):
            if (form == 'raw'):
                return datetime_now
            elif (form == 'int'):
                return dt_int
            elif (form == 'num'):
                return dt_num
            elif (form == 'list'):
                return dt_list
            elif (form == 'str'):
                return dt_str
            else:
                print("[get_datetime] Error: 'form' value, " + form +
                      " not recognized")
                return False

        else:
            print("[get_datetime] Error: 'value' " + value +
                  " not recognized; no action taken")
            return False
Esempio n. 16
0
def flat_file_replace(file_out,
                      grab_list,
                      change_list,
                      count_offset=True,
                      par=False,
                      ptype='w'):
    '''
    Description: In the file 'file_out', the lines in 'grab_list' are replaced with the strings in 'change_list'

   (e.g.) 
   
       flat_file_replace('file.in', [1,2], ["This is the first line!","This is line #2!"])

    Variables:
    
        'file_out': file string pathway, if only a single node is given, current (path) directory is assumed

        'grab_list': list of integers, each integer corrosponds to a line number, options for 0 or 1 index start 

        'change_list': list of strings, each string is a separate line

        'par': [*] True if endline character is to be added to each output string, else False. 

        'count_offset': [*] True if values in grab_list corrospond to line numbers, else values corrospond to list index

        'ptype': [*] a string in found in the ptype_write list.         

    Output: Success Boolean   
    '''

    # Testing proper variable types
    test = __io_opt_test__(ptype, 'write', par=par, count_offset=count_offset)
    if (not test):
        return False
    test = check.type_test_print(file_out, str, 'file_out',
                                 'flat_file_replace')
    if (not test):
        return False

    # Accounts for the difference between line number (starting at 1) and python indexing (starting at 0)
    if (count_offset):
        grab_list = [x - 1 for x in grab_list]

    # Read in file
    file_lines = flat_file_read(file_out)
    m = len(file_lines)

    # Testing the lengths of variable arrays
    n = len(grab_list)
    test = __grab_list_test__(grab_list,
                              n,
                              m,
                              repeat=False,
                              change_list=change_list)
    if (not test):
        return False

    # Make modifications
    for i in grab_list:
        j = grab_list.index(i)
        if (par):
            file_lines[i] = change_list[j] + "\n"
        else:
            file_lines[i] = change_list[j]

    # Print modifications to file
    result = flat_file_write(file_out, file_lines, ptype=ptype)
    return result
Esempio n. 17
0
def flat_file_copy(file_in,
                   file_out,
                   grab_list,
                   repeat=False,
                   group=0,
                   ptype='w'):
    '''
    Description: Grabs the lines in 'grab_list' as strings from the file 'file_in'
                 the lines in grab_list are then printed to file_out 

   (e.g.) 
   
       flat_file_replace('file.in', [1,2], ["This is the first line!","This is line #2!"])

    Variables:
    
        'file_out': file string pathway, if only a single node is given, current (path) directory is assumed

        'grab_list': list of integers, each integer corrosponds to a line number, options for 0 or 1 index start 

        'scrub': [bool] (False), Removes end and return line characters from each grabbed string  

        'repeat': [bool] (False), if True, then 'grouping' formatting is used

        'count_offset': [bool] (True), shifts 'grab_list' values by 1 to align line numbers with python indices

        'ptype': [string] ('r'), reading mode          

    Output: List of Strings; Output: Success Boolean  
    '''

    # basic dummy check of variables 'file_out' and 'group'
    test = check.type_test_print(file_out, str, 'file_out', 'flat_file_copy')
    if (not test):
        return False
    test = check.type_test_print(group, int, 'group', 'flat_file_copy')
    if (not test):
        return False
    if (group < 0):
        print("[] Error: 'group' must be a non-negative integer")
        return False

    # Grab appropriate lines (as specified from grab_list and repeat) from 'file_in'
    lines = flat_file_grab(file_in, grab_list, scrub=False, repeat=repeat)
    if (lines == False):
        print("[flat_file_copy] Error: retrieving data from 'file_in' failed")
        try:
            print("'file_in' pathway: " + file_in)
            return False
        except:
            print(
                "'file_in' pathway could not be parsed, check the pathway for errors"
            )
            return False

    # Parse and return 'out_list' through 'repeat' and 'group' options
    if (repeat):
        nlines = len(lines)
        out_list = []

        if (group > 0):
            for i in range(nlines):
                out_list.append(lines[i])
                if (i > 0 and (i + 1) % group == 0):
                    out_list.append("\n")
    else:
        if (group > 0):
            out_list.append(lines[i])
            if (i > 0 and (i + 1) % group == 0):
                out_list.append("\n")

    result = flat_file_write(file_out, out_list, ptype=ptype)
    return result
Esempio n. 18
0
def flat_file_grab(file_in,
                   grab_list=[],
                   scrub=False,
                   repeat=False,
                   count_offset=True,
                   ptype='r'):
    '''
    Description: Grabs the lines in 'grab_list' as strings from the file 'file_in'

   (e.g.) 
   
       flat_file_replace('file.in', [1,2], ["This is the first line!","This is line #2!"])

    Variables:
    
        'file_out': file string pathway, if only a single node is given, current (path) directory is assumed

        'grab_list': list of integers, each integer corrosponds to a line number, options for 0 or 1 index start 

        'scrub': [bool] (False), Removes end and return line characters from each grabbed string  

        'repeat': [bool] (False), if True, then 'grouping' formatting is used

        'count_offset': [bool] (True), shifts 'grab_list' values by 1 to align line numbers with python indices

        'ptype': [string] ('r'), reading mode          

    Output: List of Strings; Output: Success Boolean  
    '''

    # Testing proper variable types
    test = __io_opt_test__(ptype, 'read', count_offset=count_offset)
    if (not test):
        return False
    test = check.type_test_print(file_in, str, 'file_in', 'flat_file_grab')
    if (not test):
        return False

    # Accounts for the difference between line number (starting at 1) and python indexing (starting at 0)
    if (count_offset):
        grab_list = [x - 1 for x in grab_list]
    n = len(grab_list)

    # Read in file
    file_lines = flat_file_read(file_in)
    if (n == 0):
        if (scrub == True):
            for i in range(len(file_lines)):
                file_lines[i] = file_lines[i].strip('\n').strip('\r')
            return file_lines
        else:
            return file_lines
    m = len(file_lines)

    # Testing the grab_list
    test = __grab_list_test__(grab_list, n, m, repeat=repeat)
    if (not test):
        return False

    # Parse and return file_lines through 'repeat' option:
    out_lines = []

    if (repeat):
        out_lines = __list_repeat__(grab_list, file_lines, scrub)
        if (out_lines == False):
            return False
    else:
        for i in range(n):
            out_lines.append(file_lines[grab_list[i]])
            if (scrub == True):
                out_lines[i] = out_lines[i].strip("\n").strip("\r")
    return out_lines