Python: For loop problem - html

I have a PSP page with html embedded. I need to place another for loop so i can insert another %s next to background-color: which will instert a appropriate colour to colour in the html table.
For example i need to insert for z in colours so it can loop over the colours list and insert the correct colour. Where ever i try to insert the for loop it doesnt seem to work it most commonly colours each cell in the table 60 times then moves onto the next cell and repeats itself and crashes my web browser.
The colours are held in a table called colours.
code below:
<table>
<%
s = ''.join(aa[i] for i in table if i in aa)
for i in range(0, len(s), 60):
req.write('<tr><td><TT>%04d</td>' % (i+1));
for k in s[i:i+60]:
req.write('<TT><td><TT><font style="background-color:">%s<font></td>' % (k));
req.write('</TT></tr>')
#end
%>
</table>
-----EDITED-----
Plugged in the code provided ebo, it colours the table all one colour. The colours list contains a variety of colours e.g. colour = ['yellow', 'yellow', 'yellow', 'yellow', 'red', 'red', 'red', 'red']
<table>
<%
s = ''.join(aa[i] for i in table if i in aa)
for i in range(0, len(s), 60):
req.write('<tr><td>%04d</td>' % (i+1));
for j, k in enumerate(s[i:i+60]):
req.write('<td><font style="background-color:%s;">%s<font></td>' % (colour[j % len(colour)], k));
req.write('</tr>')
#end
%>
</table>

I guess you want one color for each column. Best idea would be to use enumerate:
s = ''.join(aa[i] for i in table if i in aa)
for i in range(0, len(s), 60):
req.write('<tr><td>%04d</td>' % (i+1))
for j, k in enumerate(s[i:i+60]):
req.write('<td style="background-color: %s;">%s</td>' %
(colours[j % len(colours)], k))
req.write('</tr>')
I stripped all the TT tags. They were mostly wrong, either not closed or spanning over other elements.
Update This should do. Take a look at the source, if every field is filled correctly. Also download Firebug and take a look at the parsed html code. It may differ depending on your other html failures.
colour = ["red", "red", "green", "yellow"]
print "<table>"
s = '1234567890'
for i in range(0, len(s), 60):
print('<tr><td>%04d</td>' % (i+1));
for j, k in enumerate(s[i:i+60]):
print('<td><font style="background-color:%s;">%s<font></td>' % (colour[j % len(colour)], k));
print('</tr>')
print "</table>"
I piped the output of the following code into a html file and opened it. Works as expected.
python table.py > table.html
firefox table.html
I guess you have some additional errors in your code which mess up parsing.

Related

Extracting color from complex function: " Cannot modify global variable 'cColor' in function."

I'd like to extract the "col" color value from this function to be used to paint plots or candle colors. But everything I try creates one error or another. I checked the Script Reference. Shouldn't there be some way to "return" a value, as is usually the case with most functions?
lset(l,x1,y1,x2,y2,col)=>
line.set_xy1(l,x1,y1)
line.set_xy2(l,x2,y2)
line.set_width(l,5)
line.set_style(l, line.style_solid)
line.set_color(l,y2 > y1 ? #ff1100 : #39ff14) //red : green
temp = line.get_price(l,bar_index) // another value to extract
The documentation is showing it like this:
line.new(x1, y1, x2, y2, xloc, extend, color, style, width) → series line
So in your code it's looking differently and also the "new" is missing.
Scrolling a bit up on the linked page shows that there exist indeed methods to retrieve some properties of the line object:
Lines are managed using built-in functions in the line namespace. They include:
line.new() to create them.
line.set_*() functions to modify the properties of an line.
line.get_*() functions to read the properties of an existing line.
line.copy() to clone them.
line.delete() to delete them.
The line.all array which always contains the IDs of all
the visible lines on the chart. The array’s size will depend on
the maximum line count for your script and how many of those you
have drawn. aray.size(line.all) will return the array’s size.
The most simple usage is to instantiate a line object with the correct values directly, like shown here:
//#version=5
indicator("Price path projection", "PPP", true, max_lines_count = 100)
qtyOfLinesInput = input.int(10, minval = 1)
y2Increment = (close - open) / qtyOfLinesInput
// Starting point of the fan in y.
lineY1 = math.avg(close[1], open[1])
// Loop creating the fan of lines on each bar.
for i = 0 to qtyOfLinesInput
// End point in y if line stopped at current bar.
lineY2 = open + (y2Increment * i)
// Extrapolate necessary y position to the next bar because we extend lines one bar in the future.
lineY2 := lineY2 + (lineY2 - lineY1)
lineColor = lineY2 > lineY1 ? color.lime : color.fuchsia
line.new(bar_index - 1, lineY1, bar_index + 1, lineY2, color = lineColor)
Getting the line color from outside is difficult or impossible though as there never exists a method to retrieve it while for other properties those methods exist.
So the most simple way is to create the same funcionality, to get the color that exists inside the line-object, outside too, or only outside.
currentLineColor = y2 > y1 ? #ff1100 : #39ff14
You could try to extend the line-object somehow like this:
line.prototype.get_color = function() {
return this.color;
};
console.log(line.get_color())
I'm not sure if the approach with the prototype is working but it's worth it to try if you need it.

Deleting commas in R Markdown html output

I am using R Markdown to create an html file for regression results tables, which are produced by stargazer and lfe in a code chunk.
library(lfe); library(stargazer)
data <- data.frame(x = 1:10, y = rnorm(10), z = rnorm(10))
result <- stargazer(felm(y ~ x + z, data = data), type = 'html')
I create a html file win an inline code r result after the chunk above. However, a bunch of commas appear at the top of the table.
When I check the html code, I see almost every </tr> is followed by a comma.
How can I delete these commas?
Maybe not what you are looking for exactly but I am a huge fan of modelsummary. I knit to HTML to see how it looks and then usually knit to pdf. The modelsummary equivalent would look something like this
library(lfe)
library(modelsummary)
data = data.frame(x = 1:10, y = rnorm(10), z = rnorm(10))
results = felm(y ~ x + z, data = data)
modelsummary(results)
There are a lot of ways to customize it through kableExtra and other packages. The documentation is really good. Here is kind of a silly example
library(kableExtra)
modelsummary(results,
coef_map = c("x" = "Cool Treatment",
"z" = "Confounder",
"(Intercept)" = "(Intercept)")) %>%
row_spec(1, background = "#F5ABEA")

python color entire pandas dataframe rows based on column values

I have a script that downloads a .csv and does some manipulation and then emails panda dataframes in a nice html format by using df.to_html.
I would like to enhance these tables by highlighting, or coloring, different rows based on their text value in a specific column.
I tried using pandas styler which appears to work however I can not convert that to html using to_html. I get a "AttributeError: 'str' object has no attribute 'to_html"
Is there a another way to do this?
As an example lets say my DF looks like the following and I want to highlight all rows for each manufacturer. i.e Use three different colors for Ford, Chevy, and Dodge:
Year Color Manufacturer
2011 Red Ford
2010 Yellow Ford
2000 Blue Chevy
1983 Orange Dodge
I noticed I can pass formatters into to_html but it appears that it cannot do what I am trying to accomplish by coloring? I would like to be able to do something like:
def colorred():
return ['background-color: red']
def color_row(value):
if value is "Ford":
result = colorred()
return result
df1.to_html("test.html", escape=False, formatters={"Manufacturer": color_row})
Surprised this has never been answered as looking back at it I do not believe this is even possible with to_html formatters. After revisiting this several times I have found a very nice solution I am happy with. I have not seen anything close to this online so I hope this helps someone else.
d = {'Year' : [2011, 2010, 2000, 1983],
'Color' : ['Red', 'Yellow', 'Blue', 'Orange'],
'Manufacturer' : ['Ford', 'Ford', 'Chevy', 'Dodge']}
df =pd.DataFrame(d)
print (df)
def color_rows(s):
df = s.copy()
#Key:Value dictionary of Column Name:Color
color_map = {}
#Unqiue Column values
manufacturers = df['Manufacturer'].unique()
colors_to_use = ['background-color: #ABB2B9', 'background-color: #EDBB99', 'background-color: #ABEBC6',
'background-color: #AED6F1']
#Loop over our column values and associate one color to each
for manufacturer in manufacturers:
color_map[manufacturer] = colors_to_use[0]
colors_to_use.pop(0)
for index, row in df.iterrows():
if row['Manufacturer'] in manufacturers:
manufacturer = row['Manufacturer']
#Get the color to use based on this rows Manufacturers value
my_color = color_map[manufacturer]
#Update the row using loc
df.loc[index,:] = my_color
else:
df.loc[index,:] = 'background-color: '
return df
df.style.apply(color_rows, axis=None)
Output:
Pandas row coloring
Since I do not have the cred to embed images here is how I email it. I convert it to html with the following.
styled = df.style.apply(color_rows, axis=None).set_table_styles(
[{'selector': '.row_heading',
'props': [('display', 'none')]},
{'selector': '.blank.level0',
'props': [('display', 'none')]}])
html = (styled.render())

GNUPLOT: How to use a function to decide the plot style

I have lots of series to draw in 1 plot. I want to decide the plot style/type according to the number of a series. Here is the example code of what I am aiming for:
title(i)=value(sprintf("title%i",i))
title1='x'
title2='x^2'
title3='x^3'
...
with(i)=value(sprintf("with%i",i))
with1='lines'
with2='points'
with3='boxes'
...
plot for [i=1:100] '-' title title(i) with with(i)
I have test the title() function works. But the with function does not work correctly.
Can you help me fix the code?
Or do you think there are other ways to achieve what I am aiming for?
It's possible to build a string of a plot command and then run this string:
p="plot x linewidth 1"
do for [i=1:10]{
p=p.sprintf(", x+%d linewidth %d", i, i+1)
}
print p
eval(p)
The output of the print command is:
plot x linewidth 1, x+1 linewidth 2, x+2 linewidth 3, ...
and this is the resulting plot:
Depending on what you finally want, this might be something for you:
do for [i=1:10]{
p=p.(i==1 ? "'myData.csv' with lines" : "")
p=p.(i==2 ? "'myData.csv' with steps" : "")
...
}
However, this looks pretty ugly.

Can anyone help me understand this code (HTML table parsing in lxml, python)?

Background: I need to write an html table parser in python for HTML tables with varying colspans and rowspans. Upon some research I stumbled about this gem. It works well for simple cases without wacky colspans and rowspans, however I've run into a bug. The code assumes that if an element has a colspan of 3, it belongs to three different table headers, while it really only belongs to the table header the colspan falls in the center of. An example of this can be seen at http://en.wiktionary.org/wiki/han#Swedish (open up the declension table under the Swedish section). The code incorrectly returns that "hans" (possessive-neuter-3rd person masculine) belongs to possessive-common-3rd person masculine and possessive-plural-3rd person masculine because it has a colspan of 3. I've tried adding a check to table_to_2d_dict which would create a counter if a colspan > 1, and only count the element as a part of a header if the counter was equal to the the colspan // 2 + 1 (this returns the median of the range(1,colspan+1) which is the value of the table header which the element should be counted as). However, when I implement this check in the location specified in the code below, it doesn't work. To be honest this probably stems from my lack of understanding how this code works, so...
Question: Can someone explain what this code does and why it malfunctions as described above? If someone can implement a fix that'd be great but right now I'm primarily concerned with understanding the code. Thanks
Below is the code with comments that I've added to highlight parts of the code I understand and parts I don't.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import defaultdict
def table_to_list(table):
dct = table_to_2d_dict(table)
return list(iter_2d_dict(dct))
def table_to_2d_dict(table):
result = defaultdict(lambda : defaultdict(str))
for row_i, row in enumerate(table.xpath('./tr')): #these double for loops iterate over each element in the table
for col_i, col in enumerate(row.xpath('./td|./th')):
colspan = int(col.get('colspan', 1)) #gets colspan attr of the element, if none assumes it's 1
rowspan = int(col.get('rowspan', 1)) #gets rowspan attr of the element, if none assumes it's 1
col_data = col.text_content() #gets raw text inside element
#WHAT DOES THIS DO? :(
while row_i in result and col_i in result[row_i]:
col_i += 1
for i in range(row_i, row_i + rowspan):
for j in range(col_i, col_i + colspan):
result[i][j] = col_data
return result
#what does this do? :(
def iter_2d_dict(dct):
for i, row in sorted(dct.items()):
cols = []
for j, col in sorted(row.items()):
cols.append(col)
yield cols
if __name__ == '__main__':
import lxml.html
from pprint import pprint
doc = lxml.html.parse('tables.html')
for table_el in doc.xpath('//table'):
table = table_to_list(table_el)
pprint(table)