Best Python code snippet using autotest_python
after_analysis2.py
Source:after_analysis2.py  
...38        for row in csvReader:39            record = Record(*row)40            listOfRecords.append(record)41        return listOfRecords42def record_summary(listOfRecords):43    """44    description:45    args:46    return:47    """48    summaryRecords = defaultdict()49    count = 050    age = defaultdict(int)51    adt = 052    material = defaultdict(int)53    for record in listOfRecords:54        try:55            year = record.year56            county = record.countyCode57            yearReconstructed = record.yearReconstructed58            deck = record.deck59            adt = record.averageDailyTraffic60            structType = record.structureType61        except:62            pass63    return listOfRecords64def to_csv(output, filename):65    """66    description:67    args:68    return:69    """70    outputNew = list()71    #output = [item._asdict() for item in output]72    for item in output:73        try:74            outputNew.append(item._asdict())75        except:76            outputNew.append(None)77        output = outputNew78        fieldnames = ['year',79                      'stateCode',80                      'structureNumber',81                      'countyCode',82                      'yearBuilt',83                      'averageDailyTraffic',84                      'deck',85                      'yearReconstructed',86                      'avgDailyTruckTraffic',87                      'material',88                      'structureType'89                     ]90        with open(filename, 'w') as csvFile:91            csvWriter = csv.DictWriter(csvFile, delimiter=',', fieldnames=fieldnames)92            csvWriter.writeheader()93            for row in output:94                if row == None:95                    #NoneDict = dict(zip(fieldnames, [None]*len(fieldnames)))96                    #csvWriter.writerow(NoneDict)97                    pass98                else:99                    csvWriter.writerow(row)100def main():101    path = '../../../../data/nbi/'102    os.chdir(path)103    rfBridges = 'bridgesRf.csv'104    rfNBridges = 'bridgesRfNegative.csv'105    flBridges = 'bridgesFl.csv'106    flNBridges = 'bridgesFlNegative.csv'107    ##False Positive and false negatives108    bothFalsePositive = 'bFP.csv'109    bothFalseNegative = 'bFN.csv'110    bothTruePositive ='bTP.csv'111    bothTrueNegative ='bTN.csv'112    nbiFile = 'nebraska1992-2019.csv'113    # Read structure Number114    rfList = read_structure_numbers(rfBridges)115    rfNList = read_structure_numbers(rfNBridges)116    flList = read_structure_numbers(flBridges)117    flNList = read_structure_numbers(flNBridges)118    # read structure of false positive and negative119    bFNList = read_structure_numbers(bothFalseNegative)120    bFPList = read_structure_numbers(bothFalsePositive)121    bTPList = read_structure_numbers(bothTruePositive)122    bTNList = read_structure_numbers(bothTrueNegative)123    # read nbi records124    nbiList = read_nbi_records(nbiFile)125    # gather structure number126    structNumbers =  list()127    for nbiRecord in nbiList:128        structNumber = nbiRecord.structureNumber129        structNumbers.append(structNumber)130    # create dictionary of structure numbers131    nbiDict = defaultdict()132    for structNumber, nbiRecord in zip(structNumbers, nbiList):133        nbiDict[structNumber] = nbiRecord134    rfBridgeRecords = list()135    rfNBridgeRecords = list()136    flowBridgeRecords = list()137    flowNBridgeRecords = list()138    bFNRecords = list()139    bFPRecords = list()140    bTNRecords = list()141    bTPRecords = list()142    for structNum in rfList:143        rfBridgeRecords.append(nbiDict.get(structNum))144    for structNum in rfNList:145        rfNBridgeRecords.append(nbiDict.get(structNum))146    for structNum in flList:147        flowBridgeRecords.append(nbiDict.get(structNum))148    for structNum in flNList:149        flowNBridgeRecords.append(nbiDict.get(structNum))150    # False Positive and False Negative151    for structNum in bFNList:152        bFNRecords.append(nbiDict.get(structNum))153    for structNum in bFPList:154        bFPRecords.append(nbiDict.get(structNum))155    for structNum in bTPList:156        bTPRecords.append(nbiDict.get(structNum))157    for structNum in bTNList:158        bTNRecords.append(nbiDict.get(structNum))159    # Average random forest age, adt, adtt, year of resconstruction160    outputRf = record_summary(rfBridgeRecords)161    to_csv(outputRf, 'TrueRfFalseFl.csv')162    outputRfN = record_summary(rfNBridgeRecords)163    to_csv(outputRfN, 'TrueRfNFalseFlN.csv')164    outputFlow = record_summary(flowBridgeRecords)165    to_csv(outputFlow, 'TrueFlFalseRf.csv')166    outputFlowN = record_summary(flowNBridgeRecords)167    to_csv(outputFlowN, 'TrueFlNFalseRfN.csv')168    outputbFN = record_summary(bFNRecords)169    to_csv(outputbFN, 'bFNRecords.csv')170    outputbFP = record_summary(bFPRecords)171    to_csv(outputbFP, 'bFPRecords.csv')172    outputbTP = record_summary(bTPRecords)173    to_csv(outputbTP, 'bTPRecords.csv')174    outputbTN = record_summary(bTNRecords)175    to_csv(outputbTN, 'bTNRecords.csv')176if __name__== "__main__":...parse_heartrate_summary_json.py
Source:parse_heartrate_summary_json.py  
1import json2import pandas as pd3HR_SUMMARY_COLUMNS = ("device_id",4                        "local_date_time",5                        "timestamp",6                        "heartrate_daily_restinghr",7                        "heartrate_daily_caloriesoutofrange",8                        "heartrate_daily_caloriesfatburn",9                        "heartrate_daily_caloriescardio",10                        "heartrate_daily_caloriespeak")11def parseHeartrateSummaryData(record_summary, device_id, curr_date):12    # API Version X: not sure the exact version13    if "heartRateZones" in record_summary:14        heartrate_zones = record_summary["heartRateZones"]15        d_resting_heartrate = record_summary["value"] if "value" in record_summary else None16    # API VERSION Y: not sure the exact version17    elif "value" in record_summary:18        heartrate_zones = record_summary["value"]["heartRateZones"]19        d_resting_heartrate = record_summary["value"]["restingHeartRate"] if "restingHeartRate" in record_summary["value"] else None20    else:21        ValueError("Heartrate zone are stored in an unkown format, this could mean Fitbit's heartrate API changed")22    23    if "caloriesOut" in heartrate_zones[0]:24        d_calories_outofrange = heartrate_zones[0]["caloriesOut"]25        d_calories_fatburn = heartrate_zones[1]["caloriesOut"]26        d_calories_cardio = heartrate_zones[2]["caloriesOut"]27        d_calories_peak = heartrate_zones[3]["caloriesOut"]28    else:29        d_calories_outofrange, d_calories_fatburn, d_calories_cardio, d_calories_peak = None, None, None, None30    31    row_summary = (device_id,32                    curr_date,33                    0,34                    d_resting_heartrate,35                    d_calories_outofrange,36                    d_calories_fatburn,37                    d_calories_cardio,38                    d_calories_peak)39    return row_summary40def parseHeartrateData(heartrate_data):41    if heartrate_data.empty:42        return pd.DataFrame(columns=HR_SUMMARY_COLUMNS)43    device_id = heartrate_data["device_id"].iloc[0]44    records_summary = []45    # Parse JSON into individual records46    for record in heartrate_data.json_fitbit_column:47        record = json.loads(record)  # Parse text into JSON48        if "activities-heart" in record:49            curr_date = record["activities-heart"][0]["dateTime"] + " 00:00:00"50            record_summary = record["activities-heart"][0]51            row_summary = parseHeartrateSummaryData(record_summary, device_id, curr_date)52            records_summary.append(row_summary)53    parsed_data = pd.DataFrame(data=records_summary, columns=HR_SUMMARY_COLUMNS)54    return parsed_data55    56def main(json_raw, stream_parameters):57    parsed_data = parseHeartrateData(json_raw)...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!!
