Formatting HTML tables in Julia with Dash - html-table

I am trying to format an HTML table using Dash in Julia. Based on the third example from the Julia Plotly page, I am using the "generate_table" function:
function generate_table(dataframe, max_rows = size(dataframe)[1])
html_table([
html_thead(html_tr([html_th(col) for col in names(dataframe)])),
html_tbody([
html_tr([html_td(dataframe[r, c]) for c in names(dataframe)]) for r = 1:min(nrow(dataframe), max_rows)]),
])
end
and calling this function with a dataframe, cleverly called "df":
generate_table(df)
This works fine, but the resulting table is shoved against the left-hand side of the webpage.
How can I style the table to be centered on the page?
I've tried defining the style of the html_table using this example from Python, using style="text-align:center" or style=["text:align:center"] at the end of the html_table` tag as in the following example. Since Julia no longer uses curly brackets, I've changed the curly brackets in the Python example to both parentheses and square brackets (and no brackets at all), but still have not found a solution.
function generate_table(dataframe, max_rows = size(dataframe)[1])
html_table([
html_thead(html_tr([html_th(col) for col in names(dataframe)])),
html_tbody([
html_tr([html_td(dataframe[r, c]) for c in names(dataframe)]) for r = 1:min(nrow(dataframe), max_rows)]),
], style="text-align:center")
end
This generate_table function gives me this error on the resulting page:
I've tried looking for Julia-based examples of how to style these tables, but I'm not finding much.

Style arguments — like all key-value-like arguments — are passed as dictionaries. The transliteration of a python dict like {'text-align': 'center'} is a Dict:
style = Dict("text-align"=>"center")
Note that you can also use NamedTuples for a more succinct shorthand, but dashes aren't valid Julia identifiers so you instead use camelCase:
style = (textAlign="center",) # The comma is important!

Related

Can anyone tell me what's wrong with my code (I am a newbie in programming, pls do cooperate )

I am trying to write a code which calculates the HCF of two numbers but I am either getting a error or an empty list as my answer
I was expecting the HCF, My idea was to get the factors of the 2 given numbers and then find the common amongst them then take the max out of that
For future reference, do not attach screenshots. Instead, copy your code and put it into a code block because stack overflow supports code blocks. To start a code block, write three tildes like ``` and to end it write three more tildes to close. If you add a language name like python, or javascript after the first three tildes, syntax highlighting will be enabled. I would also create a more descriptive title that more accurately describes the problem at hand. It would look like so:
Title: How to print from 1-99 in python?
for i in range(1,100):
print(i)
To answer your question, it seems that your HCF list is empty, and the python max function expects the argument to the function to not to be empty (the 'arg' is the HCF list). From inspection of your code, this is because the two if conditions that need to be satisfied before anything is added to HCF is never satisfied.
So it could be that hcf2[x] is not in hcf and hcf[x] is not in hcf[x] 2.
What I would do is extract the logic for the finding of the factors of each number to a function, then use built in python functions to find the common elements between the lists. Like so:
num1 = int(input("Num 1:")) # inputs
num2 = int(input("Num 2:")) # inputs
numberOneFactors = []
numberTwoFactors = []
commonFactors = []
# defining a function that finds the factors and returns it as a list
def findFactors(number):
temp = []
for i in range(1, number+1):
if number%i==0:
temp.append(i)
return temp
numberOneFactors = findFactors(num1) # populating factors 1 list
numberTwoFactors = findFactors(num2) # populating factors 2 list
# to find common factors we can use the inbuilt python set functions.
commonFactors = list(set(numberOneFactors).intersection(numberTwoFactors))
# the intersection method finds the common elements in a set.

Call for global variable in JS block of Selenium Webdriver test (Python)

I have a string of numbers set by user. Defined in the beginning of the Webdriver test:
numbers = input("prompt")
Then I need to enter value of this variable by JS code like this:
driver.execute_script("document.getElementsByName('phone')[0].value=***")
Where instead of *** I need the value of "numbers" variable. How should I properly insert it to make it work?
Here is what you want to do.
numbers = input("prompt")
driver.execute_script("document.getElementsByName('phone')[0].value={}".format(numbers))
The documentation link:
https://docs.python.org/3/library/string.html
And a snip-it from the docs:
The field_name itself begins with an arg_name that is either a number or a keyword. If it’s a number, it refers to a positional argument, and if it’s a keyword, it refers to a named keyword argument. If the numerical arg_names in a format string are 0, 1, 2, … in sequence, they can all be omitted (not just some) and the numbers 0, 1, 2, … will be automatically inserted in that order. Because arg_name is not quote-delimited, it is not possible to specify arbitrary dictionary keys (e.g., the strings '10' or ':-]') within a format string. The arg_name can be followed by any number of index or attribute expressions. An expression of the form '.name' selects the named attribute using getattr(), while an expression of the form '[index]' does an index lookup using getitem().
Changed in version 3.1: The positional argument specifiers can be omitted for str.format(), so '{} {}'.format(a, b) is equivalent to '{0} {1}'.format(a, b).
OR
numbers = input("prompt")
driver.execute_script("document.getElementsByName('phone')[0].value=%s" % numbers)
See examples of both here:
https://pyformat.info/
If your python variable's value is simple string without single quotes or special characters, you can simply use:
driver.execute_script("document.getElementsByName('phone')[0].value='" +
python_variable + "'");
If it has quote marks in it, or special characters that need escaping, or if it's not a string at all, you need to obtain JavaScript string representation of your Python variable's value. json.dumps will handle all the necessary formatting and escaping for you, appropriate to the type of your variable:
from json import dumps
driver.execute_script("document.getElementsByName('phone')[0].value=" +
dumps(python_variable))

Multiple statements in Main module

How do you put multiple lines of statements inside an Elm main module
Example,
module Main exposing (main)
import Html exposing (text)
main =
text "1"
text "2"
The above does not work and gives this error
Detected errors in 1 module.
-- TOO MANY ARGS -------------------------------------------------- src/Main.elm
The `text` function expects 1 argument, but it got 3 instead.
5|> text "1"
6| text "2"
Are there any missing commas? Or missing parentheses?
Putting parenthesis and commas does not help.
Elm is an expression-based language. It doesn't have statements because it doesn't have side-effects. Instead it consists of expressions which return values associated with types that are verified at compile-time.
Your code is a valid expression syntactically, so I'm not sure how you got that specific error. I can't reproduce it either directly at top level, where expressions don't belong, or in a function where expressions do belong, but there I get a type error instead of a syntax error. You're leaving out some essential part of your code.
In any case, even if you put it correctly into a function this won't do what you want. There are multiple problems even then:
Your code will be interpreted as three arguments applied to the function text, '1', text, and '2', because the line-break is not significant.
'1' is a character literal, not a string literal. "1" is a string literal.
Whatever you're going to use this with, it most likely expects a single element, not a list of elements.
The correct way to return two elements as one is to wrap the two elements in a parent element, like 'span' for example:
module Main exposing (main)
import Html exposing (text, span)
main =
span []
[ text "1"
, text "2"
]
Lastly, I recommend that you begin learning by following the official Elm guide. Elm is different enough that a trial-and-error approach based on what tends to work in JavaScript is likely to just lead to frustration.

pyspark.sql data.frame understanding functions

I am taking a mooc.
It has one assignment where a column needs to be converted to the lower case. sentence=lower(column) does the trick. But initially I thought that the syntax should be sentence=column.lower(). I looked at the documentation and I couldnt figure out the problem with my syntax. Would it be possible to explain how I could have figured out that I have a wrong syntax by searching online documentation and function definition?
I am specially confused as This link shows that string.lower() does the trick in case of the regular string python objects
from pyspark.sql.functions import regexp_replace, trim, col, lower
def removePunctuation(column):
"""Removes punctuation, changes to lower case, and strips leading and trailing spaces.
Note:
Only spaces, letters, and numbers should be retained. Other characters should should be
eliminated (e.g. it's becomes its). Leading and trailing spaces should be removed after
punctuation is removed.
Args:
column (Column): A Column containing a sentence.
Returns:
Column: A Column named 'sentence' with clean-up operations applied.
"""
sentence=lower(column)
return sentence
sentenceDF = sqlContext.createDataFrame([('Hi, you!',),
(' No under_score!',),
(' * Remove punctuation then spaces * ',)], ['sentence'])
sentenceDF.show(truncate=False)
(sentenceDF
.select(removePunctuation(col('sentence')))
.show(truncate=False))
You are correct. When you are working with a string, if you want to convert it to lowercase, you should use str.lower().
And if you check the String page in the Python Documentation, you will see it has a lower method that should work as you expect:
a_string = "StringToConvert"
a_string.lower() # "stringtoconvert"
However. in the Spark example you provided, in your function removePunctuation you are NOT working with a singlestring, you are working with a Column. And a Column is a different object than a string, that is way you should use a method that works with a Column.
Specifically, you are working with this pyspark sql method. The next time you are in doubt on which method you need to implement, double check the datatype of your objects. Also, if you check the list of imports, you will see it is calling the lower method from pyspark.sql.functions
This is how i managed to do it:
lowered = lower(column)
np_lowered = regexp_replace(lowered, '[^\w\s]', '')
trimmed_np_lowered = trim(np_lowered)
return trimmed_np_lowered
return trim(lower(regexp_replace(column, "\p{Punct}", ""))).alias('sentence')

Combining a format string with a superscript and a subscript in pyplot when rendering text in a plot

I would like to include the equation for a "power-law" curve I am creating using pyplot. I have tried several variations of the following code:
ax.text(0.1,0.9,r'{0:}x$^{1:}$'.format(A,b))
of course the text renderer uses the curly brackets as well as the format statement. I have tried doubling the curly brackets to have
ax.text(0.1,0.9,r'{0:}x$^{{1:}}$'.format(A,b))
and even tripling them
ax.text(0.1,0.9,r'{0:}x$^{{{1:}}}$'.format(A,b))
I have also tried splitting the text into two lines
exponent = '{0:}$'.format(b)
ax.text(0.1,0.9,r'{0:}x$^'.format(A)+exponent)
none of these really make sense to me or to pyplot, but I can't seem to ask the right search question to get this to work. I have found answers that suggested splitting the line and using double curly brackets but nothing that will make this work. Is this possible?
EDIT:
Through further experimentation I have answered the question above which was a simplified version of the equation I wanted to put in the plot, so let me change this question slightly. To do what I wanted above I have found that:
ax.text(0.1,0.9,r'{0:}x$^{{ {1:} }}$'.format(A,b))
works. I don't know why I hadn't tried it earlier, but I have now. The problem is that I actually want a subscript on x as well. Given that the above works I would have thought that:
ax.text(0.1,0.9,r'{0:}x$^{{ {1:} }}_{{\rm map}}$
would work, but I get the following error:
Subscript/superscript sequence is too long. Use braces { } to remove
ambiguity. (at char 0), (line:1, col:1)
I cannot see where to add braces that will remove any ambiguity. Can anyone tell me what I need to do?
This works:
ax.text(0.1, 0.9, r'${0:}x^{{{1:}}}_{{\rm map}}$'.format(A, b))
The issue was that your x was outside of the mathmode ($...$).
With regards to the double curly braces, there is an easy explanation: When using the format function all single curly braces are matched with an argument to the format function (they can also be nested). Two subsequent curly braces are the defined way of getting one curly bracket after applying format. See the documentation for more information on this.