How to use safeformat method in Pytest

Best Python code snippet using pytest

tables.py

Source:tables.py Github

copy

Full Screen

1#!/usr/bin/python2# -*- coding: utf-8 -*-3from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle4from reportlab.platypus import Paragraph5from reportlab.lib.enums import TA_CENTER6import copy7import pandas as pd8import pdb9import numbers10import re11style = getSampleStyleSheet()12whiteParaStyle = ParagraphStyle('whiteParaStyle',parent=style['BodyText'],textColor="white",alignment=TA_CENTER)13greyParaStyle = ParagraphStyle('greyParaStyle',parent=style['BodyText'],textColor="#443e42")14greyCenterParaStyle = ParagraphStyle('greyParaStyle',parent=style['BodyText'],textColor="#443e42",alignment=TA_CENTER)15# offCourseStyle = ParagraphStyle('offCourseStyle',parent=style['BodyText'],textColor="white",alignment=TA_CENTER,backColor="#d83110")16# progressStyle = ParagraphStyle('progressStyle',parent=style['BodyText'],textColor="#443e42",alignment=TA_CENTER,backColor="#f39000")17# onCourseStyle = ParagraphStyle('onCourseStyle',parent=style['BodyText'],textColor="#443e42",alignment=TA_CENTER,backColor="#d8da00")18offCourseStyle = ParagraphStyle('offCourseStyle',parent=style['BodyText'],textColor="#d83110",alignment=TA_CENTER)19progressStyle = ParagraphStyle('progressStyle',parent=style['BodyText'],textColor="#f39000",alignment=TA_CENTER)20onCourseStyle = ParagraphStyle('onCourseStyle',parent=style['BodyText'],textColor="#d8da00",alignment=TA_CENTER)21def condStyle(progress):22 if progress=="On course":23 return onCourseStyle24 elif progress=="No progress or worsening":25 return offCourseStyle26 elif progress=="Some progress":27 return progressStyle28 elif progress=="Off course":29 return offCourseStyle30 else:31 return greyCenterParaStyle32 33#Read a CSV to make this data?34dataDictionary = {"Mozambique":{}}35dataDictionary["Mozambique"]["country"] = "Mozambique"36dataDictionary["Mozambique"]["table1"] = [["Gini index score*",Paragraph("Gini index rank**",style=whiteParaStyle),"Year"],[51,125,2011]]37dataDictionary["Mozambique"]["table2"] = [38 ["Population (thousands)",format(12428,",d"),2015]39 ,["Under-5 population (thousands)",format(1935,",d"),2015]40 ,["Urban (%)",format(20,",d"),2015]41 ,[">65 years (%)",format(5,",d"),2015]42 ]43dataDictionary["Mozambique"]["table3"] = [44 ["Number of children under 5 affected (thousands)","",""]45 ,[Paragraph("Stunting<super>1</super>",style=greyParaStyle),format(733,",d"),2015]46 ,[Paragraph("Wasting<super>1</super>",style=greyParaStyle),format(43,",d"),2015]47 ,[Paragraph("Overweight<super>1</super>",style=greyParaStyle),format(149,",d"),2015]48 ,["% of children under 5 affected","",""]49 ,[Paragraph("Wasting<super>1</super>",style=greyParaStyle),format(2,"d"),2015]50 ,[Paragraph("Severe wasting<super>1</super>",style=greyParaStyle),format(1,"d"),2015]51 ,[Paragraph("Overweight<super>1</super>",style=greyParaStyle),format(8,"d"),2015]52 ,[Paragraph("Low birth weight<super>2</super>",style=greyParaStyle),format(7,"d"),2015]53 ]54dataDictionary["Mozambique"]["table4"] = [55 [Paragraph("Adolescent overweight<super>1</super>",style=greyParaStyle),"NA","NA"]56 ,[Paragraph("Adolescent obesity<super>1</super>",style=greyParaStyle),"NA","NA"]57 ,[Paragraph("Women of reproductive age, thinness<super>2</super>",style=greyParaStyle),format(5,"d"),2010]58 ,[Paragraph("Women of reproductive age, short stature<super>2</super>",style=greyParaStyle),format(2,"d"),2010]59]60dataDictionary["Mozambique"]["table5"] = [61 [Paragraph("Women of reproductive age with anaemia<super>1</super>",style=greyParaStyle),"",""]62 ,["Total population affected (thousands of people)",format(467,",d"),2011]63 ,["Total population affected (%)",format(17,"d"),2011]64 ,[Paragraph(u"Vitamin A deficiency in children 6\u201359 months old (%)<super>2</super>",style=greyParaStyle),format(39,"d"),2013]65 ,[Paragraph(u"Population classification of iodine nutrition (age group 5\u201319 years old)<super>3</super>",style=greyParaStyle),Paragraph("Risk of iodine-induced hyperthyroidism (IIH) within 5-10 years following introduction of iodized salt in susceptible groups)",style=greyParaStyle),1996]66]67dataDictionary["Mozambique"]["table6"] = [68 [69 Paragraph("<b>Under-5 stunting</b>",style=whiteParaStyle)70 ,Paragraph("<b>Under-5 wasting</b>",style=whiteParaStyle)71 ,Paragraph("<b>Under-5 overweight</b>",style=whiteParaStyle)72 ,Paragraph("<b>WRA anaemia</b>",style=whiteParaStyle)73 ,Paragraph("<b>EBF</b>",style=whiteParaStyle)74 ]75 ,["Off course, some progress","On course","Off course, no progress","Off course","On course"]76]77dataDictionary["Mozambique"]["table6a"] = [78 [79 Paragraph("<b>Adult female obesity</b>",style=whiteParaStyle)80 ,Paragraph("<b>Adult male obesity</b>",style=whiteParaStyle)81 ,Paragraph("<b>Adult female diabetes</b>",style=whiteParaStyle)82 ,Paragraph("<b>Adult male diabetes</b>",style=whiteParaStyle)83 ]84 ,["Off course, some progress","On course","Off course, no progress","Off course"]85]86dataDictionary["Mozambique"]["table7"] = [87 [Paragraph("Severe acute malnutrition, geographic coverage<super>1</super>",style=greyParaStyle),"9","2012"]88 ,[Paragraph("Vitamin A supplementation, full coverage<super>2</super>",style=greyParaStyle),"65","2013"]89 ,[Paragraph("Children under 5 with diarrhoea receiving ORS<super>2</super>",style=greyParaStyle),"44","2011"]90 ,[Paragraph("Immunisation coverage, DTP3<super>3</super>",style=greyParaStyle),"78","2016"]91 ,[Paragraph("Iodised salt consumption<super>2</super>",style=greyParaStyle),"87","2006"]92]93dataDictionary["Mozambique"]["table8"] = [94 ["Minimum acceptable diet","6","2011"]95 ,["Minimum dietary diversity","13","2011"]96]97dataDictionary["Mozambique"]["table9"] = [98 [Paragraph("Early childbearing: births by age 18 (%)<super>1</super>",style=greyParaStyle),"33","2011"]99 ,[Paragraph("Gender Inequality Index (score*)<super>2</super>",style=greyParaStyle),"0.529","2013"]100 ,[Paragraph("Gender Inequality Index (country rank)<super>2</super>",style=greyParaStyle),"155","2013"]101]102dataDictionary["Mozambique"]["table10"] = [103 ["Physicians","0.117","2005"]104 ,["Nurses and midwives","1.306","2005"]105 ,["Community health workers","0.188","2005"]106]107dataDictionary["Mozambique"]["table11"] = [108 [Paragraph("National implementation of the International Code of Marketing of Breast-milk Substitutes<super>1</super>",style=greyParaStyle),"Law","2014"]109 ,[Paragraph("Extent of constitutional right to food<super>2</super>",style=greyParaStyle),"High","2003"]110 ,[Paragraph("Maternity Protection Convention 183<super>3</super>",style=greyParaStyle),"No","2011"]111 ,[Paragraph("Wheat fortification legislation<super>4</super>",style=greyParaStyle),"Mandatory","2015"]112 ,[Paragraph("Undernutrition mentioned in national development plans and economic growth strategies<super>5</super>",style=greyParaStyle),"Rank: 39/126","2010-2015"]113 ,[Paragraph("Overnutrition mentioned in national development plans and economic growth strategies<super>5</super>",style=greyParaStyle),"Rank: 57/116","2010-2015"]114]115dataDictionary["Mozambique"]["table12"] = [116 [Paragraph("All major NCDs",style=greyParaStyle),Paragraph("Available, partially implemented",style=greyParaStyle),"2010"]117]118dataDictionary["Afghanistan"] = copy.deepcopy(dataDictionary["Mozambique"])119dataDictionary["Albania"] = copy.deepcopy(dataDictionary["Mozambique"])120dataDictionary["Algeria"] = copy.deepcopy(dataDictionary["Mozambique"])121dataDictionary["Andorra"] = copy.deepcopy(dataDictionary["Mozambique"])122dataDictionary["Angola"] = copy.deepcopy(dataDictionary["Mozambique"])123dataDictionary["Antigua and Barbuda"] = copy.deepcopy(dataDictionary["Mozambique"])124dataDictionary["Argentina"] = copy.deepcopy(dataDictionary["Mozambique"])125dataDictionary["Armenia"] = copy.deepcopy(dataDictionary["Mozambique"])126dataDictionary["Australia"] = copy.deepcopy(dataDictionary["Mozambique"])127dataDictionary["Austria"] = copy.deepcopy(dataDictionary["Mozambique"])128dataDictionary["Azerbaijan"] = copy.deepcopy(dataDictionary["Mozambique"])129dataDictionary["Bahamas"] = copy.deepcopy(dataDictionary["Mozambique"])130dataDictionary["Bahrain"] = copy.deepcopy(dataDictionary["Mozambique"])131dataDictionary["Bangladesh"] = copy.deepcopy(dataDictionary["Mozambique"])132dataDictionary["Barbados"] = copy.deepcopy(dataDictionary["Mozambique"])133dataDictionary["Belarus"] = copy.deepcopy(dataDictionary["Mozambique"])134dataDictionary["Belgium"] = copy.deepcopy(dataDictionary["Mozambique"])135dataDictionary["Belize"] = copy.deepcopy(dataDictionary["Mozambique"])136dataDictionary["Benin"] = copy.deepcopy(dataDictionary["Mozambique"])137dataDictionary["Bhutan"] = copy.deepcopy(dataDictionary["Mozambique"])138dataDictionary["Bolivia"] = copy.deepcopy(dataDictionary["Mozambique"])139dataDictionary["Bosnia and Herzegovina"] = copy.deepcopy(dataDictionary["Mozambique"])140dataDictionary["Botswana"] = copy.deepcopy(dataDictionary["Mozambique"])141dataDictionary["Brazil"] = copy.deepcopy(dataDictionary["Mozambique"])142dataDictionary["Brunei Darussalam"] = copy.deepcopy(dataDictionary["Mozambique"])143dataDictionary["Bulgaria"] = copy.deepcopy(dataDictionary["Mozambique"])144dataDictionary["Burkina Faso"] = copy.deepcopy(dataDictionary["Mozambique"])145dataDictionary["Burundi"] = copy.deepcopy(dataDictionary["Mozambique"])146dataDictionary["Cambodia"] = copy.deepcopy(dataDictionary["Mozambique"])147dataDictionary["Cameroon"] = copy.deepcopy(dataDictionary["Mozambique"])148dataDictionary["Canada"] = copy.deepcopy(dataDictionary["Mozambique"])149dataDictionary["Cape Verde"] = copy.deepcopy(dataDictionary["Mozambique"])150dataDictionary["Central African Republic"] = copy.deepcopy(dataDictionary["Mozambique"])151dataDictionary["Chad"] = copy.deepcopy(dataDictionary["Mozambique"])152dataDictionary["Chile"] = copy.deepcopy(dataDictionary["Mozambique"])153dataDictionary["China"] = copy.deepcopy(dataDictionary["Mozambique"])154dataDictionary["Colombia"] = copy.deepcopy(dataDictionary["Mozambique"])155dataDictionary["Comoros"] = copy.deepcopy(dataDictionary["Mozambique"])156dataDictionary["Congo (Republic of the)"] = copy.deepcopy(dataDictionary["Mozambique"])157dataDictionary["Costa Rica"] = copy.deepcopy(dataDictionary["Mozambique"])158dataDictionary["Cote d'Ivoire"] = copy.deepcopy(dataDictionary["Mozambique"])159dataDictionary["Croatia"] = copy.deepcopy(dataDictionary["Mozambique"])160dataDictionary["Cuba"] = copy.deepcopy(dataDictionary["Mozambique"])161dataDictionary["Cyprus"] = copy.deepcopy(dataDictionary["Mozambique"])162dataDictionary["Czech Republic"] = copy.deepcopy(dataDictionary["Mozambique"])163dataDictionary["Democratic People's Republic of Korea"] = copy.deepcopy(dataDictionary["Mozambique"])164dataDictionary["Democratic Republic of the Congo"] = copy.deepcopy(dataDictionary["Mozambique"])165dataDictionary["Denmark"] = copy.deepcopy(dataDictionary["Mozambique"])166dataDictionary["Djibouti"] = copy.deepcopy(dataDictionary["Mozambique"])167dataDictionary["Dominica"] = copy.deepcopy(dataDictionary["Mozambique"])168dataDictionary["Dominican Republic"] = copy.deepcopy(dataDictionary["Mozambique"])169dataDictionary["Ecuador"] = copy.deepcopy(dataDictionary["Mozambique"])170dataDictionary["Egypt"] = copy.deepcopy(dataDictionary["Mozambique"])171dataDictionary["El Salvador"] = copy.deepcopy(dataDictionary["Mozambique"])172dataDictionary["Equatorial Guinea"] = copy.deepcopy(dataDictionary["Mozambique"])173dataDictionary["Eritrea"] = copy.deepcopy(dataDictionary["Mozambique"])174dataDictionary["Estonia"] = copy.deepcopy(dataDictionary["Mozambique"])175dataDictionary["Ethiopia"] = copy.deepcopy(dataDictionary["Mozambique"])176dataDictionary["Fiji"] = copy.deepcopy(dataDictionary["Mozambique"])177dataDictionary["Finland"] = copy.deepcopy(dataDictionary["Mozambique"])178dataDictionary["France"] = copy.deepcopy(dataDictionary["Mozambique"])179dataDictionary["Gabon"] = copy.deepcopy(dataDictionary["Mozambique"])180dataDictionary["Gambia"] = copy.deepcopy(dataDictionary["Mozambique"])181dataDictionary["Georgia"] = copy.deepcopy(dataDictionary["Mozambique"])182dataDictionary["Germany"] = copy.deepcopy(dataDictionary["Mozambique"])183dataDictionary["Ghana"] = copy.deepcopy(dataDictionary["Mozambique"])184dataDictionary["Greece"] = copy.deepcopy(dataDictionary["Mozambique"])185dataDictionary["Grenada"] = copy.deepcopy(dataDictionary["Mozambique"])186dataDictionary["Guatemala"] = copy.deepcopy(dataDictionary["Mozambique"])187dataDictionary["Guinea"] = copy.deepcopy(dataDictionary["Mozambique"])188dataDictionary["Guinea-Bissau"] = copy.deepcopy(dataDictionary["Mozambique"])189dataDictionary["Guyana"] = copy.deepcopy(dataDictionary["Mozambique"])190dataDictionary["Haiti"] = copy.deepcopy(dataDictionary["Mozambique"])191dataDictionary["Honduras"] = copy.deepcopy(dataDictionary["Mozambique"])192dataDictionary["Hungary"] = copy.deepcopy(dataDictionary["Mozambique"])193dataDictionary["Iceland"] = copy.deepcopy(dataDictionary["Mozambique"])194dataDictionary["India"] = copy.deepcopy(dataDictionary["Mozambique"])195dataDictionary["Indonesia"] = copy.deepcopy(dataDictionary["Mozambique"])196dataDictionary["Iran"] = copy.deepcopy(dataDictionary["Mozambique"])197dataDictionary["Iraq"] = copy.deepcopy(dataDictionary["Mozambique"])198dataDictionary["Ireland"] = copy.deepcopy(dataDictionary["Mozambique"])199dataDictionary["Israel"] = copy.deepcopy(dataDictionary["Mozambique"])200dataDictionary["Italy"] = copy.deepcopy(dataDictionary["Mozambique"])201dataDictionary["Jamaica"] = copy.deepcopy(dataDictionary["Mozambique"])202dataDictionary["Japan"] = copy.deepcopy(dataDictionary["Mozambique"])203dataDictionary["Jordan"] = copy.deepcopy(dataDictionary["Mozambique"])204dataDictionary["Kazakhstan"] = copy.deepcopy(dataDictionary["Mozambique"])205dataDictionary["Kenya"] = copy.deepcopy(dataDictionary["Mozambique"])206dataDictionary["Kiribati"] = copy.deepcopy(dataDictionary["Mozambique"])207dataDictionary["Kuwait"] = copy.deepcopy(dataDictionary["Mozambique"])208dataDictionary["Kyrgyzstan"] = copy.deepcopy(dataDictionary["Mozambique"])209dataDictionary["Lao People's Democratic Republic"] = copy.deepcopy(dataDictionary["Mozambique"])210dataDictionary["Latvia"] = copy.deepcopy(dataDictionary["Mozambique"])211dataDictionary["Lebanon"] = copy.deepcopy(dataDictionary["Mozambique"])212dataDictionary["Lesotho"] = copy.deepcopy(dataDictionary["Mozambique"])213dataDictionary["Liberia"] = copy.deepcopy(dataDictionary["Mozambique"])214dataDictionary["Libya"] = copy.deepcopy(dataDictionary["Mozambique"])215dataDictionary["Liechtenstein"] = copy.deepcopy(dataDictionary["Mozambique"])216dataDictionary["Lithuania"] = copy.deepcopy(dataDictionary["Mozambique"])217dataDictionary["Luxembourg"] = copy.deepcopy(dataDictionary["Mozambique"])218dataDictionary["Madagascar"] = copy.deepcopy(dataDictionary["Mozambique"])219dataDictionary["Malawi"] = copy.deepcopy(dataDictionary["Mozambique"])220dataDictionary["Malaysia"] = copy.deepcopy(dataDictionary["Mozambique"])221dataDictionary["Maldives"] = copy.deepcopy(dataDictionary["Mozambique"])222dataDictionary["Mali"] = copy.deepcopy(dataDictionary["Mozambique"])223dataDictionary["Malta"] = copy.deepcopy(dataDictionary["Mozambique"])224dataDictionary["Marshall Islands"] = copy.deepcopy(dataDictionary["Mozambique"])225dataDictionary["Mauritania"] = copy.deepcopy(dataDictionary["Mozambique"])226dataDictionary["Mauritius"] = copy.deepcopy(dataDictionary["Mozambique"])227dataDictionary["Mexico"] = copy.deepcopy(dataDictionary["Mozambique"])228dataDictionary["Micronesia (Federated States of)"] = copy.deepcopy(dataDictionary["Mozambique"])229dataDictionary["Monaco"] = copy.deepcopy(dataDictionary["Mozambique"])230dataDictionary["Mongolia"] = copy.deepcopy(dataDictionary["Mozambique"])231dataDictionary["Montenegro"] = copy.deepcopy(dataDictionary["Mozambique"])232dataDictionary["Morocco"] = copy.deepcopy(dataDictionary["Mozambique"])233# dataDictionary["Mozambique"] = copy.deepcopy(dataDictionary["Mozambique"])234dataDictionary["Myanmar"] = copy.deepcopy(dataDictionary["Mozambique"])235dataDictionary["Namibia"] = copy.deepcopy(dataDictionary["Mozambique"])236dataDictionary["Nauru"] = copy.deepcopy(dataDictionary["Mozambique"])237dataDictionary["Nepal"] = copy.deepcopy(dataDictionary["Mozambique"])238dataDictionary["Netherlands"] = copy.deepcopy(dataDictionary["Mozambique"])239dataDictionary["New Zealand"] = copy.deepcopy(dataDictionary["Mozambique"])240dataDictionary["Nicaragua"] = copy.deepcopy(dataDictionary["Mozambique"])241dataDictionary["Niger"] = copy.deepcopy(dataDictionary["Mozambique"])242dataDictionary["Nigeria"] = copy.deepcopy(dataDictionary["Mozambique"])243dataDictionary["Norway"] = copy.deepcopy(dataDictionary["Mozambique"])244dataDictionary["Oman"] = copy.deepcopy(dataDictionary["Mozambique"])245dataDictionary["Pakistan"] = copy.deepcopy(dataDictionary["Mozambique"])246dataDictionary["Palau"] = copy.deepcopy(dataDictionary["Mozambique"])247dataDictionary["Panama"] = copy.deepcopy(dataDictionary["Mozambique"])248dataDictionary["Papua New Guinea"] = copy.deepcopy(dataDictionary["Mozambique"])249dataDictionary["Paraguay"] = copy.deepcopy(dataDictionary["Mozambique"])250dataDictionary["Peru"] = copy.deepcopy(dataDictionary["Mozambique"])251dataDictionary["Philippines"] = copy.deepcopy(dataDictionary["Mozambique"])252dataDictionary["Poland"] = copy.deepcopy(dataDictionary["Mozambique"])253dataDictionary["Portugal"] = copy.deepcopy(dataDictionary["Mozambique"])254dataDictionary["Qatar"] = copy.deepcopy(dataDictionary["Mozambique"])255dataDictionary["Republic of Korea"] = copy.deepcopy(dataDictionary["Mozambique"])256dataDictionary["Republic of Moldova"] = copy.deepcopy(dataDictionary["Mozambique"])257dataDictionary["Romania"] = copy.deepcopy(dataDictionary["Mozambique"])258dataDictionary["Russian Federation"] = copy.deepcopy(dataDictionary["Mozambique"])259dataDictionary["Rwanda"] = copy.deepcopy(dataDictionary["Mozambique"])260dataDictionary["Saint Kitts and Nevis"] = copy.deepcopy(dataDictionary["Mozambique"])261dataDictionary["Saint Lucia"] = copy.deepcopy(dataDictionary["Mozambique"])262dataDictionary["Saint Vincent and the Grenadines"] = copy.deepcopy(dataDictionary["Mozambique"])263dataDictionary["Samoa"] = copy.deepcopy(dataDictionary["Mozambique"])264dataDictionary["San Marino"] = copy.deepcopy(dataDictionary["Mozambique"])265dataDictionary["Sao Tome and Principe"] = copy.deepcopy(dataDictionary["Mozambique"])266dataDictionary["Saudi Arabia"] = copy.deepcopy(dataDictionary["Mozambique"])267dataDictionary["Senegal"] = copy.deepcopy(dataDictionary["Mozambique"])268dataDictionary["Serbia"] = copy.deepcopy(dataDictionary["Mozambique"])269dataDictionary["Seychelles"] = copy.deepcopy(dataDictionary["Mozambique"])270dataDictionary["Sierra Leone"] = copy.deepcopy(dataDictionary["Mozambique"])271dataDictionary["Singapore"] = copy.deepcopy(dataDictionary["Mozambique"])272dataDictionary["Slovakia"] = copy.deepcopy(dataDictionary["Mozambique"])273dataDictionary["Slovenia"] = copy.deepcopy(dataDictionary["Mozambique"])274dataDictionary["Solomon Islands"] = copy.deepcopy(dataDictionary["Mozambique"])275dataDictionary["Somalia"] = copy.deepcopy(dataDictionary["Mozambique"])276dataDictionary["South Africa"] = copy.deepcopy(dataDictionary["Mozambique"])277dataDictionary["South Sudan"] = copy.deepcopy(dataDictionary["Mozambique"])278dataDictionary["Spain"] = copy.deepcopy(dataDictionary["Mozambique"])279dataDictionary["Sri Lanka"] = copy.deepcopy(dataDictionary["Mozambique"])280dataDictionary["Sudan"] = copy.deepcopy(dataDictionary["Mozambique"])281dataDictionary["Suriname"] = copy.deepcopy(dataDictionary["Mozambique"])282dataDictionary["Swaziland"] = copy.deepcopy(dataDictionary["Mozambique"])283dataDictionary["Sweden"] = copy.deepcopy(dataDictionary["Mozambique"])284dataDictionary["Switzerland"] = copy.deepcopy(dataDictionary["Mozambique"])285dataDictionary["Syria"] = copy.deepcopy(dataDictionary["Mozambique"])286dataDictionary["Tajikistan"] = copy.deepcopy(dataDictionary["Mozambique"])287dataDictionary["Thailand"] = copy.deepcopy(dataDictionary["Mozambique"])288dataDictionary["The former Yugoslav Republic of Macedonia"] = copy.deepcopy(dataDictionary["Mozambique"])289dataDictionary["Timor-Leste"] = copy.deepcopy(dataDictionary["Mozambique"])290dataDictionary["Togo"] = copy.deepcopy(dataDictionary["Mozambique"])291dataDictionary["Tonga"] = copy.deepcopy(dataDictionary["Mozambique"])292dataDictionary["Trinidad and Tobago"] = copy.deepcopy(dataDictionary["Mozambique"])293dataDictionary["Tunisia"] = copy.deepcopy(dataDictionary["Mozambique"])294dataDictionary["Turkey"] = copy.deepcopy(dataDictionary["Mozambique"])295dataDictionary["Turkmenistan"] = copy.deepcopy(dataDictionary["Mozambique"])296dataDictionary["Tuvalu"] = copy.deepcopy(dataDictionary["Mozambique"])297dataDictionary["Uganda"] = copy.deepcopy(dataDictionary["Mozambique"])298dataDictionary["Ukraine"] = copy.deepcopy(dataDictionary["Mozambique"])299dataDictionary["United Arab Emirates"] = copy.deepcopy(dataDictionary["Mozambique"])300dataDictionary["United Kingdom"] = copy.deepcopy(dataDictionary["Mozambique"])301dataDictionary["United Republic of Tanzania"] = copy.deepcopy(dataDictionary["Mozambique"])302dataDictionary["United States of America"] = copy.deepcopy(dataDictionary["Mozambique"])303dataDictionary["Uruguay"] = copy.deepcopy(dataDictionary["Mozambique"])304dataDictionary["Uzbekistan"] = copy.deepcopy(dataDictionary["Mozambique"])305dataDictionary["Vanuatu"] = copy.deepcopy(dataDictionary["Mozambique"])306dataDictionary["Venezuela"] = copy.deepcopy(dataDictionary["Mozambique"])307dataDictionary["Viet Nam"] = copy.deepcopy(dataDictionary["Mozambique"])308dataDictionary["Yemen"] = copy.deepcopy(dataDictionary["Mozambique"])309dataDictionary["Zambia"] = copy.deepcopy(dataDictionary["Mozambique"])310dataDictionary["Zimbabwe"] = copy.deepcopy(dataDictionary["Mozambique"])311def replaceDash(x):312 x = str(x)313 y = re.sub(r"((?:^|[^{])\d+)-(\d+[^}])",u"\\1\u2013\\2", x)314 return y315missingVals = [" ",".","","Insufficient data to make assessment"]316def safeFormat(x,commas=False,precision=0):317 if pd.isnull(x):318 return "NA"319 elif x in missingVals:320 return "NA"321 else:322 if not isinstance(x,numbers.Number):323 return replaceDash(x)324 if precision == 0:325 x = int(round(x,precision))326 else:327 x = round(x,precision)328 if commas:329 return format(x,",")330 else:331 return x332dat = pd.read_csv("data.csv")333for country in dataDictionary.keys():334 row = dat.loc[(dat.country==country)].iloc[0]335 dataDictionary[country]["country"] = country336 337 # dataDictionary["Mozambique"]["table1"] = [["Gini index score*",Paragraph("Gini index rank<super>†</super>",style=whiteParaStyle),"Year"],[51,125,2011]]338 dataDictionary[country]["table1"][1] = [safeFormat(row["value_gini"]),safeFormat(row["rank_gini"]),safeFormat(row["year_gini"])]339 # dataDictionary["Mozambique"]["table2"] = [340 # ["Population (000)",format(12428,",d"),2015]341 # ,["Under-5 population (000)",format(1935,",d"),2015]342 # ,["Urban (%)",format(20,",d"),2015]343 # ,[">65 years (%)",format(5,",d"),2015]344 # ]345 dataDictionary[country]["table2"][0][1] = safeFormat(row["totalpop2017"],True)346 dataDictionary[country]["table2"][0][2] = safeFormat(2017)347 dataDictionary[country]["table2"][1][1] = safeFormat(row["under5pop"],True)348 dataDictionary[country]["table2"][1][2] = safeFormat(2017)349 dataDictionary[country]["table2"][2][1] = safeFormat(row["urbanpop"])350 dataDictionary[country]["table2"][2][2] = safeFormat(2017)351 dataDictionary[country]["table2"][3][1] = safeFormat(row["over65pop"],True)352 dataDictionary[country]["table2"][3][2] = safeFormat(2017)353 # dataDictionary["Mozambique"]["table3"] = [354 # ["Number of children under 5 affected (000)","",""]355 # ,[Paragraph("Stunting<super>a</super>",style=greyParaStyle),format(733,",d"),2015]356 # ,[Paragraph("Wasting<super>a</super>",style=greyParaStyle),format(43,",d"),2015]357 # ,[Paragraph("Overweight<super>a</super>",style=greyParaStyle),format(149,",d"),2015]358 # ,["Percentage of children under 5 affected","",""]359 # ,[Paragraph("Wasting<super>a</super>",style=greyParaStyle),format(2,"d"),2015]360 # ,[Paragraph("Severe wasting<super>a</super>",style=greyParaStyle),format(1,"d"),2015]361 # ,[Paragraph("Overweight<super>a</super>",style=greyParaStyle),format(8,"d"),2015]362 # ,[Paragraph("Low birth weight<super>b</super>",style=greyParaStyle),format(7,"d"),2015]363 # ]364 dataDictionary[country]["table3"][1][1] = safeFormat(row["number_stunting_current"],True)365 dataDictionary[country]["table3"][1][2] = safeFormat(row["year_stunting_current"])366 dataDictionary[country]["table3"][2][1] = safeFormat(row["number_wasting"],True)367 dataDictionary[country]["table3"][2][2] = safeFormat(row["year_wasting"])368 dataDictionary[country]["table3"][3][1] = safeFormat(row["number_u5overweight"],True)369 dataDictionary[country]["table3"][3][2] = safeFormat(row["year_u5overweight"])370 dataDictionary[country]["table3"][5][1] = safeFormat(row["prev_wasting"])371 dataDictionary[country]["table3"][5][2] = safeFormat(row["year_wasting"])372 dataDictionary[country]["table3"][6][1] = safeFormat(row["prev_sev_wasting"])373 dataDictionary[country]["table3"][6][2] = safeFormat(row["year_sev_wasting"])374 dataDictionary[country]["table3"][7][1] = safeFormat(row["prev_u5overweight"])375 dataDictionary[country]["table3"][7][2] = safeFormat(row["year_u5overweight"])376 dataDictionary[country]["table3"][8][1] = safeFormat(row["LBW"])377 dataDictionary[country]["table3"][8][2] = safeFormat(row["year_lbw"])378 # dataDictionary["Mozambique"]["table4"] = [379 # [Paragraph("Adolescent overweight<super>a</super>",style=greyParaStyle),"NA","NA"]380 # ,[Paragraph("Adolescent obesity<super>a</super>",style=greyParaStyle),"NA","NA"]381 # ,[Paragraph("Women of reproductive age, thinness<super>b</super>",style=greyParaStyle),format(5,"d"),2010]382 # ,[Paragraph("Women of reproductive age, short stature<super>b</super>",style=greyParaStyle),format(2,"d"),2010]383 # ]384 dataDictionary[country]["table4"][0][1] = safeFormat(row["AdolOW"])385 dataDictionary[country]["table4"][0][2] = safeFormat(row["year_adolOWOB"])386 dataDictionary[country]["table4"][1][1] = safeFormat(row["AdolOB"])387 dataDictionary[country]["table4"][1][2] = safeFormat(row["year_adolOWOB"])388 dataDictionary[country]["table4"][2][1] = safeFormat(row["prev_BMI185"])389 dataDictionary[country]["table4"][2][2] = safeFormat(row["year_BMI185"])390 dataDictionary[country]["table4"][3][1] = safeFormat(row["prev_height145"])391 dataDictionary[country]["table4"][3][2] = safeFormat(row["year_height145"])392 # dataDictionary["Mozambique"]["table5"] = [393 # [Paragraph("Women of reproductive age with anemia<super>a</super>",style=greyParaStyle),"",""]394 # ,["Total population affected (000)",format(467,",d"),2011]395 # ,["Total population affected (%)",format(17,"d"),2011]396 # ,[Paragraph("Vitamin A deficiency in children 6-59 months old (%)<super>b</super>",style=greyParaStyle),format(39,"d"),2013]397 # ,[Paragraph("Population classification of iodine nutrition (age group 5-19)<super>c</super>",style=greyParaStyle),Paragraph("Risk of iodine-induced hyperthyroidism (IIH) within 5-10 years following introduction of iodized salt in susceptible groups)",style=greyParaStyle),1996]398 # ]399 dataDictionary[country]["table5"][1][1] = safeFormat(row["WRAanaemia_NUMBER"],True)400 dataDictionary[country]["table5"][1][2] = safeFormat(row["year_WRAanaemia"])401 dataDictionary[country]["table5"][2][1] = safeFormat(row["WRAanaemia_RATE"])402 dataDictionary[country]["table5"][2][2] = safeFormat(row["year_WRAanaemia"])403 dataDictionary[country]["table5"][3][1] = safeFormat(row["prevalence_vita"])404 dataDictionary[country]["table5"][3][2] = safeFormat(row["year_vitA_def"])405 dataDictionary[country]["table5"][4][1] = Paragraph(safeFormat(row["Class_IodineNutrition"]),style=greyCenterParaStyle)406 dataDictionary[country]["table5"][4][2] = safeFormat(row["year_IodineNutrition"])407 # dataDictionary["Mozambique"]["table6"] = [408 # [409 # Paragraph("<b>Under-5 stunting, 2015<super>a</super></b>",style=whiteParaStyle)410 # ,Paragraph("<b>Under-5 wasting, 2015<super>b</super></b>",style=whiteParaStyle)411 # ,Paragraph("<b>Under-5 overweight, 2015<super>a</super></b>",style=whiteParaStyle)412 # ,Paragraph("<b>WRA Anemia, 2011<super>b</super></b>",style=whiteParaStyle)413 # ,Paragraph("<b>EBF, 2014-2015<super>a</super></b>",style=whiteParaStyle)414 # ]415 # ,["Off course, some progress","On course","Off course, no progress","Off course","On course"]416 # ]417 # dataDictionary[country]["table6"][0] = [418 # Paragraph("<b>Under-5 stunting, %s<super>1</super></b>" % safeFormat(row["year_stunting_current"]),style=whiteParaStyle)419 # ,Paragraph("<b>Under-5 wasting, %s<super>2</super></b>" % safeFormat(row["year_wasting"]),style=whiteParaStyle)420 # ,Paragraph("<b>Under-5 overweight, %s<super>1</super></b>" % safeFormat(row["year_u5overweight"]),style=whiteParaStyle)421 # ,Paragraph("<b>WRA anaemia, %s<super>2</super></b>" % safeFormat(row["year_WRAanaemia"]),style=whiteParaStyle)422 # ,Paragraph("<b>EBF, %s<super>1</super></b>" % safeFormat(row["year_ebf_current"]),style=whiteParaStyle)423 # ]424 dataDictionary[country]["table6"][1] = [425 Paragraph(safeFormat(row["stunting_progress"]),style=condStyle(row["stunting_progress"]))426 ,Paragraph(safeFormat(row["wasting_progress"]),style=condStyle(row["wasting_progress"]))427 ,Paragraph(safeFormat(row["u5overweight_progress"]),style=condStyle(row["u5overweight_progress"]))428 ,Paragraph(safeFormat(row["progress_WRAanaemia"]),style=condStyle(row["progress_WRAanaemia"]))429 ,Paragraph(safeFormat(row["EBF_progress"]),style=condStyle(row["EBF_progress"]))430 ]431 # dataDictionary["Mozambique"]["table6a"] = [432 # [433 # Paragraph("<b>Adult female obesity, 2015<super>a</super></b>",style=whiteParaStyle)434 # ,Paragraph("<b>Adult male obesity, 2015<super>a</super></b>",style=whiteParaStyle)435 # ,Paragraph("<b>Adult female diabetes, 2015<super>a</super></b>",style=whiteParaStyle)436 # ,Paragraph("<b>Adult male diabetes, 2015<super>a</super></b>",style=whiteParaStyle)437 # ]438 # ,["Off course, some progress","On course","Off course, no progress","Off course"]439 # ]440 # dataDictionary[country]["table6a"][0] = [441 # Paragraph("<b>Adult female obesity, %s<super>1</super></b>" % safeFormat(2017),style=whiteParaStyle)442 # ,Paragraph("<b>Adult male obesity, %s<super>1</super></b>" % safeFormat(2017),style=whiteParaStyle)443 # ,Paragraph("<b>Adult female diabetes, %s<super>1</super></b>" % safeFormat(2017),style=whiteParaStyle)444 # ,Paragraph("<b>Adult male diabetes, %s<super>1</super></b>" % safeFormat(2017),style=whiteParaStyle)445 # ]446 dataDictionary[country]["table6a"][1] = [447 Paragraph(safeFormat(row["ob_female_progress"]),style=condStyle(row["ob_female_progress"]))448 ,Paragraph(safeFormat(row["ob_male_progress"]),style=condStyle(row["ob_male_progress"]))449 ,Paragraph(safeFormat(row["dm_female_progress"]),style=condStyle(row["dm_female_progress"]))450 ,Paragraph(safeFormat(row["dm_male_progress"]),style=condStyle(row["dm_male_progress"]))451 ]452 # dataDictionary["Mozambique"]["table7"] = [453 # [Paragraph("Severe acute malnutrition, geographic coverage<super>a</super>",style=greyParaStyle),"9","2012"]454 # ,[Paragraph("Vitamin A supplementation, full coverage<super>b</super>",style=greyParaStyle),"65","2013"]455 # ,[Paragraph("Children under 5 with diarrhea receiving ORS<super>b</super>",style=greyParaStyle),"44","2011"]456 # ,[Paragraph("Immunization coverage, DTP3<super>b</super>",style=greyParaStyle),"78","2013"]457 # ,[Paragraph("Iodized salt consumption<super>b</super>",style=greyParaStyle),"87","2006"]458 # ]459 dataDictionary[country]["table7"][0][1] = safeFormat(row["SAMcoverage_rate"])460 dataDictionary[country]["table7"][0][2] = safeFormat(row["year_SAM"])461 dataDictionary[country]["table7"][1][1] = safeFormat(row["vitA_supp"])462 dataDictionary[country]["table7"][1][2] = safeFormat(row["year_vitA_supp"])463 dataDictionary[country]["table7"][2][1] = safeFormat(row["ors"])464 dataDictionary[country]["table7"][2][2] = safeFormat(row["yr_ors"])465 dataDictionary[country]["table7"][3][1] = safeFormat(row["DTP3"])466 dataDictionary[country]["table7"][3][2] = safeFormat(row["year_DTP"])467 dataDictionary[country]["table7"][4][1] = safeFormat(row["householdconsumingsalt"])468 dataDictionary[country]["table7"][4][2] = safeFormat(row["year_Iodised"])469 # dataDictionary["Mozambique"]["table8"] = [470 # ["Minimum acceptable diet","6","2011"]471 # ,["Minimum dietary diversity","13","2011"]472 # ]473 dataDictionary[country]["table8"][0][1] = safeFormat(row["mad"])474 dataDictionary[country]["table8"][0][2] = safeFormat(row["yr_mad"])475 dataDictionary[country]["table8"][1][1] = safeFormat(row["mdd"])476 dataDictionary[country]["table8"][1][2] = safeFormat(row["yr_mdd"])477 # dataDictionary["Mozambique"]["table9"] = [478 # [Paragraph("Early childbearing: births by age 18 (%)<super>a</super>",style=greyParaStyle),"33","2011"]479 # ,[Paragraph("Gender Inequality Index (score*)<super>b</super>",style=greyParaStyle),"0.529","2013"]480 # ,[Paragraph("Gender Inequality Index (country rank)<super>b</super>",style=greyParaStyle),"155","2013"]481 # ]482 dataDictionary[country]["table9"][0][1] = safeFormat(row["earlychild"])483 dataDictionary[country]["table9"][0][2] = safeFormat(row["year_early_child"])484 dataDictionary[country]["table9"][1][1] = safeFormat(row["index_genderinequality"],False,3)485 dataDictionary[country]["table9"][1][2] = safeFormat(row["year_genderinequality"])486 dataDictionary[country]["table9"][2][1] = safeFormat(row["rank_genderinequality"])487 dataDictionary[country]["table9"][2][2] = safeFormat(row["year_genderinequality"])488 # dataDictionary["Mozambique"]["table10"] = [489 # ["Physicians","0.117","2005"]490 # ,["Nurses and midwives","1.306","2005"]491 # ,["Community health workers","0.188","2005"]492 # ]493 dataDictionary[country]["table10"][0][1] = safeFormat(row["valuephysician"],False,3)494 dataDictionary[country]["table10"][0][2] = safeFormat(row["yearphysician"])495 dataDictionary[country]["table10"][1][1] = safeFormat(row["valuenurse"],False,3)496 dataDictionary[country]["table10"][1][2] = safeFormat(row["yearnurse"])497 dataDictionary[country]["table10"][2][1] = safeFormat(row["valuehealthworker"],False,3)498 dataDictionary[country]["table10"][2][2] = safeFormat(row["yearhealthworker"])499 # dataDictionary["Mozambique"]["table11"] = [500 # [Paragraph("National implementation of the International Code of Marketing of Breast-milk Substitutes<super>a</super>",style=greyParaStyle),"Law","2014"]501 # ,[Paragraph("Extent of constitutional right to food<super>b</super>",style=greyParaStyle),"High","2003"]502 # ,[Paragraph("Maternity protection (Convention 183)<super>c</super>",style=greyParaStyle),"No","2011"]503 # ,[Paragraph("Wheat fortification legislation<super>d</super>",style=greyParaStyle),"Mandatory","2015"]504 # ,[Paragraph("Undernutrition mentioned in national development plans and economic growth strategies<super>e</super>",style=greyParaStyle),"Rank: 39/126","2010-2015"]505 # ,[Paragraph("Overnutrition mentioned in national development plans and economic growth strategies<super>e</super>",style=greyParaStyle),"Rank: 57/116","2010-2015"]506 # ]507 dataDictionary[country]["table11"][0][1] = Paragraph(safeFormat(row["Code_breastfeeding"]),style=greyCenterParaStyle)508 dataDictionary[country]["table11"][0][2] = safeFormat(row["year_code_bf"])509 dataDictionary[country]["table11"][1][1] = Paragraph(safeFormat(row["RTF_level1"]),style=greyCenterParaStyle)510 dataDictionary[country]["table11"][1][2] = safeFormat(row["year_RTF"])511 dataDictionary[country]["table11"][2][1] = Paragraph(safeFormat(row["cat_maternityprotection"]),style=greyCenterParaStyle)512 dataDictionary[country]["table11"][2][2] = safeFormat(row["year_maternityprotection"])513 dataDictionary[country]["table11"][3][1] = Paragraph(safeFormat(row["Fortification"]),style=greyCenterParaStyle)514 dataDictionary[country]["table11"][3][2] = safeFormat(row["year_FFI"])515 dataDictionary[country]["table11"][4][1] = safeFormat(row["undernutritionrank_1to126"])516 dataDictionary[country]["table11"][4][2] = safeFormat(row["year_policyrank"])517 dataDictionary[country]["table11"][5][1] = safeFormat(row["overnutritionrank_1to116"])518 dataDictionary[country]["table11"][5][2] = safeFormat(row["year_policyrank"])519 # dataDictionary["Mozambique"]["table12"] = [520 # ["All major NCDs",Paragraph("Available, partially implemented",style=greyParaStyle),"2010"]521 # ]522 dataDictionary[country]["table12"][0][1] = Paragraph(safeFormat(row["ncd_policy"]),style=greyCenterParaStyle)523 dataDictionary[country]["table12"][0][2] = safeFormat(row["year_ncdpolicy"])524tableStyles = {}525tableStyles["table1"] = [526 ('TEXTCOLOR',(0,0),(-1,-1),"white")527 ,('BACKGROUND',(0,0),(2,0),"#7b1059")528 ,('FONTNAME',(0,1),(2,1),"Arial-Bold")529 # ,('FONTNAME',(0,1),(2,1),"Arial")530 ,('BACKGROUND',(0,1),(2,1),"#c79ec5")531 # ,('GRID',(0,0),(-1,-1),1,"white")532 ,('LINEAFTER',(0,0),(1,1),1,"white")533 ,('ALIGN',(0,0),(-1,-1),"CENTER")534 ,('VALIGN',(0,0),(-1,-1),"MIDDLE")535 ]536tableStyles["table2"] = [537 ('BACKGROUND',(0,1),(-1,1),"#fef5e7")538 ,('BACKGROUND',(0,3),(-1,3),"#fef5e7")539 ,('ALIGN',(0,0),(0,-1),"LEFT")540 ,('ALIGN',(1,0),(2,-1),"CENTER")541 ,('VALIGN',(0,0),(-1,-1),"MIDDLE")542 ,('BOX',(1,0),(1,-1),1,"#f79c2a")543 ,('LINEABOVE',(0,0),(-1,0),1,"#f79c2a")544 ,('LINEBELOW',(0,-1),(-1,-1),1,"#f79c2a")545 ,('TEXTCOLOR',(0,0),(-1,-1),"#443e42")546 ]547tableStyles["table3"] = [548 ('BACKGROUND',(0,1),(-1,1),"#fef5e7")549 ,('BACKGROUND',(0,3),(-1,3),"#fef5e7")550 ,('BACKGROUND',(0,5),(-1,5),"#fef5e7")551 ,('BACKGROUND',(0,7),(-1,7),"#fef5e7")552 ,('ALIGN',(0,0),(0,-1),"LEFT")553 ,('ALIGN',(1,0),(2,-1),"CENTER")554 ,('VALIGN',(0,0),(-1,-1),"MIDDLE")555 ,('BOX',(1,1),(1,3),1,"#f79c2a")556 ,('BOX',(1,5),(1,-1),1,"#f79c2a")557 ,('LINEABOVE',(0,0),(-1,0),1,"#f79c2a")558 ,('LINEABOVE',(0,1),(-1,1),1,"#f79c2a")559 ,('LINEABOVE',(0,4),(-1,4),1,"#f79c2a")560 ,('LINEABOVE',(0,5),(-1,5),1,"#f79c2a")561 ,('LINEBELOW',(0,-1),(-1,-1),1,"#f79c2a")562 ,('SPAN',(0,0),(-1,0))563 # ,('FONTNAME',(0,0),(-1,0),"Arial-Bold")564 ,('SPAN',(0,4),(-1,4))565 # ,('FONTNAME',(0,4),(-1,4),"Arial-Bold")566 ,('TEXTCOLOR',(0,0),(-1,-1),"#443e42")567 ]568tableStyles["table4"] = tableStyles["table2"]569tableStyles["table5"] = [570 ('LINEABOVE',(0,0),(-1,0),1,"#f79c2a")571 ,('LINEABOVE',(0,1),(-1,1),1,"#f79c2a")572 ,('LINEABOVE',(0,3),(-1,3),1,"#f79c2a")573 ,('LINEBELOW',(0,4),(-1,4),1,"#f79c2a")574 ,('SPAN',(0,0),(-1,0))575 ,('LINEAFTER',(0,1),(1,2),.5,"#fbcd99")576 ,('LINEBELOW',(0,1),(-1,1),.5,"#fbcd99")577 ,('LINEAFTER',(0,3),(1,-1),1,"#fbcd99")578 ,('LINEABOVE',(0,-1),(-1,-1),1,"#fbcd99")579 ,('VALIGN',(0,0),(-1,-1),"MIDDLE")580 ,('ALIGN',(0,0),(0,-1),"LEFT")581 ,('ALIGN',(1,0),(2,-1),"CENTER")582 ,('TEXTCOLOR',(0,0),(-1,-1),"#443e42")583]584tableStyles["table6"] = [585 ('TEXTCOLOR',(0,0),(-1,0),"white")586 # ,('BACKGROUND',(0,0),(-1,0),"#204d5e")587 # ,('BACKGROUND',(0,1),(-1,1),"white")588 # ,('GRID',(0,0),(-1,-1),1,"#386170")589 ,('ALIGN',(0,0),(-1,-1),"CENTER")590 ,('VALIGN',(0,0),(-1,-1),"MIDDLE")591 ,('TEXTCOLOR',(0,1),(-1,-1),"#443e42")592 ]593tableStyles["table6a"] = tableStyles["table6"]594tableStyles["table7"] = tableStyles["table2"]595tableStyles["table8"] = [596 ('BACKGROUND',(0,1),(-1,1),"#fef5e7")597 ,('ALIGN',(0,0),(0,-1),"LEFT")598 ,('ALIGN',(1,0),(2,-1),"CENTER")599 ,('VALIGN',(0,0),(-1,-1),"MIDDLE")600 ,('BOX',(1,0),(1,-1),1,"#f79c2a")601 ,('LINEABOVE',(0,0),(-1,0),1,"#f79c2a")602 ,('LINEBELOW',(0,-1),(-1,-1),1,"#f79c2a")603 ,('TEXTCOLOR',(0,0),(-1,-1),"#443e42")604 ]605tableStyles["table9"] = tableStyles["table8"]606tableStyles["table10"] = tableStyles["table8"]607tableStyles["table11"] = [608 ('BACKGROUND',(0,1),(-1,1),"#fef5e7")609 ,('BACKGROUND',(0,3),(-1,3),"#fef5e7")610 ,('BACKGROUND',(0,5),(-1,5),"#fef5e7")611 ,('ALIGN',(0,0),(0,-1),"LEFT")612 ,('ALIGN',(1,0),(2,-1),"CENTER")613 ,('VALIGN',(0,0),(-1,-1),"MIDDLE")614 ,('BOX',(1,0),(1,-1),1,"#f79c2a")615 ,('LINEABOVE',(0,0),(-1,0),1,"#f79c2a")616 ,('LINEBELOW',(0,-1),(-1,-1),1,"#f79c2a")617 ,('TEXTCOLOR',(0,0),(-1,-1),"#443e42")618 ]...

Full Screen

Full Screen

tables_world.py

Source:tables_world.py Github

copy

Full Screen

1#!/usr/bin/python2# -*- coding: utf-8 -*-3from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle4from reportlab.platypus import Paragraph5from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT6import copy7import pandas as pd8import numbers9import re10from reportlab.pdfbase import pdfmetrics11from reportlab.pdfbase.ttfonts import TTFont12from reportlab.lib.fonts import addMapping13import pdb14dark_orange = "#DE5D09"15orange = "#F39000"16light_orange = "#FCC97A"17dark_aqua = "#007495"18aqua = "#93CAC9"19aqua_light = "#B2D8D7"20aqua_extra_light = "#D1E7E5"21dark_grey = "#475C6D"22grey = "#A0ADBB"23light_grey = "#CFD9E5"24pdfmetrics.registerFont(TTFont('Averta', 'fonts/Averta-Regular.ttf'))25pdfmetrics.registerFont(TTFont('Averta-Bold', 'fonts/Averta-Bold.ttf'))26pdfmetrics.registerFont(TTFont('Averta-Italic', 'fonts/Averta-RegularItalic.ttf'))27addMapping('Averta', 0, 0, 'Averta')28addMapping('Averta', 0, 1, 'Averta-Italic')29addMapping('Averta', 1, 0, 'Averta-Bold')30style = getSampleStyleSheet()31dark_greyParaBold = ParagraphStyle('dark_greyParaBold', parent=style['BodyText'], textColor=dark_grey, alignment=TA_LEFT, fontName="Averta-Bold")32dark_greyParaBoldCenter = ParagraphStyle('dark_greyParaBold', parent=style['BodyText'], textColor=dark_grey, alignment=TA_CENTER, fontName="Averta-Bold")33dark_greyParaStyle = ParagraphStyle('dark_greyParaStyle', parent=style['BodyText'], textColor=dark_grey, alignment=TA_LEFT)34dark_greyParaStyleRight = ParagraphStyle('dark_greyParaStyle', parent=style['BodyText'], textColor=dark_grey, alignment=TA_RIGHT)35NACourseStyle = ParagraphStyle('offCourseStyle', parent=style['BodyText'], textColor=grey, alignment=TA_LEFT)36offCourseStyle = ParagraphStyle('offCourseStyle', parent=style['BodyText'], textColor=orange, alignment=TA_LEFT)37progressStyle = ParagraphStyle('progressStyle', parent=style['BodyText'], textColor=aqua, alignment=TA_LEFT)38onCourseStyle = ParagraphStyle('onCourseStyle', parent=style['BodyText'], textColor=dark_aqua, alignment=TA_LEFT)39dataDictionary = {"World": {}}40dataDictionary["World"]["country"] = "World"41dataDictionary["World"]["table1"] = [42 [43 Paragraph("<b>Under-5 stunting</b>", style=dark_greyParaBold),44 Paragraph("<b>Under-5 wasting</b>", style=dark_greyParaBold),45 Paragraph("<b>Under-5 overweight</b>", style=dark_greyParaBold),46 Paragraph("<b>WRA anaemia</b>", style=dark_greyParaBold),47 Paragraph("<b>Exclusive breastfeeding</b>", style=dark_greyParaBold)48 ],49 ["Off course, some progress", "On course", "Off course, no progress", "Off course", "On course"]50]51dataDictionary["World"]["table1a"] = [52 [53 Paragraph("<b>Adult female obesity</b>", style=dark_greyParaBold),54 Paragraph("<b>Adult male obesity</b>", style=dark_greyParaBold),55 Paragraph("<b>Adult female diabetes</b>", style=dark_greyParaBold),56 Paragraph("<b>Adult male diabetes</b>", style=dark_greyParaBold)57 ],58 ["Off course, some progress", "On course", "Off course, no progress", "Off course"]59]60#61# dataDictionary["World"]["table2"] = [62# [Paragraph("Gini index score<super>1</super>", style=dark_greyParaBold), Paragraph("Gini index rank<super>2</super>", style=dark_greyParaBold), "Year"], [51, 125, 2011]63# ]64dataDictionary["World"]["table3"] = [65 ["Population (millions)", format(12428, ",d"), 2015],66 ["Under-5 population (millions)", format(1935, ",d"), 2015],67 ["Rural (%)", format(20, ",d"), 2015],68 ["≥65 years (millions)", format(5, ",d"), 2015],69]70dataDictionary["World"]["table4"] = [71 [Paragraph("Early childbearing: births by age 18 (%)", style=dark_greyParaBold), "33", "2011"]72]73dataDictionary["World"]["table5"] = [74 ["Physicians", "0.117", "2005"],75 ["Nurses and midwives", "1.306", "2005"],76 ["Community health workers", "0.188", "2005"]77]78dataDictionary["World"]["table6"] = [79 [Paragraph("Mandatory legislation for salt iodisation", style=dark_greyParaBold), "Yes"],80 [Paragraph("Sugar-sweetened beverage tax", style=dark_greyParaBold), "Yes"],81 [Paragraph("Food-based dietary guidelines", style=dark_greyParaBold), "Yes"],82 [Paragraph("Multisectoral comprehensive nutrition plan", style=dark_greyParaBold), "Yes"],83]84dataDictionary["World"]["table7"] = [85 [86 Paragraph("Stunting", style=dark_greyParaBoldCenter),87 Paragraph("Anaemia", style=dark_greyParaBoldCenter),88 Paragraph("Low birth weight", style=dark_greyParaBoldCenter),89 Paragraph("Child overweight", style=dark_greyParaBoldCenter),90 Paragraph("Exclusive breastfeeding", style=dark_greyParaBoldCenter),91 Paragraph("Wasting", style=dark_greyParaBoldCenter),92 Paragraph("Salt intake", style=dark_greyParaBoldCenter),93 Paragraph("Overweight adults and adolescents", style=dark_greyParaBoldCenter),94 ],95 ["Yes", "Yes", "No", "Yes", "Yes", "Yes", "Yes", "Yes", "Yes", "Yes"]96]97dataDictionary["World"]["table8"] = [98 [99 Paragraph("<b>Coverage/practice indicator</b>", style=dark_greyParaBold),100 Paragraph("<b>Number of countries with data</b>", style=dark_greyParaBold),101 Paragraph("<b>Minimum %</b>", style=dark_greyParaBold),102 Paragraph("<b>Maximum %</b>", style=dark_greyParaBold),103 Paragraph("<b>Mean %</b>", style=dark_greyParaBold),104 Paragraph("<b>Median % for countries with data</b>", style=dark_greyParaBold),105 ],106 [u"Children 0\u201359 months with diarrhoea who received zinc treatment", "46", "0.1", "50.2", "8.6", "2.8"],107 [u"Children 6\u201359 months who received vitamin A supplements in last 6 months", "58", "4.5", "86.4", "57.0", "60.9"],108 [u"Children 6\u201359 months given iron supplements in past 7 days", "56", "1.3", "45.4", "14.6", "11.6"],109 [Paragraph("Women with a birth in last five years who received iron and folic acid during their most recent pregnancy", style=dark_greyParaStyle), "62", "22.6", "96.6", "74.6", "81.0"],110 ["Household consumption of any iodised salt", "52", "18.0", "99.8", "82.7", "90.9"],111]112dat = pd.read_csv("data_world.csv")113country_names = dat.region.unique()114for country_name in country_names:115 dataDictionary[country_name] = copy.deepcopy(dataDictionary["World"])116def replaceDash(x):117 x = str(x)118 y = re.sub(r"((?:^|[^{])\d+)-(\d+[^}])", u"\\1\u2013\\2", x)119 return y120missingVals = [" ", ".", "", "No data","na","NA"]121def safeFormat(x, commas=False, precision=0, percent=False, divisor=False):122 if pd.isnull(x):123 return "NA"124 elif x in missingVals:125 return "NA"126 else:127 if percent:128 try:129 x = float(x) * 100130 except ValueError:131 return replaceDash(x)132 if divisor:133 try:134 x = float(x) / divisor135 if x < 1:136 precision += 1137 except ValueError:138 return replaceDash(x)139 if not isinstance(x, numbers.Number):140 try:141 x = float(x)142 except ValueError:143 return replaceDash(x)144 if precision == 0:145 x = int(round(x, precision))146 else:147 x = round(x, precision)148 if commas:149 return format(x, ",")150 else:151 return x152def indicator(ctryDat, indicator):153 try:154 return ctryDat.loc[(ctryDat["indicator"] == indicator)].iloc[0]["value"]155 except IndexError:156 return "NA"157def indicator_sum(ctryDat, indicator):158 try:159 return ctryDat.loc[(ctryDat["indicator"] == indicator)].iloc[0]["value.sum"]160 except IndexError:161 return "NA"162def indicator_n(ctryDat, indicator):163 try:164 return ctryDat.loc[(ctryDat["indicator"] == indicator)].iloc[0]["n"]165 except IndexError:166 return "NA"167def indicator_n_max(ctryDat, indicator):168 try:169 row = ctryDat.loc[(ctryDat["indicator"] == indicator)]170 max_year = row["year"].max()171 max_row = row[(row["year"] == max_year)].iloc[0]172 return max_row["n"]173 except IndexError:174 return "NA"175def indicator_n_disagg(ctryDat, indicator, disaggregation):176 try:177 return ctryDat.loc[(ctryDat["indicator"] == indicator) & (ctryDat["disaggregation"] == disaggregation)].iloc[0]["n"]178 except IndexError:179 return "NA"180def indicator_frac(ctryDat, indicator, value):181 try:182 row = ctryDat.loc[(ctryDat["indicator"] == indicator) & (ctryDat["value"] == value)].iloc[0]183 return "{}/{}".format(int(row["n"]), int(row["N"]))184 except IndexError:185 return "NA"186def indicator_disagg(ctryDat, indicator, disagg, disagg_value=None):187 if disagg_value:188 try:189 return ctryDat.loc[(ctryDat["indicator"] == indicator) & (ctryDat["disaggregation"] == disagg) & (ctryDat["disagg.value"] == disagg_value)].iloc[0]["value"]190 except IndexError:191 return "NA"192 else:193 try:194 return ctryDat.loc[(ctryDat["indicator"] == indicator) & (ctryDat["disaggregation"] == disagg)].iloc[0]["value"]195 except IndexError:196 return "NA"197def indicator_disagg_frac(ctryDat, indicator, disagg, value, disagg_value=None):198 if disagg_value:199 try:200 row = ctryDat.loc[(ctryDat["indicator"] == indicator) & (ctryDat["disaggregation"] == disagg) & (ctryDat["disagg.value"] == disagg_value) & (ctryDat["value"] == value)].iloc[0]201 return "{}/{}".format(int(row["n"]), int(row["N"]))202 except IndexError:203 return "NA"204 else:205 try:206 row = ctryDat.loc[(ctryDat["indicator"] == indicator) & (ctryDat["disaggregation"] == disagg) & (ctryDat["value"] == value)].iloc[0]207 return "{}/{}".format(int(row["n"]), int(row["N"]))208 except IndexError:209 return "NA"210def year(ctryDat, indicator):211 try:212 return ctryDat.loc[(ctryDat["indicator"] == indicator)].iloc[0]["year"]213 except IndexError:214 return "NA"215def year_range(ctryDat, indicator):216 try:217 return ctryDat.loc[(ctryDat["indicator"] == indicator)].iloc[0]["year_range"]218 except IndexError:219 return "NA"220for country in dataDictionary.keys():221 ctryDat = dat.loc[(dat.region == country)]222 dataDictionary[country]["country"] = country223 max_n = ctryDat["n"].max()224 if max_n >= 50:225 minimum_n = 10226 elif max_n >= 20:227 minimum_n = 5228 elif max_n > 2:229 minimum_n = 3230 else:231 minimum_n = 2232 summed_vars = [233 "population",234 "u5_pop",235 "65_years",236 "under_5_stunting_track",237 "under_5_wasting_track",238 "under_5_overweight_track",239 "wra_anaemia_track",240 "ebf_track",241 "adult_fem_obesity_track",242 "adult_mal_obesity_track",243 "adult_fem_diabetes_track",244 "adult_mal_diabetes_track",245 "salt_leg",246 "sugar_tax",247 "fbdg",248 "multi_sec",249 "stunting_plan",250 "anaemia_plan",251 "LBW_plan",252 "child_overweight_plan",253 "EBF_plan",254 "wasting_plan",255 "sodium_plan",256 "overweight_adults_adoles_plan",257 ]258 ctryDat_with_n = ctryDat.loc[(ctryDat["n"] >= minimum_n) & (~ctryDat["indicator"].isin(summed_vars))]259 ctryDat_without_n = ctryDat.loc[(pd.isnull(ctryDat["n"])) | (ctryDat["indicator"].isin(summed_vars))]260 ctryDat = pd.concat([ctryDat_with_n, ctryDat_without_n])261 dataDictionary[country]["table1"][1] = [262 Paragraph(safeFormat(indicator_frac(ctryDat, "under_5_stunting_track", "On course"))+" on course", style=offCourseStyle),263 Paragraph(safeFormat(indicator_frac(ctryDat, "under_5_wasting_track", "On course"))+" on course", style=offCourseStyle),264 Paragraph(safeFormat(indicator_frac(ctryDat, "under_5_overweight_track", "On course"))+" on course", style=offCourseStyle),265 Paragraph(safeFormat(indicator_frac(ctryDat, "wra_anaemia_track", "On course"))+" on course", style=offCourseStyle),266 Paragraph(safeFormat(indicator_frac(ctryDat, "ebf_track", "On course"))+" on course", style=offCourseStyle),267 ]268 dataDictionary[country]["table1a"][1] = [269 Paragraph(safeFormat(indicator_frac(ctryDat, "adult_fem_obesity_track", "On course"))+" on course", style=offCourseStyle),270 Paragraph(safeFormat(indicator_frac(ctryDat, "adult_mal_obesity_track", "On course"))+" on course", style=offCourseStyle),271 Paragraph(safeFormat(indicator_frac(ctryDat, "adult_fem_diabetes_track", "On course"))+" on course", style=offCourseStyle),272 Paragraph(safeFormat(indicator_frac(ctryDat, "adult_mal_diabetes_track", "On course"))+" on course", style=offCourseStyle),273 ]274 # dataDictionary[country]["table2"][1] = [275 # safeFormat(indicator(ctryDat, "gini")),276 # safeFormat(indicator(ctryDat, "gini_rank")),277 # safeFormat(year(ctryDat, "gini"))278 # ]279 dataDictionary[country]["table3"][0][1] = safeFormat(indicator_sum(ctryDat, "population"), True, divisor=1000)280 if safeFormat(indicator_sum(ctryDat, "population"), True, divisor=1000) == "0.0":281 dataDictionary[country]["table3"][0][0] = "Population (000)"282 dataDictionary[country]["table3"][0][1] = safeFormat(indicator_sum(ctryDat, "population"), True)283 dataDictionary[country]["table3"][0][2] = safeFormat(year(ctryDat, "population"))284 dataDictionary[country]["table3"][1][1] = safeFormat(indicator_sum(ctryDat, "u5_pop"), True, divisor=1000)285 if safeFormat(indicator_sum(ctryDat, "u5_pop"), True, divisor=1000) == "0.0":286 dataDictionary[country]["table3"][1][0] = "Under-5 population (000)"287 dataDictionary[country]["table3"][1][1] = safeFormat(indicator_sum(ctryDat, "u5_pop"), True)288 dataDictionary[country]["table3"][1][2] = safeFormat(year(ctryDat, "u5_pop"))289 dataDictionary[country]["table3"][2][1] = safeFormat(indicator(ctryDat, "rural_percent"))290 dataDictionary[country]["table3"][2][2] = safeFormat(year(ctryDat, "rural_percent"))291 dataDictionary[country]["table3"][3][1] = safeFormat(indicator_sum(ctryDat, "65_years"), True, divisor=1000)292 if safeFormat(indicator_sum(ctryDat, "65_years"), True, divisor=1000) == "0.0":293 dataDictionary[country]["table3"][3][0] = "≥65 years (000)"294 dataDictionary[country]["table3"][3][1] = safeFormat(indicator_sum(ctryDat, "65_years"), True)295 dataDictionary[country]["table3"][3][2] = safeFormat(year(ctryDat, "65_years"))296 dataDictionary[country]["table3_n1"] = safeFormat(indicator_n(ctryDat, "u5_pop"))297 dataDictionary[country]["table3_n2"] = safeFormat(indicator_n(ctryDat, "rural_percent"))298 dataDictionary[country]["table3_n3"] = safeFormat(indicator_n(ctryDat, "65_years"))299 dataDictionary[country]["table4"][0][1] = safeFormat(indicator(ctryDat, "early_childbearing_prev"))300 dataDictionary[country]["table4"][0][2] = Paragraph(str(safeFormat(year_range(ctryDat, "early_childbearing_prev"))), style=dark_greyParaStyleRight)301 dataDictionary[country]["table4_n"] = safeFormat(indicator_n(ctryDat, "early_childbearing_prev"))302 dataDictionary[country]["table5"][0][1] = safeFormat(indicator(ctryDat, "physicians"), False, 2)303 dataDictionary[country]["table5"][0][2] = Paragraph(str(safeFormat(year_range(ctryDat, "physicians"))), style=dark_greyParaStyleRight)304 dataDictionary[country]["table5"][1][1] = safeFormat(indicator(ctryDat, "nurses_and_midwives"), False, 2)305 dataDictionary[country]["table5"][1][2] = Paragraph(str(safeFormat(year_range(ctryDat, "nurses_and_midwives"))), style=dark_greyParaStyleRight)306 dataDictionary[country]["table5"][2][1] = safeFormat(indicator(ctryDat, "community_health_workers"), False, 2)307 dataDictionary[country]["table5"][2][2] = Paragraph(str(safeFormat(year_range(ctryDat, "community_health_workers"))), style=dark_greyParaStyleRight)308 dataDictionary[country]["table5_n"] = safeFormat(indicator_n(ctryDat, "physicians"))309 dataDictionary[country]["table6"][0][1] = safeFormat(indicator_frac(ctryDat, "salt_leg", "Yes"))310 dataDictionary[country]["table6"][1][1] = safeFormat(indicator_frac(ctryDat, "sugar_tax", "Yes"))311 dataDictionary[country]["table6"][2][1] = safeFormat(indicator_frac(ctryDat, "fbdg", "Yes"))312 dataDictionary[country]["table6"][3][1] = safeFormat(indicator_frac(ctryDat, "multi_sec", "Yes"))313 dataDictionary[country]["table7"][1] = [314 safeFormat(indicator_frac(ctryDat, "stunting_plan", "Yes")),315 safeFormat(indicator_frac(ctryDat, "anaemia_plan", "Yes")),316 safeFormat(indicator_frac(ctryDat, "LBW_plan", "Yes")),317 safeFormat(indicator_frac(ctryDat, "child_overweight_plan", "Yes")),318 safeFormat(indicator_frac(ctryDat, "EBF_plan", "Yes")),319 safeFormat(indicator_frac(ctryDat, "wasting_plan", "Yes")),320 safeFormat(indicator_frac(ctryDat, "sodium_plan", "Yes")),321 safeFormat(indicator_frac(ctryDat, "overweight_adults_adoles_plan", "Yes")),322 ]323 # dataDictionary[country]["table8"][1][1] = safeFormat(indicator_disagg(ctryDat, "diarrhea_zinc", "all"))324 #325 # dataDictionary[country]["table8"][2][1] = safeFormat(indicator_disagg(ctryDat, "vit_a", "gender", "Both"))326 # dataDictionary[country]["table8"][2][2] = safeFormat(indicator_disagg(ctryDat, "vit_a", "gender", "Boys"))327 # dataDictionary[country]["table8"][2][3] = safeFormat(indicator_disagg(ctryDat, "vit_a", "gender", "Girls"))328 #329 # dataDictionary[country]["table8"][3][1] = safeFormat(indicator_disagg(ctryDat, "iron_supp", "gender", "Both"))330 # dataDictionary[country]["table8"][3][2] = safeFormat(indicator_disagg(ctryDat, "iron_supp", "gender", "Boys"))331 # dataDictionary[country]["table8"][3][3] = safeFormat(indicator_disagg(ctryDat, "iron_supp", "gender", "Girls"))332 #333 # dataDictionary[country]["table8"][4][1] = safeFormat(indicator_disagg(ctryDat, "iron_and_folic", "all"))334 # dataDictionary[country]["table8"][4][3] = safeFormat(indicator_disagg(ctryDat, "iron_and_folic", "all"))335 #336 # dataDictionary[country]["table8"][5][1] = safeFormat(indicator_disagg(ctryDat, "iodised_salt", "all"))337 dataDictionary[country]["pov_percent_n"] = safeFormat(indicator_n(ctryDat, "190_percent"))338 n_indicators = [339 "190_percent",340 "GDP_capita_PPP",341 "fruit_veg_availability",342 "female_secondary_enroll_net",343 "basic_water",344 "basic_sanitation",345 "agriculture_expenditure",346 "coexistence",347 "adolescent_underweight",348 "adolescent_overweight",349 "adolescent_obesity",350 "adult_diabetes",351 "adult_overweight",352 "adult_obesity",353 "adult_blood_pressure",354 "adult_anemia",355 "adult_sodium",356 "Calcium",357 "diarrhea_zinc",358 "vit_a",359 "iron_supp",360 "iron_and_folic",361 "iodised_salt"362 ]363 for n_indicator in n_indicators:364 dataDictionary[country][n_indicator+"_n"] = safeFormat(indicator_n(ctryDat, n_indicator))365 # dataDictionary[country]["table8"][1][4] = safeFormat(indicator_n(ctryDat, "diarrhea_zinc"))366 # dataDictionary[country]["table8"][2][4] = safeFormat(indicator_n(ctryDat, "vit_a"))367 # dataDictionary[country]["table8"][3][4] = safeFormat(indicator_n(ctryDat, "iron_supp"))368 # dataDictionary[country]["table8"][4][4] = safeFormat(indicator_n(ctryDat, "iron_and_folic"))369 # dataDictionary[country]["table8"][5][4] = safeFormat(indicator_n(ctryDat, "iodised_salt"))370 n_indicators_disagg = [371 ("stunting_percent", "gender"),372 ("overweight_percent", "gender"),373 ("wasting_percent", "income"),374 ("stunting_percent", "income"),375 ("overweight_percent", "income"),376 ("wasting_percent", "location"),377 ("stunting_percent", "location"),378 ("overweight_percent", "location"),379 ]380 for n_indicator, disagg in n_indicators_disagg:381 dataDictionary[country][n_indicator+"_"+disagg+"_n"] = safeFormat(indicator_n_disagg(ctryDat, n_indicator, disagg))382 c_feeding_n_max = 0383 c_feeding_inds = [384 "continued_breastfeeding_2yr",385 "continued_breastfeeding_1yr",386 "minimum_accept_diet",387 "minimum_diet_diversity",388 "minimum_meal",389 "solid_foods",390 "exclusive_breastfeeding",391 "early_initiation"392 ]393 for ind in c_feeding_inds:394 this_n = indicator_n_max(ctryDat, ind)395 try:396 if this_n > c_feeding_n_max:397 c_feeding_n_max = this_n398 except TypeError:399 pass400 dataDictionary[country]["c_feeding_n"] = safeFormat(c_feeding_n_max)401generic_style = [402 ('TEXTCOLOR', (0, 0), (-1, -1), dark_grey),403 ('BACKGROUND', (0, 0), (-1, -1), "white"),404 ('LINEABOVE', (0, 0), (-1, 0), 1, dark_grey),405 ('ALIGN', (0, 0), (-1, -1), "LEFT"),406 ('VALIGN', (0, 0), (-1, -1), "MIDDLE"),407 ('LINEBELOW', (0, -1), (-1, -1), 1, dark_grey)408]409tableStyles = {}410tableStyles["table1"] = [411 ('TEXTCOLOR', (0, 0), (-1, -1), dark_grey),412 ('BACKGROUND', (0, 0), (-1, -1), "transparent"),413 ('ALIGN', (0, 0), (-1, -1), "LEFT"),414 ('VALIGN', (0, 0), (-1, -1), "MIDDLE"),415 ('FONTNAME', (0, 0), (-1, 0), "Averta-Bold")416]417tableStyles["table1a"] = tableStyles["table1"]418# tableStyles["table2"] = generic_style + [419# ('FONTNAME', (0, 0), (-1, 0), "Averta-Bold"),420# ('LINEABOVE', (0, 1), (-1, 1), 1, dark_grey)421# ]422tableStyles["table3"] = generic_style + [423 ('LINEABOVE', (0, 1), (-1, 1), 1, grey),424 ('LINEABOVE', (0, 2), (-1, 2), 1, grey),425 ('LINEABOVE', (0, 3), (-1, 3), 1, grey),426 ('FONTNAME', (0, 0), (0, -1), "Averta-Bold")427]428tableStyles["table4"] = generic_style + [429 ('LINEABOVE', (0, 1), (-1, 1), 1, grey),430 ('LINEABOVE', (0, 2), (-1, 2), 1, grey),431 ('LINEABOVE', (0, 3), (-1, 3), 1, grey)432]433tableStyles["table5"] = generic_style + [434 ('LINEABOVE', (0, 1), (-1, 1), 1, grey),435 ('LINEABOVE', (0, 2), (-1, 2), 1, grey),436 ('FONTNAME', (0, 0), (0, -1), "Averta-Bold")437]438tableStyles["table6"] = generic_style + [439 ('LINEABOVE', (0, 1), (-1, 1), 1, grey),440 ('LINEABOVE', (0, 2), (-1, 2), 1, grey),441 ('LINEABOVE', (0, 3), (-1, 3), 1, grey)442]443tableStyles["table7"] = generic_style + [444 ('TEXTCOLOR', (0, 0), (-1, -1), dark_grey),445 ('BACKGROUND', (0, 0), (-1, -1), "white"),446 ('ALIGN', (0, 0), (-1, -1), "CENTER"),447 ('VALIGN', (0, 0), (-1, -1), "MIDDLE"),448 ('LINEAFTER', (0, 0), (0, -1), 1, dark_grey),449 ('LINEAFTER', (1, 0), (1, -1), 1, dark_grey),450 ('LINEAFTER', (2, 0), (2, -1), 1, dark_grey),451 ('LINEAFTER', (3, 0), (3, -1), 1, dark_grey),452 ('LINEAFTER', (4, 0), (4, -1), 1, dark_grey),453 ('LINEAFTER', (5, 0), (5, -1), 1, dark_grey),454 ('LINEAFTER', (6, 0), (6, -1), 1, dark_grey),455]456tableStyles["table8"] = generic_style + [457 ('FONTNAME', (0, 0), (-1, 0), "Averta-Bold"),458 ('LINEABOVE', (0, 1), (-1, 1), 1, dark_grey),459 ('LINEABOVE', (0, 2), (-1, 2), 1, grey),460 ('LINEABOVE', (0, 3), (-1, 3), 1, grey),461 ('LINEABOVE', (0, 4), (-1, 4), 1, grey),462 ('LINEABOVE', (0, 5), (-1, 5), 1, grey),...

Full Screen

Full Screen

tables_reg.py

Source:tables_reg.py Github

copy

Full Screen

1#!/usr/bin/python2# -*- coding: utf-8 -*-3from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle4from reportlab.platypus import Paragraph5from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT6import copy7import pandas as pd8import numbers9import re10from reportlab.pdfbase import pdfmetrics11from reportlab.pdfbase.ttfonts import TTFont12from reportlab.lib.fonts import addMapping13import pdb14dark_orange = "#DE5D09"15orange = "#F39000"16light_orange = "#FCC97A"17dark_aqua = "#007495"18aqua = "#93CAC9"19aqua_light = "#B2D8D7"20aqua_extra_light = "#D1E7E5"21dark_grey = "#475C6D"22grey = "#A0ADBB"23light_grey = "#CFD9E5"24pdfmetrics.registerFont(TTFont('Averta', 'fonts/Averta-Regular.ttf'))25pdfmetrics.registerFont(TTFont('Averta-Bold', 'fonts/Averta-Bold.ttf'))26pdfmetrics.registerFont(TTFont('Averta-Italic', 'fonts/Averta-RegularItalic.ttf'))27addMapping('Averta', 0, 0, 'Averta')28addMapping('Averta', 0, 1, 'Averta-Italic')29addMapping('Averta', 1, 0, 'Averta-Bold')30style = getSampleStyleSheet()31dark_greyParaBold = ParagraphStyle('dark_greyParaBold', parent=style['BodyText'], textColor=dark_grey, alignment=TA_LEFT, fontName="Averta-Bold")32dark_greyParaBoldCenter = ParagraphStyle('dark_greyParaBold', parent=style['BodyText'], textColor=dark_grey, alignment=TA_CENTER, fontName="Averta-Bold")33dark_greyParaStyle = ParagraphStyle('dark_greyParaStyle', parent=style['BodyText'], textColor=dark_grey, alignment=TA_LEFT)34dark_greyParaStyleRight = ParagraphStyle('dark_greyParaStyle', parent=style['BodyText'], textColor=dark_grey, alignment=TA_RIGHT)35NACourseStyle = ParagraphStyle('offCourseStyle', parent=style['BodyText'], textColor=grey, alignment=TA_LEFT)36offCourseStyle = ParagraphStyle('offCourseStyle', parent=style['BodyText'], textColor=orange, alignment=TA_LEFT)37progressStyle = ParagraphStyle('progressStyle', parent=style['BodyText'], textColor=aqua, alignment=TA_LEFT)38onCourseStyle = ParagraphStyle('onCourseStyle', parent=style['BodyText'], textColor=dark_aqua, alignment=TA_LEFT)39dataDictionary = {"Asia": {}}40dataDictionary["Asia"]["country"] = "Asia"41dataDictionary["Asia"]["table1"] = [42 [43 Paragraph("<b>Under-5 stunting</b>", style=dark_greyParaBold),44 Paragraph("<b>Under-5 wasting</b>", style=dark_greyParaBold),45 Paragraph("<b>Under-5 overweight</b>", style=dark_greyParaBold),46 Paragraph("<b>WRA anaemia</b>", style=dark_greyParaBold),47 Paragraph("<b>Exclusive breastfeeding</b>", style=dark_greyParaBold)48 ],49 ["Off course, some progress", "On course", "Off course, no progress", "Off course", "On course"]50]51dataDictionary["Asia"]["table1a"] = [52 [53 Paragraph("<b>Adult female obesity</b>", style=dark_greyParaBold),54 Paragraph("<b>Adult male obesity</b>", style=dark_greyParaBold),55 Paragraph("<b>Adult female diabetes</b>", style=dark_greyParaBold),56 Paragraph("<b>Adult male diabetes</b>", style=dark_greyParaBold)57 ],58 ["Off course, some progress", "On course", "Off course, no progress", "Off course"]59]60#61# dataDictionary["Asia"]["table2"] = [62# [Paragraph("Gini index score<super>1</super>", style=dark_greyParaBold), Paragraph("Gini index rank<super>2</super>", style=dark_greyParaBold), "Year"], [51, 125, 2011]63# ]64dataDictionary["Asia"]["table3"] = [65 ["Population (millions)", format(12428, ",d"), 2015],66 ["Under-5 population (millions)", format(1935, ",d"), 2015],67 ["Rural (%)", format(20, ",d"), 2015],68 ["≥65 years (millions)", format(5, ",d"), 2015],69]70dataDictionary["Asia"]["table4"] = [71 [Paragraph("Early childbearing: births by age 18 (%)", style=dark_greyParaBold), "33", "2011"]72]73dataDictionary["Asia"]["table5"] = [74 ["Physicians", "0.117", "2005"],75 ["Nurses and midwives", "1.306", "2005"],76 ["Community health workers", "0.188", "2005"]77]78dataDictionary["Asia"]["table6"] = [79 [Paragraph("Mandatory legislation for salt iodisation", style=dark_greyParaBold), "Yes"],80 [Paragraph("Sugar-sweetened beverage tax", style=dark_greyParaBold), "Yes"],81 [Paragraph("Food-based dietary guidelines", style=dark_greyParaBold), "Yes"],82 [Paragraph("Multisectoral comprehensive nutrition plan", style=dark_greyParaBold), "Yes"],83]84dataDictionary["Asia"]["table7"] = [85 [86 Paragraph("Stunting", style=dark_greyParaBoldCenter),87 Paragraph("Anaemia", style=dark_greyParaBoldCenter),88 Paragraph("Low birth weight", style=dark_greyParaBoldCenter),89 Paragraph("Child overweight", style=dark_greyParaBoldCenter),90 Paragraph("Exclusive breastfeeding", style=dark_greyParaBoldCenter),91 Paragraph("Wasting", style=dark_greyParaBoldCenter),92 Paragraph("Salt intake", style=dark_greyParaBoldCenter),93 Paragraph("Overweight adults and adolescents", style=dark_greyParaBoldCenter),94 ],95 ["Yes", "Yes", "No", "Yes", "Yes", "Yes", "Yes", "Yes", "Yes", "Yes"]96]97# dataDictionary["Asia"]["table8"] = [98# [99# Paragraph("<b>Coverage/practice indicator</b>", style=dark_greyParaBold),100# Paragraph("<b>%</b>", style=dark_greyParaBold),101# Paragraph("<b>Male</b>", style=dark_greyParaBold),102# Paragraph("<b>Female</b>", style=dark_greyParaBold),103# Paragraph("<b>Year</b>", style=dark_greyParaBold)104# ],105# [u"Children 0\u201359 months with diarrhoea who received zinc treatment", "8.1", "NA", "NA", "2014"],106# [u"Children 6\u201359 months who received vitamin A supplements in last 6 months", "71.7", "71.6", "71.9", "2014"],107# [u"Children 6\u201359 months given iron supplements in past 7 days", "2.7", "2.6", "2.7", "2014"],108# [Paragraph("Women with a birth in last five years who received iron and folic acid during their most recent pregnancy", style=dark_greyParaStyle), "69.4", "", "NA", "2014"],109# ["Household consumption of any iodised salt", "99.5", "NA", "NA", "2014"],110# ]111dat = pd.read_csv("data_reg.csv")112country_names = dat.region.unique()113for country_name in country_names:114 dataDictionary[country_name] = copy.deepcopy(dataDictionary["Asia"])115def replaceDash(x):116 x = str(x)117 y = re.sub(r"((?:^|[^{])\d+)-(\d+[^}])", u"\\1\u2013\\2", x)118 return y119missingVals = [" ", ".", "", "No data","na","NA"]120def safeFormat(x, commas=False, precision=0, percent=False, divisor=False):121 if pd.isnull(x):122 return "NA"123 elif x in missingVals:124 return "NA"125 else:126 if percent:127 try:128 x = float(x) * 100129 except ValueError:130 return replaceDash(x)131 if divisor:132 try:133 x = float(x) / divisor134 if x < 1:135 precision += 1136 except ValueError:137 return replaceDash(x)138 if not isinstance(x, numbers.Number):139 try:140 x = float(x)141 except ValueError:142 return replaceDash(x)143 if precision == 0:144 x = int(round(x, precision))145 else:146 x = round(x, precision)147 if commas:148 return format(x, ",")149 else:150 return x151def indicator(ctryDat, indicator):152 try:153 return ctryDat.loc[(ctryDat["indicator"] == indicator)].iloc[0]["value"]154 except IndexError:155 return "NA"156def indicator_sum(ctryDat, indicator):157 try:158 return ctryDat.loc[(ctryDat["indicator"] == indicator)].iloc[0]["value.sum"]159 except IndexError:160 return "NA"161def indicator_n(ctryDat, indicator):162 try:163 return ctryDat.loc[(ctryDat["indicator"] == indicator)].iloc[0]["n"]164 except IndexError:165 return "NA"166def indicator_n_max(ctryDat, indicator):167 try:168 row = ctryDat.loc[(ctryDat["indicator"] == indicator)]169 max_year = row["year"].max()170 max_row = row[(row["year"] == max_year)].iloc[0]171 return max_row["n"]172 except IndexError:173 return "NA"174def indicator_n_disagg(ctryDat, indicator, disaggregation):175 try:176 return ctryDat.loc[(ctryDat["indicator"] == indicator) & (ctryDat["disaggregation"] == disaggregation)].iloc[0]["n"]177 except IndexError:178 return "NA"179def indicator_frac(ctryDat, indicator, value):180 try:181 row = ctryDat.loc[(ctryDat["indicator"] == indicator) & (ctryDat["value"] == value)].iloc[0]182 return "{}/{}".format(int(row["n"]), int(row["N"]))183 except IndexError:184 return "NA"185def indicator_disagg(ctryDat, indicator, disagg, disagg_value=None):186 if disagg_value:187 try:188 return ctryDat.loc[(ctryDat["indicator"] == indicator) & (ctryDat["disaggregation"] == disagg) & (ctryDat["disagg.value"] == disagg_value)].iloc[0]["value"]189 except IndexError:190 return "NA"191 else:192 try:193 return ctryDat.loc[(ctryDat["indicator"] == indicator) & (ctryDat["disaggregation"] == disagg)].iloc[0]["value"]194 except IndexError:195 return "NA"196def indicator_disagg_frac(ctryDat, indicator, disagg, value, disagg_value=None):197 if disagg_value:198 try:199 row = ctryDat.loc[(ctryDat["indicator"] == indicator) & (ctryDat["disaggregation"] == disagg) & (ctryDat["disagg.value"] == disagg_value) & (ctryDat["value"] == value)].iloc[0]200 return "{}/{}".format(int(row["n"]), int(row["N"]))201 except IndexError:202 return "NA"203 else:204 try:205 row = ctryDat.loc[(ctryDat["indicator"] == indicator) & (ctryDat["disaggregation"] == disagg) & (ctryDat["value"] == value)].iloc[0]206 return "{}/{}".format(int(row["n"]), int(row["N"]))207 except IndexError:208 return "NA"209def year(ctryDat, indicator):210 try:211 return ctryDat.loc[(ctryDat["indicator"] == indicator)].iloc[0]["year"]212 except IndexError:213 return "NA"214def year_range(ctryDat, indicator):215 try:216 return ctryDat.loc[(ctryDat["indicator"] == indicator)].iloc[0]["year_range"]217 except IndexError:218 return "NA"219for country in dataDictionary.keys():220 ctryDat = dat.loc[(dat.region == country)]221 dataDictionary[country]["country"] = country222 dataDictionary[country]["regional"] = ctryDat.iloc[0]["regional"]223 max_n = ctryDat["n"].max()224 if max_n >= 50:225 minimum_n = 10226 elif max_n >= 20:227 minimum_n = 5228 elif max_n > 2:229 minimum_n = 3230 else:231 minimum_n = 2232 summed_vars = [233 "population",234 "u5_pop",235 "65_years",236 "under_5_stunting_track",237 "under_5_wasting_track",238 "under_5_overweight_track",239 "wra_anaemia_track",240 "ebf_track",241 "adult_fem_obesity_track",242 "adult_mal_obesity_track",243 "adult_fem_diabetes_track",244 "adult_mal_diabetes_track",245 "salt_leg",246 "sugar_tax",247 "fbdg",248 "multi_sec",249 "stunting_plan",250 "anaemia_plan",251 "LBW_plan",252 "child_overweight_plan",253 "EBF_plan",254 "wasting_plan",255 "sodium_plan",256 "overweight_adults_adoles_plan",257 ]258 ctryDat_with_n = ctryDat.loc[(ctryDat["n"] >= minimum_n) & (~ctryDat["indicator"].isin(summed_vars))]259 ctryDat_without_n = ctryDat.loc[(pd.isnull(ctryDat["n"])) | (ctryDat["indicator"].isin(summed_vars))]260 ctryDat = pd.concat([ctryDat_with_n, ctryDat_without_n])261 dataDictionary[country]["table1"][1] = [262 Paragraph(safeFormat(indicator_frac(ctryDat, "under_5_stunting_track", "On course"))+" on course", style=offCourseStyle),263 Paragraph(safeFormat(indicator_frac(ctryDat, "under_5_wasting_track", "On course"))+" on course", style=offCourseStyle),264 Paragraph(safeFormat(indicator_frac(ctryDat, "under_5_overweight_track", "On course"))+" on course", style=offCourseStyle),265 Paragraph(safeFormat(indicator_frac(ctryDat, "wra_anaemia_track", "On course"))+" on course", style=offCourseStyle),266 Paragraph(safeFormat(indicator_frac(ctryDat, "ebf_track", "On course"))+" on course", style=offCourseStyle),267 ]268 dataDictionary[country]["table1a"][1] = [269 Paragraph(safeFormat(indicator_frac(ctryDat, "adult_fem_obesity_track", "On course"))+" on course", style=offCourseStyle),270 Paragraph(safeFormat(indicator_frac(ctryDat, "adult_mal_obesity_track", "On course"))+" on course", style=offCourseStyle),271 Paragraph(safeFormat(indicator_frac(ctryDat, "adult_fem_diabetes_track", "On course"))+" on course", style=offCourseStyle),272 Paragraph(safeFormat(indicator_frac(ctryDat, "adult_mal_diabetes_track", "On course"))+" on course", style=offCourseStyle),273 ]274 # dataDictionary[country]["table2"][1] = [275 # safeFormat(indicator(ctryDat, "gini")),276 # safeFormat(indicator(ctryDat, "gini_rank")),277 # safeFormat(year(ctryDat, "gini"))278 # ]279 dataDictionary[country]["table3"][0][1] = safeFormat(indicator_sum(ctryDat, "population"), True, divisor=1000)280 if safeFormat(indicator_sum(ctryDat, "population"), True, divisor=1000) == "0.0":281 dataDictionary[country]["table3"][0][0] = "Population (000)"282 dataDictionary[country]["table3"][0][1] = safeFormat(indicator_sum(ctryDat, "population"), True)283 dataDictionary[country]["table3"][0][2] = safeFormat(year(ctryDat, "population"))284 dataDictionary[country]["table3"][1][1] = safeFormat(indicator_sum(ctryDat, "u5_pop"), True, divisor=1000)285 if safeFormat(indicator_sum(ctryDat, "u5_pop"), True, divisor=1000) == "0.0":286 dataDictionary[country]["table3"][1][0] = "Under-5 population (000)"287 dataDictionary[country]["table3"][1][1] = safeFormat(indicator_sum(ctryDat, "u5_pop"), True)288 dataDictionary[country]["table3"][1][2] = safeFormat(year(ctryDat, "u5_pop"))289 dataDictionary[country]["table3"][2][1] = safeFormat(indicator(ctryDat, "rural_percent"))290 dataDictionary[country]["table3"][2][2] = safeFormat(year(ctryDat, "rural_percent"))291 dataDictionary[country]["table3"][3][1] = safeFormat(indicator_sum(ctryDat, "65_years"), True, divisor=1000)292 if safeFormat(indicator_sum(ctryDat, "65_years"), True, divisor=1000) == "0.0":293 dataDictionary[country]["table3"][3][0] = "≥65 years (000)"294 dataDictionary[country]["table3"][3][1] = safeFormat(indicator_sum(ctryDat, "65_years"), True)295 dataDictionary[country]["table3"][3][2] = safeFormat(year(ctryDat, "65_years"))296 dataDictionary[country]["table3_n0"] = safeFormat(indicator_n(ctryDat, "population"))297 dataDictionary[country]["table3_n1"] = safeFormat(indicator_n(ctryDat, "u5_pop"))298 dataDictionary[country]["table3_n2"] = safeFormat(indicator_n(ctryDat, "rural_percent"))299 dataDictionary[country]["table3_n3"] = safeFormat(indicator_n(ctryDat, "65_years"))300 dataDictionary[country]["table4"][0][1] = safeFormat(indicator(ctryDat, "early_childbearing_prev"))301 dataDictionary[country]["table4"][0][2] = Paragraph(str(safeFormat(year_range(ctryDat, "early_childbearing_prev"))), style=dark_greyParaStyleRight)302 dataDictionary[country]["table4_n"] = safeFormat(indicator_n(ctryDat, "early_childbearing_prev"))303 dataDictionary[country]["table5"][0][1] = safeFormat(indicator(ctryDat, "physicians"), False, 2)304 dataDictionary[country]["table5"][0][2] = Paragraph(str(safeFormat(year_range(ctryDat, "physicians"))), style=dark_greyParaStyleRight)305 dataDictionary[country]["table5"][1][1] = safeFormat(indicator(ctryDat, "nurses_and_midwives"), False, 2)306 dataDictionary[country]["table5"][1][2] = Paragraph(str(safeFormat(year_range(ctryDat, "nurses_and_midwives"))), style=dark_greyParaStyleRight)307 dataDictionary[country]["table5"][2][1] = safeFormat(indicator(ctryDat, "community_health_workers"), False, 2)308 dataDictionary[country]["table5"][2][2] = Paragraph(str(safeFormat(year_range(ctryDat, "community_health_workers"))), style=dark_greyParaStyleRight)309 dataDictionary[country]["table5_n"] = safeFormat(indicator_n(ctryDat, "physicians"))310 dataDictionary[country]["table6"][0][1] = safeFormat(indicator_frac(ctryDat, "salt_leg", "Yes"))311 dataDictionary[country]["table6"][1][1] = safeFormat(indicator_frac(ctryDat, "sugar_tax", "Yes"))312 dataDictionary[country]["table6"][2][1] = safeFormat(indicator_frac(ctryDat, "fbdg", "Yes"))313 dataDictionary[country]["table6"][3][1] = safeFormat(indicator_frac(ctryDat, "multi_sec", "Yes"))314 dataDictionary[country]["table7"][1] = [315 safeFormat(indicator_frac(ctryDat, "stunting_plan", "Yes")),316 safeFormat(indicator_frac(ctryDat, "anaemia_plan", "Yes")),317 safeFormat(indicator_frac(ctryDat, "LBW_plan", "Yes")),318 safeFormat(indicator_frac(ctryDat, "child_overweight_plan", "Yes")),319 safeFormat(indicator_frac(ctryDat, "EBF_plan", "Yes")),320 safeFormat(indicator_frac(ctryDat, "wasting_plan", "Yes")),321 safeFormat(indicator_frac(ctryDat, "sodium_plan", "Yes")),322 safeFormat(indicator_frac(ctryDat, "overweight_adults_adoles_plan", "Yes")),323 ]324 # dataDictionary[country]["table8"][1][1] = safeFormat(indicator_disagg(ctryDat, "diarrhea_zinc", "all"))325 # dataDictionary[country]["table8"][1][4] = safeFormat(year(ctryDat, "diarrhea_zinc"))326 #327 # dataDictionary[country]["table8"][2][1] = safeFormat(indicator_disagg(ctryDat, "vit_a", "gender", "Both"))328 # dataDictionary[country]["table8"][2][2] = safeFormat(indicator_disagg(ctryDat, "vit_a", "gender", "Boys"))329 # dataDictionary[country]["table8"][2][3] = safeFormat(indicator_disagg(ctryDat, "vit_a", "gender", "Girls"))330 # dataDictionary[country]["table8"][2][4] = safeFormat(year(ctryDat, "vit_a"))331 #332 # dataDictionary[country]["table8"][3][1] = safeFormat(indicator_disagg(ctryDat, "iron_supp", "gender", "Both"))333 # dataDictionary[country]["table8"][3][2] = safeFormat(indicator_disagg(ctryDat, "iron_supp", "gender", "Boys"))334 # dataDictionary[country]["table8"][3][3] = safeFormat(indicator_disagg(ctryDat, "iron_supp", "gender", "Girls"))335 # dataDictionary[country]["table8"][3][4] = safeFormat(year(ctryDat, "iron_supp"))336 #337 # dataDictionary[country]["table8"][4][1] = safeFormat(indicator_disagg(ctryDat, "iron_and_folic", "all"))338 # dataDictionary[country]["table8"][4][3] = safeFormat(indicator_disagg(ctryDat, "iron_and_folic", "all"))339 # dataDictionary[country]["table8"][4][4] = safeFormat(year(ctryDat, "iron_and_folic"))340 #341 # dataDictionary[country]["table8"][5][1] = safeFormat(indicator_disagg(ctryDat, "iodised_salt", "all"))342 # dataDictionary[country]["table8"][5][4] = safeFormat(year(ctryDat, "iodised_salt343 dataDictionary[country]["pov_percent_n"] = safeFormat(indicator_n(ctryDat, "190_percent"))344 n_indicators = [345 "190_percent",346 "GDP_capita_PPP",347 "fruit_veg_availability",348 "female_secondary_enroll_net",349 "basic_water",350 "basic_sanitation",351 "agriculture_expenditure",352 "coexistence",353 "adolescent_underweight",354 "adolescent_overweight",355 "adolescent_obesity",356 "adult_diabetes",357 "adult_overweight",358 "adult_obesity",359 "adult_blood_pressure",360 "adult_anemia",361 "adult_sodium",362 "Calcium"363 ]364 for n_indicator in n_indicators:365 dataDictionary[country][n_indicator+"_n"] = safeFormat(indicator_n(ctryDat, n_indicator))366 n_indicators_disagg = [367 ("stunting_percent", "gender"),368 ("overweight_percent", "gender"),369 ("wasting_percent", "income"),370 ("stunting_percent", "income"),371 ("overweight_percent", "income"),372 ("wasting_percent", "location"),373 ("stunting_percent", "location"),374 ("overweight_percent", "location"),375 ]376 for n_indicator, disagg in n_indicators_disagg:377 dataDictionary[country][n_indicator+"_"+disagg+"_n"] = safeFormat(indicator_n_disagg(ctryDat, n_indicator, disagg))378 c_feeding_n_max = 0379 c_feeding_inds = [380 "continued_breastfeeding_2yr",381 "continued_breastfeeding_1yr",382 "minimum_accept_diet",383 "minimum_diet_diversity",384 "minimum_meal",385 "solid_foods",386 "exclusive_breastfeeding",387 "early_initiation"388 ]389 for ind in c_feeding_inds:390 this_n = indicator_n_max(ctryDat, ind)391 try:392 if this_n > c_feeding_n_max:393 c_feeding_n_max = this_n394 except TypeError:395 pass396 dataDictionary[country]["c_feeding_n"] = safeFormat(c_feeding_n_max)397generic_style = [398 ('TEXTCOLOR', (0, 0), (-1, -1), dark_grey),399 ('BACKGROUND', (0, 0), (-1, -1), "white"),400 ('LINEABOVE', (0, 0), (-1, 0), 1, dark_grey),401 ('ALIGN', (0, 0), (-1, -1), "LEFT"),402 ('VALIGN', (0, 0), (-1, -1), "MIDDLE"),403 ('LINEBELOW', (0, -1), (-1, -1), 1, dark_grey)404]405tableStyles = {}406tableStyles["table1"] = [407 ('TEXTCOLOR', (0, 0), (-1, -1), dark_grey),408 ('BACKGROUND', (0, 0), (-1, -1), "transparent"),409 ('ALIGN', (0, 0), (-1, -1), "LEFT"),410 ('VALIGN', (0, 0), (-1, -1), "MIDDLE"),411 ('FONTNAME', (0, 0), (-1, 0), "Averta-Bold")412]413tableStyles["table1a"] = tableStyles["table1"]414# tableStyles["table2"] = generic_style + [415# ('FONTNAME', (0, 0), (-1, 0), "Averta-Bold"),416# ('LINEABOVE', (0, 1), (-1, 1), 1, dark_grey)417# ]418tableStyles["table3"] = generic_style + [419 ('LINEABOVE', (0, 1), (-1, 1), 1, grey),420 ('LINEABOVE', (0, 2), (-1, 2), 1, grey),421 ('LINEABOVE', (0, 3), (-1, 3), 1, grey),422 ('FONTNAME', (0, 0), (0, -1), "Averta-Bold")423]424tableStyles["table4"] = generic_style + [425 ('LINEABOVE', (0, 1), (-1, 1), 1, grey),426 ('LINEABOVE', (0, 2), (-1, 2), 1, grey),427 ('LINEABOVE', (0, 3), (-1, 3), 1, grey)428]429tableStyles["table5"] = generic_style + [430 ('LINEABOVE', (0, 1), (-1, 1), 1, grey),431 ('LINEABOVE', (0, 2), (-1, 2), 1, grey),432 ('FONTNAME', (0, 0), (0, -1), "Averta-Bold")433]434tableStyles["table6"] = generic_style + [435 ('LINEABOVE', (0, 1), (-1, 1), 1, grey),436 ('LINEABOVE', (0, 2), (-1, 2), 1, grey),437 ('LINEABOVE', (0, 3), (-1, 3), 1, grey)438]439tableStyles["table7"] = generic_style + [440 ('TEXTCOLOR', (0, 0), (-1, -1), dark_grey),441 ('BACKGROUND', (0, 0), (-1, -1), "white"),442 ('ALIGN', (0, 0), (-1, -1), "CENTER"),443 ('VALIGN', (0, 0), (-1, -1), "MIDDLE"),444 ('LINEAFTER', (0, 0), (0, -1), 1, dark_grey),445 ('LINEAFTER', (1, 0), (1, -1), 1, dark_grey),446 ('LINEAFTER', (2, 0), (2, -1), 1, dark_grey),447 ('LINEAFTER', (3, 0), (3, -1), 1, dark_grey),448 ('LINEAFTER', (4, 0), (4, -1), 1, dark_grey),449 ('LINEAFTER', (5, 0), (5, -1), 1, dark_grey),450 ('LINEAFTER', (6, 0), (6, -1), 1, dark_grey),451]452# tableStyles["table8"] = generic_style + [453# ('FONTNAME', (0, 0), (-1, 0), "Averta-Bold"),454# ('LINEABOVE', (0, 1), (-1, 1), 1, dark_grey),455# ('LINEABOVE', (0, 2), (-1, 2), 1, grey),456# ('LINEABOVE', (0, 3), (-1, 3), 1, grey),457# ('LINEABOVE', (0, 4), (-1, 4), 1, grey),458# ('LINEABOVE', (0, 5), (-1, 5), 1, grey),...

Full Screen

Full Screen

ShoutOut.py

Source:ShoutOut.py Github

copy

Full Screen

1from base.module import ModuleBase, ModuleAdminCommand2from base.events import EVT_CHATCOMMAND3import re45class SafeFormat(dict):6 def __missing__(self, key):7 return key.join('{}')89class ShoutOut(ModuleBase):10 module_name = "shoutout"11 def setup(self):12 self._shoutout_data = self.get_module_data()1314 self.register_admin_command(ModuleAdminCommand(15 'command',16 self.set_command,17 usage = f'{self.module_name} command !<command>',18 description = 'Set chat command for shoutouts',19 ))2021 self.register_admin_command(ModuleAdminCommand(22 'message',23 self.set_message,24 usage = f'{self.module_name} message <message>',25 description = 'Set chat message for shoutouts. Avilable variables: {streamer}, {game}, {url}',26 ))2728 self.register_admin_command(ModuleAdminCommand(29 'account',30 self.set_response_account,31 usage = f'{self.module_name} account',32 description = 'Set the account to use for shoutouts',33 ))3435 self.event_listen(EVT_CHATCOMMAND, self.command)3637 def command(self, event):38 if event.command == self.so_command:39 match = re.search(r'^@?([^ ]+)$', event.message)40 if match:41 so_user = match.group(1)42 twitch_user = self.twitch_api.get_user(so_user)43 if not twitch_user:44 return False4546 twitch_channel = self.twitch_api.get_channel(twitch_user['id'])4748 chat_str = self.so_str.format_map(SafeFormat({49 'streamer' : twitch_user['display_name'],50 'game' : twitch_channel['game_name'],51 'url' : 'https://twitch.tv/{}'.format(twitch_user['login'])52 }))5354 twitch_id = self._shoutout_data.get('account', None)55 self.send_chat_message(chat_str, twitch_id)5657 return True5859 return False6061 def set_command(self, input, command):62 match = re.search(r'^!([^ ]+)$', input)6364 if match:65 command = match.group(1)66 self._shoutout_data['command'] = command67 self.save_module_data(self._shoutout_data)6869 self.print(f"Shoutout command changed to !{command}")7071 else:72 self.print(f'Current command: !{self.so_command}')73 self.print(f'Usage: {command.usage}')7475 def set_message(self, input, command):76 if not input:77 self.print(f'Usage: {command.usage}')78 self.print('Available variables: {streamer}, {game}, {url}')79 self.print(f'Current message: {self.so_str}')80 return8182 self._shoutout_data['message'] = input83 self.save_module_data(self._shoutout_data)8485 self.print('Shoutout message updated:')86 self.print(self.so_str)8788 def set_response_account(self, input, command):89 def account_selected(account):90 self._shoutout_data['account'] = account.twitch_user_id91 self.save_module_data(self._shoutout_data)9293 self.select_account(account_selected)9495 @property96 def so_str(self):97 return self._shoutout_data.get('message', 'Go check out {streamer}. They were last playing {game}. {url}')9899 @property100 def so_command(self):101 return self._shoutout_data.get('command', 'so')102103 def shutdown(self): ...

Full Screen

Full Screen

Pytest Tutorial

Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.

Chapters

  1. What is pytest
  2. Pytest installation: Want to start pytest from scratch? See how to install and configure pytest for Python automation testing.
  3. Run first test with pytest framework: Follow this step-by-step tutorial to write and run your first pytest script.
  4. Parallel testing with pytest: A hands-on guide to parallel testing with pytest to improve the scalability of your test automation.
  5. Generate pytest reports: Reports make it easier to understand the results of pytest-based test runs. Learn how to generate pytest reports.
  6. Pytest Parameterized tests: Create and run your pytest scripts while avoiding code duplication and increasing test coverage with parameterization.
  7. Pytest Fixtures: Check out how to implement pytest fixtures for your end-to-end testing needs.
  8. Execute Multiple Test Cases: Explore different scenarios for running multiple test cases in pytest from a single file.
  9. Stop Test Suite after N Test Failures: See how to stop your test suite after n test failures in pytest using the @pytest.mark.incremental decorator and maxfail command-line option.

YouTube

Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.

https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP

Run Pytest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful