Best Python code snippet using autotest_python
Task_1.py
Source:Task_1.py  
1import CarRental2import datetime3import re4monthName = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',5             'November', 'December']6#modifying date format function7def modifyDate(entry):8    # We will be modifying:9    # 1)The date of birth of each object10    flag = 011    object = re.search(r"[-/][0-9]*[-/]", entry.getDob(),re.M | re.S)  # if the date has the format of "/digit/" or "-digit-" it should be modified12    if object:13        replaceString = monthName[int(object.group()[1:len(object.group()) - 1]) - 1]  # the replace string is the monthName element indexed by the digit14        entry.setDob(re.sub(r"[-/][0-9]*[-/]", " " + replaceString + " ", entry.getDob()))15        flag = 116    # 2)The start rental date of each object17    object = re.search(r"[-/][0-9]*[-/]", entry.getSd(), re.M | re.S)18    if object:19        replaceString = monthName[int(object.group()[1:len(object.group()) - 1]) - 1]20        entry.setSd(re.sub(r"[-/][0-9]*[-/]", " " + replaceString + " ", entry.getSd()))21        flag= 122    # 3)The end rental date of each object23    object = re.search(r"[-/][0-9]*[-/]", entry.getEd(), re.M | re.S)24    if object:25        replaceString = monthName[int(object.group()[1:len(object.group()) - 1]) - 1]26        entry.setEd(re.sub(r"[-/][0-9]*[-/]", " " + replaceString + " ", entry.getEd()))27        flag = 128    return flag29# function to try and complete the missing information30def completeMissing(list):31    missingList=[] # this is a list to put the elements which can't be completed32    completeList=[] # this is a list to put the elements which are completed33    printList1 = [0,0,0,0,0,0,0,0,0,0]   #this list will be counting data for printing summary for completed/recovered entries34    printList2 = [0,0,0,0,0,0,0,0,0,0]   #this list will be counting data for printing summary for uncompleted entries(either missing cl, or missing more than a field so that it can not be filled35    for i in list:36        countList = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] #this list will be couting the data for printing summary for each entry seperately37        flag = modifyDate(i)    #if any date in the entry is modified, flag is set to one38        countList[1] = flag    #countList[1] represents if entry is with wrong date format39        if(i.getCl()!=""):      #if cl is missing, then this entry can not be completed40            if (i.getId() == "" or i.getName() == "" or i.getDob() == "" or i.getMobile() == "" or i.getCm() == "" or41                    i.getYear() == "" or i.getSd() == "" or i.getEd() == "" or i.getRb() == ""):42                for j in list:   #start searching the list, to fill the incompleted entry43                    if (i.getCl() == j.getCl()):44                        # get the missing cm from the j.getCm is it's exist45                        if (i.getCm() == ""):46                            countList[7] = 1   #countList[7] states whether a missing cm or not47                            if(j.getCm() != ""):48                              i.setCm(j.getCm())49                        # get the missing year from the j.getYear is it's exist50                        if (i.getYear() == ""):51                            countList[9] = 1   #countList[9] states whether the year is missing in this entry or not52                            if(j.getYear() != ""):53                              i.setYear(j.getYear())54                        if (i.getSd() == "" and j.getSd() != "" and i.getEd() != "" and compareDates(i.getEd(),j.getEd())==1): #trying to fill the start date,55                        #if missing start date, then need to check that end date is the same,56                        #if both dates are missing, then entry can not be completed57                            i.setSd(j.getSd())58                        if (i.getEd() == "" and j.getEd() != "" and i.getSd() != "" and compareDates(i.getSd(),j.getSd())==1): #trying to fill the end date59                        #if missing end  date, then start date should be checked before completing entry60                            i.setEd(j.getEd())61                        # get the missing rb from the j.getRb is it's exist62                        if (i.getRb() == "" and j.getRb() != "" and ( (i.getEd() != "" and compareDates(i.getEd(),j.getEd())==1)63                            or (i.getSd() != "" and compareDates(i.getSd(),j.getSd())==1) ) ):64                        #before completing the Rb entry, need to check the start or end date, to make sure we are dealing with same entries65                        #note: no two cars with same Cl and same start date and end date are not duplicates66                            i.setRb(j.getRb())67                        if (i.getId() == ""):68                            countList[3] = 1  #countList[3] states wether id is missing in the given entry69                            #if missing and before filling it, need to check that the cl and start date and end date are the same for this person70                            if(j.getId() != "" and i.getCl().upper() == j.getCl().upper() and i.getEd() != "" and compareDates(i.getEd(),j.getEd())==171                                and i.getSd() != "" and compareDates(i.getSd(),j.getSd())==1):72                                i.setId(j.getId())73                    if (i.getName() == ""):74                            countList[2] = 1  #countList[2] states wether name is missing in the given entry75                            #if name is missing, check same id ( as cl is already checked) before filling,smae concept is used for Dob and mobile76                            if(j.getName() != "" and (i.getId()==j.getId())):77                              i.setName(j.getName())78                            # get the missing id from the j.getId if it's exist79                    if (i.getDob() == ""):80                            countList[4] = 1  #countList[4] states wether Dob is missing in the given entry81                            if(j.getDob() != "" and (i.getId()==j.getId())):82                               i.setDob(j.getDob())83                            # get the missing mobile from the j.getMobile if it's exist84                    if (i.getMobile() == ""):85                            countList[5] = 1  #countList[5] states wether id is missing in the given entry86                            if(j.getMobile() != ""  and (i.getId() == j.getId())):87                              i.setMobile(j.getMobile())88        else:89            if (i.getCm() == ""):90                countList[7] = 191            if (i.getYear() == ""):92                countList[9] = 193            if (i.getId() == ""):94                countList[3] = 195            if (i.getName() == ""):96                countList[2] = 197            if (i.getDob() == ""):98                countList[4] = 199            if (i.getMobile() == ""):100                countList[5] = 1101            countList[8] = 1   #countList[8] states wether cl is missing in the given entry102        # now if there are still missing fields then move that element with missing fields into a list called missingList103        if (i.getCl() == "" or i.getId() == "" or i.getName() == "" or i.getDob() == "" or i.getMobile() == "" or i.getCm() == "" or i.getYear() == ""104            or i.getSd() == "" or i.getEd() == "" or i.getRb() == ""):105            if(i.getId() == "" or i.getName() == "" or i.getDob() == "" or i.getMobile() == ""):106               countList[6] = 1 #countList[6] states wether the personal information in this entry can't be recovered107            missingList.append(i)108            for k in range(0,10):109                printList2[k] += countList[k]110        # if the current entry dosn't have any missing fields then mve it into a list called completeList111        else:112            completeList.append(i)113            for k in range(0, 10):114                printList1[k] += countList[k]115    printList2[0] = calcNumOfDuplicates(list)116    #moving all not comlete entries to a new text file called(âCarRentalMissing.txtâ)117    f=open("CarRentalMissing.txt","w")118    for i in missingList:119        f.write(str(i.printFormatedInfo()))120        f.write("\n")121    f.close()122    # moving all comlete entries to a new text file called(âCarRentalCompleted.txtâ123    f=open("CarRentalCompleted.txt","w")124    for i in completeList:125        f.write(str(i.printFormatedInfo()))126        f.write("\n")127    f.close()128    l = removeDuplicate(completeList)129    completeList = l[0]130    printList1[0] = l[1]131    #printSummary(printList1, printList2)132    return [completeList,printList1,printList2]133def printSummary(printList1,printList2):134    #printing summary before recovering, requires printing the summation of printList1[i]+printList2[i] in most cases135    print("Summary of data missing in the database:")136    print("Number of duplicate entries in the database = " , printList2[0] )137    print("Number of entries with wrong date format in the database = " , (printList1[1] + printList2[1]))138    print("Number of entries where names are dropped from the database = " ,(printList1[2] + printList2[2]))139    print("Number of entries where Ids are dropped from the database = " , (printList1[3] + printList2[3]))140    print("Number of entries where dob are dropped from the database = ", (printList1[4] + printList2[4]))141    print("Number of entries where mobile numbers are dropped from the database = " , (printList1[5] + printList2[5]))142    print("Number of entries where personal entry can not be completed = " , printList2[6])143    print("Number of entries where car make is dropped from the database = " , (printList1[7] + printList2[7]))144    print("Number of entries where car Ids are dropped from the database = ", (printList2[8]))145    print("Number of entries where car models (year) are dropped from the database = " , (printList1[9] + printList2[9]))146    print("")147    #printing summary after recovery, requires printing the printList1 elements148    print("Summary of data recovered from the database:")149    print("Number of duplicate entries removed from the new database = " , printList1[0])150    print("Number of entries with wrong date format fixed in the new database = " , printList1[1])151    print("Number of entries with names recovered in the new database = " , printList1[2])152    print("Number of entries with Ids recovered in the new database = " , printList1[3])153    print("Number of entries with dob recovered in the new database = " , printList1[4])154    print("Number of entries with mobile numbers recovered in the new database = " , printList1[5])155    print("Number of entries with car make recovered in the new database = " , printList1[7])156    print("Number of entries with car models (year) recovered in the new database = " , printList1[9])157#This function will encounter the number of duplicates in the whole database158def calcNumOfDuplicates(list):159    # this list will be a flag to help as know wether this entry is encountered as a duplicates or not160    # so we have initailzed it with zeros161    flagList = []162    for i in range(len(list)):163        flagList.append(0)164    # sum variable will contains the number of duplicates in the whole database165    sum = 0166    for i in range(len(list)):167        # if this entry is considered as a duplicate of anther antry or it's cl is not exist or bot the start and end dats are not exist168        # then we can't know if it have a duplicates or not so continue looping169        if(flagList[i]==0 and ( list[i].getCl()=="" or (list[i].getSd()=="" and list[i].getEd()=="") ) ):170            continue171        # this loop will check the duplicate of the current entry starting from the next of this current entry172        for j in range(i+1,len(list)):173            # if this entry is not a duplicate of another entry , and the cars ids are identical and some of the start or end dates174            # are identical and not empty then this entry is a duplicate of the current entry175            if(flagList[j]==0 and list[i].getCl()==list[j].getCl() and176            ((list[i].getSd()!="" and list[i].getSd()==list[j].getSd()) or (list[i].getEd()!="" and list[i].getEd()==list[j].getEd())) ):177                sum += 1178                flagList[j] = 1179    return sum180# function to remove the duplicates from the completed database181def removeDuplicate(list):182    i=0183    sum=0184    while (i < len(list)): # loops through the list185        j=i+1186        # loops through the list starting from the first element in the list after the element obtained from the first loop187        while (j < len(list)):188            #if the ids are idenetical then cheack the other field and if they are all identical then remove the second element189            if (list[i].getCl() == list[j].getCl() and compareDates(list[i].getSd(),list[j].getSd())==1 and compareDates(list[i].getEd(),list[j].getEd())==1 and190                list[i].getName().lower() == list[j].getName().lower() and compareDates(list[j].getDob(),list[i].getDob()) ==1191                 and list[i].getMobile() == list[j].getMobile() and list[i].getCm().lower() == list[j].getCm().lower()192                 and list[i].getYear() == list[j].getYear() and list[i].getRb() == list[j].getRb()):193                    sum += 1194                    list.pop(j)195                    j-=1196            j+=1197        i+=1198    return [list , sum ]199def compareDates(date1, date2):200    # if the date has the format of "/digit/" or "-digit-" it should be modified201    object1 = re.search(r"[-/][0-9]*[-/]", date1, re.M | re.S)202    if object1:203        # the replace string is the monthName element indexed by the digit204        replaceString = monthName[int(object1.group()[1:len(object1.group()) - 1]) - 1]205        date1 = re.sub(r"[-/][0-9]*[-/]", " " + replaceString + " ", date1)206    object2 = re.search(r"[-/][0-9]*[-/]", date2, re.M | re.S)207    if object2:208        # the replace string is the monthName element indexed by the digit209        replaceString = monthName[int(object2.group()[1:len(object2.group()) - 1]) - 1]210        date2 = re.sub(r"[-/][0-9]*[-/]", " " + replaceString + " ", date2)211    date1 = datetime.datetime.strptime(date1,"%d %B %Y")212    # we have created a date object to comaper the dates , because maybe date1 = 1 May 2020 and date2 = 01 May 2020213    # then comparing them as string will yield to be not identical , so using date objects will solve the problem214    date2 = datetime.datetime.strptime(date2,"%d %B %Y")215    if (date1 == date2):216        return 1217    else:...initialize.py
Source:initialize.py  
1'''2This module will read3Created on 19 Jun 20174@author: Amaurys Ãvila Ibarra5'''6from configparser import ConfigParser, ExtendedInterpolation7import os, errno, stat8from shutil import copy29__config_file = "%s/.budeAlaScan.ini" % os.path.expanduser("~")10# Ini file sections11__exe_sect = 'Executables'12__dir_sect = 'Directories'13__names_sect = 'File Names'14__general_sect = 'General'15# Ini file General options.16__gen_max_auto_num_opt = "MaxAutoNumber"17__gen_max_auto_num_val = '20'18# ini file dir options19__dir_wrk_opt = "Work"20__dir_wrk_val = "%s/budeAlaScan" % (os.path.expanduser("~"))21__dir_scan_opt = "Scan"22__dir_scan_val = "alaScan"23__dir_blibs_opt = "BudeLibs"24__dir_blibs_val = "libs"25__dir_rslt_opt = "BudeResults"26__dir_rslt_val = "results"27__dir_src_opt = "PdbSources"28__dir_src_val = "sources"29__dir_seq_opt = "BudeSeqs"30__dir_seq_val = "budeSeqs"31__dir_chi_opt = "Chimera"32__dir_chi_val = "chimeraScripts"33__dir_l_src_opt = "LongPdbSources"34__dir_l_src_val = "${%s}/${%s}" % (__dir_scan_opt, __dir_src_opt)35__dir_l_seq_opt = "LongBudeSeqs"36__dir_l_seq_val = "${%s}/${%s}" % (__dir_scan_opt, __dir_seq_opt)37__dir_l_blibs_opt = "LongBudeLibs"38__dir_l_blibs_val = "${%s}/${%s}" % (__dir_scan_opt, __dir_blibs_opt)39__dir_l_rslt_opt = "LongResults"40__dir_l_rslt_val = "${%s}/${%s}" % (__dir_scan_opt, __dir_rslt_opt)41__dir_l_chi_opt = "LongChimera"42__dir_l_chi_val = "${%s}/${%s}" % (__dir_scan_opt, __dir_chi_opt)43__dir_cpp_opt = "CppCode"44__dir_cpp_val = "cppCode"45__dir_bude_opt = "BUDE"46__dir_bude_val = "${%s}/%s/%s/bin" % (__dir_cpp_opt, "BUDE-1.2.9", "build")47__dir_getsd_opt = "GetSD"48__dir_getsd_val = "${%s}/%s" % (__dir_cpp_opt, "getSD")49__dir_colsd_opt = "ColourBySD"50__dir_colsd_val = "${%s}/%s" % (__dir_cpp_opt, "colourBySD")51__dir_msrc_opt = "MutationSources"52__dir_mrslt_opt = "mut_rslt"53# Ini file executable options54__exe_bude_opt = "BUDE"55__exe_bude_val = "budeScan"56__exe_bseq_opt = "BudeSeq"57__exe_bseq_val = "bude_sequence"58__exe_colsd_opt = "ColouBySD"59__exe_colsd_val = "colourBySD"60__exe_getsd_opt = "GetSD"61__exe_getsd_val = "getSD"62__exe_fbude_opt = "FullBude"63__exe_fbude_val = "${%s:%s}/${%s}" % (__dir_sect, __dir_bude_opt, __exe_bude_opt)64__exe_fbseq_opt = "FullBseq"65__exe_fbseq_val = "${%s:%s}/${%s}" % (__dir_sect, __dir_bude_opt, __exe_bseq_opt)66__exe_fcolsd_opt = "FullColourSD"67__exe_fcolsd_val = "${%s:%s}/${%s}" % (__dir_sect, __dir_colsd_opt, __exe_colsd_opt)68__exe_fgetsd_opt = "FullGetSD"69__exe_fgetsd_val = "${%s:%s}/${%s}" % (__dir_sect, __dir_getsd_opt, __exe_getsd_opt)70# Ini file names options71__names_b_bmc_opt = "BudeBMC"72__names_b_bmc_val = "budeAlaScan.bemc"73__names_b_ctrl_opt = "BudeCtrl"74__names_b_ctrl_val = "alaScan.bctl"75__names_b_gen_zero_opt = "BudeGenZero"76__names_b_gen_zero_val = "zeroGeneration.bzgn"77__names_b_ff_opt = "BudeForcefield"78__names_b_ff_val = "forcefield.bhff"79__names_b_transf_opt = "BudeTransformations"80__names_b_transf_val = "transformations.bltr"81__names_b_rot_choice_opt = "BudeRotamerChoice"82__names_b_rot_choice_val = "rotamer_choice.brch"83__names_b_rot_lib_opt = "BudeRotamerLibrary"84__names_b_rot_lib_val = "rotamer_library.brot"85__names_ligs_list_opt = "LigandsList"86__names_ligs_list_val = "myLigands.list"87__names_rcpts_list_opt = "ReceptorsList"88__names_rcpts_list_val = "myReceptors.list"89__names_rslt_lig_list_opt = "LigandResultsList"90__names_rslt_lig_list_val = "resultsLigands.list"91__names_rslt_rcpt_list_opt = "ReceptorResultsList"92__names_rslt_rcpt_list_val = "resultsReceptors.list"93__names_lig_sd_opt = "LigandsAvgSD"94__names_lig_sd_val = "ligandsAvgSD.bals"95__names_rcpt_sd_opt = "ReceptorsAvgSD"96__names_rcpt_sd_val = "receptorsAvgSD.bals"97__config_sections = {98    __general_sect:99     {100        __gen_max_auto_num_opt: __gen_max_auto_num_val101     }102    ,103    __exe_sect:104     {105        __exe_bude_opt: __exe_bude_val,106        __exe_bseq_opt: __exe_bseq_val,107        __exe_colsd_opt: __exe_colsd_val,108        __exe_getsd_opt: __exe_getsd_val,109        __exe_fbude_opt: __exe_fbude_val,110        __exe_fbseq_opt: __exe_fbseq_val,111        __exe_fcolsd_opt: __exe_fcolsd_val,112        __exe_fgetsd_opt: __exe_fgetsd_val113     }114    ,115    __dir_sect:116     {117        __dir_wrk_opt: __dir_wrk_val,118        __dir_scan_opt: __dir_scan_val,119        __dir_blibs_opt: __dir_blibs_val,120        __dir_rslt_opt: __dir_rslt_val,121        __dir_src_opt: __dir_src_val,122        __dir_seq_opt: __dir_seq_val,123        __dir_chi_opt: __dir_chi_val,124        __dir_l_src_opt: __dir_l_src_val,125        __dir_l_seq_opt: __dir_l_seq_val,126        __dir_l_blibs_opt: __dir_l_blibs_val,127        __dir_l_rslt_opt: __dir_l_rslt_val,128        __dir_l_chi_opt: __dir_l_chi_val,129        __dir_cpp_opt: __dir_cpp_val,130        __dir_bude_opt: __dir_bude_val,131        __dir_getsd_opt: __dir_getsd_val,132        __dir_colsd_opt: __dir_colsd_val133     }134     ,135    __names_sect:136     {137        __names_b_bmc_opt: __names_b_bmc_val,138        __names_b_ctrl_opt: __names_b_ctrl_val,139        __names_b_gen_zero_opt: __names_b_gen_zero_val,140        __names_b_ff_opt: __names_b_ff_val,141        __names_b_transf_opt: __names_b_transf_val,142        __names_b_rot_choice_opt: __names_b_rot_choice_val,143        __names_b_rot_lib_opt: __names_b_rot_lib_val,144        __names_ligs_list_opt: __names_ligs_list_val,145        __names_rcpts_list_opt: __names_rcpts_list_val,146        __names_rslt_lig_list_opt: __names_rslt_lig_list_val,147        __names_rslt_rcpt_list_opt: __names_rslt_rcpt_list_val,148        __names_lig_sd_opt: __names_lig_sd_val,149        __names_rcpt_sd_opt: __names_rcpt_sd_val150     }151    }152def __create_cfg():153    '''154    Create configuration by adding all sections and options to it.155    '''156    my_cfg = ConfigParser(interpolation=ExtendedInterpolation())157    my_cfg.optionxform = str158    for a_section in __config_sections:159        my_cfg.add_section(a_section)160        for an_option in __config_sections[a_section]:161            my_cfg.set(a_section, an_option, __config_sections[a_section][an_option])162    return my_cfg163def __read_cfg():164    '''165    Read config file, add missing configuration parameters and update166    config file if any section or option was added. 167    '''168    my_cfg = ConfigParser(interpolation=ExtendedInterpolation())169    my_cfg.optionxform = str170    my_cfg.read(__config_file, encoding='utf-8')171    if __did_add_missing_conf(my_cfg):172        copy2(__config_file, (__config_file + ".backup"))173        cfg = open(__config_file, 'w')174        my_cfg.write(cfg)175        cfg.close()176    return my_cfg177def __did_add_missing_conf(my_cfg):178    '''179    Add missing section or option and return true if any change is made.180    '''181    addition_was_made = False182    for a_section in __config_sections:183        if not my_cfg.has_section(a_section):184            my_cfg.add_section(a_section)185            addition_was_made = True186        for an_option in __config_sections[a_section]:187            if not my_cfg.has_option(a_section, an_option):188                my_cfg.set(a_section, an_option, __config_sections[a_section][an_option])189                addition_was_made = True190    return addition_was_made191def create_configuration():192    '''193    Creates configuration or reads it from file.194    '''195    try:196        flags = os.O_EXCL | os.O_WRONLY | os.O_CREAT197        mode = stat.S_IREAD | stat.S_IWRITE | stat.S_IRGRP | stat.S_IROTH198        ini_file = os.open(__config_file, flags, mode)199        os.close(ini_file)200    except OSError as e:201        if e.errno == errno.EEXIST:202            my_config = __read_cfg()203        else:204            raise205    else:206        cfg = open(__config_file, 'w')207        my_config = __create_cfg()208        my_config.write(cfg)209        cfg.close()...delete.py
Source:delete.py  
1import argparse2import time3import requests4def getSD(SDtoken, urlpart):5    url = 'https://api.serverdensity.io{}'.format(urlpart)6    r = requests.get(url, params={'token': SDtoken})7    j = r.json()8    time.sleep(0.1)9    return j10def delete(sdid, SDtoken, urlpart):11    url = 'https://api.serverdensity.io{0}/{sdid}'.format(urlpart, sdid=sdid)12    r = requests.delete(url, params={'token': SDtoken})13    time.sleep(0.1)14    return r.status_code15def delete_list(items, SDtoken, urlpart):16    for item in items:17        if '@' in str(item.get('login')):18            delete(item['_id'], SDtoken, urlpart)19            print "Item with id: {} has been deleted".format(item['_id'])20        else:21            print "Saving users that don't have an email as username"22if __name__ == '__main__':23    parser = argparse.ArgumentParser()24    parser.add_argument("SDtoken",25                        help="the api token you get from Server Density")26    args = parser.parse_args()27    SDtoken = args.SDtoken28    users = getSD(SDtoken, '/users/users')29    devices = getSD(SDtoken, '/inventory/devices')30    services = getSD(SDtoken, '/inventory/services')31    tags = getSD(SDtoken, '/inventory/tags')32    notifications = getSD(SDtoken, '/notifications/recipients')33    delete_list(users, SDtoken, '/users/users')34    delete_list(devices, SDtoken, '/inventory/devices')35    delete_list(services, SDtoken, '/inventory/services')36    delete_list(tags, SDtoken, '/inventory/tags')...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
