Exemplo n.º 1
0
def getHtmlTableFromCsvFile(filePath):
    """ Prepare a html table from a csv file """
    mytbody = tbody()
    with open(filePath, 'r') as f:
        fReader = csv.DictReader(f, dialect=ExcelFR())
        myRow = tr()
        for col in fReader.fieldnames:
            myRow = myRow.append(th(col))
        mytbody = mytbody.append(myRow)
        for row in fReader:
            myRow = tr()
            for col in fReader.fieldnames:
                myRow = myRow.append(td(HTML(row[col]), _class=col))
            mytbody = mytbody.append(myRow)
    return table(mytbody)
Exemplo n.º 2
0
def _table_header(rd):
    count = 1

    rc = th()
    for i in rd:
        rc += th(_header_entry(count % 2, i), _class="skew")
        count += 1

    return thead(tr(HTML(str(rc))))
Exemplo n.º 3
0
def _table_header(rd):
    count = 1

    rc = th()
    for i in rd:
        rc += th(_header_entry(count % 2, i), _class="skew")
        count += 1

    return thead(tr(HTML(str(rc))))
Exemplo n.º 4
0
def frequency_table(item_counts, name, max_items=10):
    """ create a table of item frequencies """

    # create header
    row = htmltag.tr(htmltag.th(name), htmltag.th('Count'))
    thead = htmltag.thead(row)

    # add items
    trs = []
    items = [(v, k) for (k, v) in item_counts.items()]
    items.sort(reverse=True)
    if len(items) > max_items:
        items = items[:max_items]
    for (value, key) in items:
        row = htmltag.tr(htmltag.td(key), htmltag.td(str(value)))
        trs.append(row)
    tbody = htmltag.tbody(*trs)
    return htmltag.table(thead, tbody)
Exemplo n.º 5
0
def frequency_table(item_counts, name, sort=True, max_items=10):
    """ create a table of item frequencies """

    # create header
    tr = htmltag.tr(htmltag.th(name), htmltag.th('Count'))
    thead = htmltag.thead(tr)

    # add items
    trs = []
    items = [(v, k) for (k, v) in item_counts.items()]
    items.sort(reverse=True)
    if len(items) > max_items:
        items = items[:max_items]
    for (value, key) in items:
        tr = htmltag.tr(htmltag.td(key), htmltag.td(str(value)))
        trs.append(tr)
    tbody = htmltag.tbody(*trs)
    return htmltag.table(thead, tbody)
Exemplo n.º 6
0
def _table_body(rd):
    row = ""
    rows = ""

    for r in rd:
        count = 1
        row = _body_entry("operation", r[0])

        for i in r[1:]:
            cl = ""
            if count % 2:
                cl = "odd"
            row += _body_entry(cl, HTML(i))
            count += 1

        rows += tr(HTML(row))

    return tbody(HTML(rows))
Exemplo n.º 7
0
def _table_body(rd):
    row = ""
    rows = ""

    for r in rd:
        count = 1
        row = _body_entry("operation", r[0])

        for i in r[1:]:
            cl = ""
            if count % 2:
                cl = "odd"
            row += _body_entry(cl, HTML(i))
            count += 1

        rows += tr(HTML(row))

    return tbody(HTML(rows))
def generateMTurkFile(startGID,endGID,outFile,prodFileWrite = False):
    imageID = genImageID(startGID,endGID)
    links = ["http://pachy.cs.uic.edu:5000/api/image/src/"+str(i)+"/?resize_pix_w=500" for i in imageID[0:maxImgs]]
    imgTags = []
    radioShare = HT.input
    for url in links:
        imgTags.append(HT.img(src = url,alt = "Unavailable"))

    # logic to create the radio buttons and the hidden form fields
    shareRadio = []
    notShareRadio = []
    hiddenField = []
    for i in range(maxImgs):
        hiddenField.append(HT.input(type='hidden',name=imageID[i],value=imageID[i]))
        shareRadio.append(HT.input(type='radio',value='share',name=imageID[i]) + "Share")
        notShareRadio.append(HT.input(type='radio',value='noShare',name=imageID[i]) + "Do Not Share")

    tdTags = []
    for i in range(maxImgs):
        tdTags.append(HT.td(HT.center(HT.HTML(hiddenField[i]),HT.HTML(shareRadio[i]),HT.HTML(notShareRadio[i])),HT.HTML(imgTags[i])))

    trTags = []
    for i in range(0,maxImgs,2):
        trTags.append(HT.tr(HT.HTML(tdTags[i]),HT.HTML(tdTags[i+1])))

    bodyTxt = HT.table(HT.HTML('\n'.join(trTags)),border="1")

    headFile = open("files/header.txt","r")
    tailFile = open("files/tail.txt","r")
    outFileDev = outFile + ".question"
    outputFile = open(outFileDev,"w")

    for line in headFile:
        outputFile.write(line)
        
    outputFile.write(bodyTxt)

    for line in tailFile:
        outputFile.write(line)

    headFile.close()
    tailFile.close()
    outputFile.close()

    if prodFileWrite:
        headFile = open("files/header_prod.txt","r")
        tailFile = open("files/tail_prod.txt","r")
        outFileProd = outFile + "_prod.question"
        outputFile = open(outFileProd,"w")
        for line in headFile:
            outputFile.write(line)
        
        outputFile.write(bodyTxt)

        for line in tailFile:   
            outputFile.write(line)

        headFile.close()
        tailFile.close()
        outputFile.close()

    return imageID
Exemplo n.º 9
0
def table(df, sortable=False, last_row_is_footer=False, col_format=None):
    """ generate an HTML table from a pandas data frame
        Args:
            df (df): pandas DataFrame
            col_format (dict): format the column name (key)
                                using the format string (value)
        Returns:
            HTML (str)
    """
    if col_format is None:
        col_format = {}
    row_count = len(df)

    # default column formatting
    default_format = {
        'align': 'right',
        'decimal_places': 2,
        'commas': True,
        'width': None,
    }

    def get_format(col, attribute):
        """ helper function to get column formatting
            Args:
                col: column name (key in the col_format)
                attribute (str)
            Returns:
                format (str) for the specified col
        """
        if col in col_format and attribute in col_format[col_name]:
            value = col_format[col_name][attribute]
        elif '*' in col_format and attribute in col_format['*']:
            value = col_format['*'][attribute]
        else:
            value = default_format[attribute]
        return value

    # create header
    items = []
    # if there's a hierarchical index for the columns, span the top level; only suppots 2 levels
    if isinstance(df.columns[0], tuple):
        headers = []
        prev_header = df.columns[0][0]
        span = 0
        for i, col_name in enumerate(df.columns):
            h1 = col_name[0]
            h2 = col_name[1]
            if h1 == prev_header:
                span += 1
                if i == (len(df.columns)-1):
                    headers.append(htmltag.th(h1, colspan=span, _class='centered'))
            else:
                headers.append(htmltag.th(prev_header, colspan=span, _class='centered'))
                if i == (len(df.columns)-1):
                    headers.append(htmltag.th(h1, colspan=1))
                else:
                    prev_header = h1
                    span = 1

            if get_format(col_name, 'align') == 'right':
                items.append(htmltag.th(h2, _class='alignRight'))
            else:
                items.append(htmltag.th(h2))
        thead = htmltag.thead(htmltag.tr(*headers), htmltag.tr(*items))

    else:
        for col_name in df.columns:
            if get_format(col_name, 'align') == 'right':
                if sortable:
                    items.append(htmltag.th(col_name, **{'class':'alignRight', 'data-sortable':'true'}))
                else:
                    items.append(htmltag.th(col_name, _class='alignRight'))
            else:
                if sortable:
                    items.append(htmltag.th(col_name, **{'data-sortable':'true'}))
                else:
                    items.append(htmltag.th(col_name))

        thead = htmltag.thead(htmltag.tr(*items))

    # create body (and optionally footer)
    tfoot = ''
    rows = []
    for i, row in df.iterrows():
        values = row.tolist()
        items = []
        for j, v in enumerate(values):
            col_name = df.columns[j]
            if is_numeric(v):
                decimal_places = get_format(col_name, 'decimal_places')
                if get_format(col_name, 'commas'):
                    pattern = '{:,.' + str(decimal_places) + 'f}'
                else:
                    pattern = '{:.' + str(decimal_places) + 'f}'
                v = pattern.format(v)
            if get_format(col_name, 'align') == 'right':
                items.append(htmltag.td(v, _class='alignRight'))
            # TODO - need to implement width control
            #width = get_format(col_name, 'width')
            #if is_numeric(width):
            #    style='width:' + str(width) + 'px'
            #    items.append(htmltag.td(v, style=style ))
            else:
                items.append(htmltag.td(v))
        if last_row_is_footer and i == row_count - 1:
            tfoot = htmltag.tfoot(htmltag.tr(*items))
        else:
            rows.append(htmltag.tr(*items))
    tbody = htmltag.tbody(*rows)
    # if sortable, apply the bootstrap-table tab, bs-table
    if sortable:
        if row_count > 15:
            return htmltag.table(thead, tbody, tfoot, **{'class':'bs-table', 'data-striped':'true', 'data-height':'600'})
        else:
            return htmltag.table(thead, tbody, tfoot, **{'class':'bs-table', 'data-striped':'true'})
    else:
        return htmltag.table(thead, tbody, tfoot, **{'class':'table-striped'})
Exemplo n.º 10
0
def table(df, sortable=False, last_row_is_footer=False, format=None):
    """ generate an HTML table from a pandas data frame """
    if not format:
        format = {}
    rowCount = len(df)

    # default column formatting
    default_format = {
        'align': 'right',
        'decimal_places': 2,
        'commas': True,
        'width': None,
    }

    # a helper function to get column formatting
    def get_format(col_name, attribute):
        if col_name in format and attribute in format[col_name]:
            value = format[col_name][attribute]
        elif '*' in format and attribute in format['*']:
            value = format['*'][attribute]
        else:
            value = default_format[attribute]
        return value

    # create header
    items = []
    if isinstance(df.columns[0], tuple):
        headers = []
        prev_header = df.columns[0][0]
        span = 0
        for i, col_name in enumerate(df.columns):
            h1 = col_name[0]
            h2 = col_name[1]
            if h1 == prev_header:
                span += 1
                if i == (len(df.columns) - 1):
                    headers.append(
                        htmltag.th(h1, colspan=span, _class='centered'))
            else:
                headers.append(
                    htmltag.th(prev_header, colspan=span, _class='centered'))
                if i == (len(df.columns) - 1):
                    headers.append(htmltag.th(h1, colspan=1))
                else:
                    prev_header = h1
                    span = 1

            if get_format(col_name, 'align') == 'right':
                items.append(htmltag.th(h2, _class='alignRight'))
            else:
                items.append(htmltag.th(h2))
        thead = htmltag.thead(htmltag.tr(*headers), htmltag.tr(*items))

    else:
        for col_name in df.columns:
            if get_format(col_name, 'align') == 'right':
                if sortable:
                    items.append(
                        htmltag.th(
                            col_name, **{
                                'class': 'alignRight',
                                'data-sortable': 'true'
                            }))
                else:
                    items.append(htmltag.th(col_name, _class='alignRight'))
            else:
                if sortable:
                    items.append(
                        htmltag.th(col_name, **{'data-sortable': 'true'}))
                else:
                    items.append(htmltag.th(col_name))

        thead = htmltag.thead(htmltag.tr(*items))

    # create body (and optionally footer)
    tfoot = ''
    rows = []
    for i, row in df.iterrows():
        values = row.tolist()
        if False:  #
            tf = t.tfoot
            tr = tf.tr
        items = []
        for j, v in enumerate(values):
            col_name = df.columns[j]
            if is_numeric(v):
                decimal_places = get_format(col_name, 'decimal_places')
                if get_format(col_name, 'commas'):
                    pattern = '{:,.' + str(decimal_places) + 'f}'
                else:
                    pattern = '{:.' + str(decimal_places) + 'f}'
                v = pattern.format(v)
            if get_format(col_name, 'align') == 'right':
                items.append(htmltag.td(v, _class='alignRight'))
            #width = get_format(col_name, 'width')
            #if is_numeric(width):
            #    style='width:' + str(width) + 'px'
            #    items.append(htmltag.td(v, style=style ))
            else:
                items.append(htmltag.td(v))
        if last_row_is_footer and i == rowCount - 1:
            tfoot = htmltag.tfoot(htmltag.tr(*items))
        else:
            rows.append(htmltag.tr(*items))
    tbody = htmltag.tbody(*rows)
    if sortable:
        if rowCount > 15:
            return htmltag.table(
                thead, tbody, tfoot, **{
                    'class': 'bs-table',
                    'data-striped': 'true',
                    'data-height': '600'
                })
        else:
            return htmltag.table(
                thead, tbody, tfoot, **{
                    'class': 'bs-table',
                    'data-striped': 'true'
                })
    else:
        return htmltag.table(thead, tbody, tfoot, **{'class': 'table-striped'})