How can I solve this problem. I added the following line of code in my *.rmd file:
DiagrammeR::mermaid("
journey
title My working day
section Go to work
Make tea: 5: Me
Go upstairs: 3: Me
Do work: 1: Me, Cat
section Go home
Go downstairs: 5: Me
Sit down: 5: Me
")
I use the R package distill to knit a distill_website. Only the journey diagramm is not generated.
I can see in the html-file a white space but no diagramm.
You can start by installing the development version of DiagrammeR from GitHub using the devtools package and see the difference:
devtools::install_github("rich-iannone/DiagrammeR")
It's seems that Journey Diagram is yet to be implemented.
So, for quick (and temporary) solution (works perfectly with distill::distill_article) you may
deploy mermaid without a bundler, one can insert a script tag with an
absolute address and a mermaidAPI call into the HTML like so:
<script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
<script>mermaid.initialize({startOnLoad:true});</script>
```{r diagram-mermaid, echo = FALSE}
DiagrammeR::mermaid(diagram = '
journey
title My working day
section Go to work
Make tea: 5: Me
Go upstairs: 3: Me
Do work: 1: Me, Cat
section Go home
Go downstairs: 5: Me
Sit down: 5: Me
', height = '100%', width = '100%')
```
Doing so will command the mermaid parser to look for the <div>
tags with class="mermaid". From these tags mermaid will try to
read the diagram/chart definitons and render them into svg charts.
Does this help in any way with distill::distill_website?
Related
I'm trying to add an image before the title in gitbook style bookdown project. This is similar to this question from the RStudio Community page, but I would like the image to appear only before the title, not every top-level heading.
I've created a reprex here: https://bd-reprex.netlify.app/
I've edited the _output.yml to include:
bookdown::gitbook:
...
includes:
before_body: assets/logo.html
However, as can be seen in the example above, the image now appears before every chapter, not just before the title.
Any help would be greatly appreciated!
This question was answered here.
The solution is to add a JS codeblock to the end of the index.Rmd file, such as
```{js, echo = FALSE}
title=document.getElementById('header');
title.innerHTML = '<img src="/path/to/img.png" alt="Test Image">' + title.innerHTML
```
From https://bookdown.org/yihui/rmarkdown-cookbook/latex-logo.html
title: |
![](logo.jpg){width=1in}
Adding a Logo to LaTeX Title
NB: although you cannot see them, there are two trailing spaces after {width=1in}, which means a line break in Markdown. Without the line break, the image and the title would be on the same line, which may not be what you desire.
See also related question: How to have Frontpage Image before chapter title and book title?
The example below (i.e. saved as a file index.rmd ) has the same code chunk to display an image above and below the top level heading, but the image doesn't appear above the top level heading. This occurs if there is a file _output.yml with only this entry bookdown::gitbook: in the same directory.
That line seems to enforce a table of contents (which I want) and that appears to strip out anything (image or text) before the first top level heading by default (which I don't want) - so can this behaviour be modified?
---
site: bookdown::bookdown_site
---
```{r echo=FALSE, message=FALSE, warning=FALSE}
library(imager)
im <- load.image(system.file('extdata/Leonardo_Birds.jpg',package='imager'))
plot(im, axes=FALSE)
```
# R Markdown
```{r echo=FALSE, message=FALSE, warning=FALSE}
library(imager)
im <- load.image(system.file('extdata/Leonardo_Birds.jpg',package='imager'))
plot(im, axes=FALSE)
```
What follows is workaround to your Options 2 and 3, using Markdown and CSS to style images and HTML+CSS to style text; also, using base64 image (transparent gif) generator as an space separator between elements.
Beware of whitespaces! (at the end of each line - place two white spaces and hit ENTER)
Does one of these approaches/hacks work for you? If not, it would be better to delete the answer, it may be misleading to others.
---
title: |
![](www/image.png){width=300px}|
|:-:|
![](www/image.png){width=300px style="display: block; margin:0 auto"}
![](www/image.png){width=300px height=90px align=left}
![](www/image.png){width=300px height=90px align=center}
![](www/image.png){width=300px height=90px align=right}
![](data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==){width=150px}
R Markdown Title
<center>R Markdown Title</center>
<p style="text-align: right;">R Markdown Title</p>
![](data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==){width=150px}
author: "Author Name"
date: "08/03/2020"
---
Using Markdown table to "style" images |-| (left-aligned), |:-:| (centered) and |-:| (right-aligned) will work well with simple RMarkdown outputs.
I realised that you have an image under # top level heading positioned at the very top of the page - with top:0px. causing image duplication and, possibly, hover problem:
<img src="https://i.imgur.com/GiViTbA.png" style="position:absolute;top:0px;height:100px;" />
replace with:
![](http://stackoverflow.com/favicon.ico){width=50px style="display: block; margin:0 auto;"}
and see what will happen.
---
title: |
![](https://i.imgur.com/GiViTbA.png){width=300px style="display: block; margin:0 auto;"}
![](data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==){width=50px}
R Markdown Title
![](data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==){width=50px}
output:
html_document: default
---
# I'm a top level heading {-}
![](http://stackoverflow.com/favicon.ico){width=50px style="display: block; margin:0 auto;"}
Note, you need to replace the image with a local image if you want to show the image in the rstudio viewer.
The image will be visible in the html file created when you knit, if you open in a browser connected to the internet.
```{r echo=FALSE, message=FALSE, warning=FALSE}
plot(cars)
```
EDIT:
Let's try to find a common ground, A Minimal Book Example, github here.
Adjustments made in index.Rmd:
---
title: |
![](data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==){height=300px}
author: "Author Name"
date: "`r Sys.Date()`"
site: bookdown::bookdown_site
output: bookdown::gitbook
---
# Prerequisites
<img src="https://i.imgur.com/GiViTbA.png" style="position:absolute;top:50px;height:300px;align:center;" />
This is a _sample_ book written in **Markdown**. You can use anything that Pandoc's Markdown supports, e.g., a math equation $a^2 + b^2 = c^2$.
index.Rmd output:
Adjustments made in Chapter: Introduction (01-intro.Rmd):
# Introduction {#intro}
![](data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==){height=240px}
<img src="https://i.imgur.com/GiViTbA.png" style="position:absolute;top:50px;height:300px;align:center;" />
You can label chapter and section titles using `{#label}` after them, e.g., we can reference Chapter \#ref(intro). If you do not manually label them, there will be automatic labels anyway, e.g., Chapter \#ref(methods).
01-intro.Rmd output:
With this solution we are "masking" a top level heading (# Introduction) with .png image, which will appear in the Table of Content as text.
Disadvantage: besides the obvious hack, image width must be at least equal or wider than top level heading title.
Note: 3 options are provided here, and none of them are perfect. The perfect solution may rely on modifications to the bookdown package?
Option 1:
Use includes with before_body like this in your _output.yml file (suggested here):
bookdown::gitbook:
css: assets/style.css
includes:
before_body: assets/big-image.html
after_body: assets/footer.html
Disadvantages:
i) Requires making a html file just to insert an image.
ii) If using a web-based image, won't show in Rstudio viewer.
iii) If using a local image, path can get mixed up and won't show in online web html rendering
iv) Includes image at the top of each chapter of bookdown if using before_body: my_image.html. Alternative option in_header: my_image.html does not seem compatible with the sidebar index.
Option 2
Insert image via yaml in index.rmd, using the solution under Tip 3 Add a Logo in your title/header/footer at this blog post
---
title: |
![](my_image.png)
My title
Disadvantages:
i) When you hover over the image, it displays a copy of the image in a slightly different location (Can this "Hover" behaviour be disabled?)
ii) If using a web-based image, won't show in Rstudio viewer.
iii) If using a local image, path can get mixed up and won't show in online web html rendering
Option 3
The code below borrowed from here (which you can place below the top level heading) presumably goes direct through the knitting process and inserts itself in the final html. The issue is that the image doesn't make room for itself and ends up over the first text. Is there some simple html/css to sort this out?
<img src="https://i.imgur.com/GiViTbA.png" style="position:absolute;top:0px;height:100px;" />
Disadvantages:
i) Image doesn't make room for itself and ends up over the first text. You can get around this with a hack by coding extra space (trial and error) through the yaml title like this:
title: |
.
.
.
.
site: bookdown::bookdown_site
EDIT
This is superseded by Radovan's accepted answer.
This was the best answer, taking option 3 from my previous answer, and combining a code approach to making the relevant space from Radovan's answer.
You will still have problems if you want to include a title in the YAML (I don't need this, as my title is in the image).
Also, on first loading the page, it presents nicely, but image is not seen if you go to the top of the document using the table of contents (the inheader approach used by this bookdown shows a better behaviour, but appears at the top of every chapter, which is not desired).
---
title: |
![](data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==){height=300px}
output:
html_document: default
---
# I'm a top level heading {-}
<img src="https://i.imgur.com/GiViTbA.png" style="position:absolute;top:50px;height:300px;align:center;" />
Note, you need to replace the image with a local image if you want to show the image in the rstudio viewer.
The image will be visible in the html file created when you knit, if you open in a browser connected to the internet.
```{r echo=FALSE, message=FALSE, warning=FALSE}
plot(cars)
```
The problem of hovering the image duplicating the image can be fixed by removing the line below from the css file that is generated at \libs\gitbook-2.6.7\css\style.css
.book .book-header h1 a:hover{color:inherit;text-decoration:none}#media (max-width:1000px){.book .book-header h1{display:none}}
as a result, this code below places the image right above the title:
---
title: |
![class='btn noHover'](images/Stats.png){width=400px style="display: block; margin:0 auto; align:center;" }
<center>GEOG380 Basic Stats with R</center>
---
I'm doing a particular automation task using python selenium (currently using mac system)- and for some reason my webElement.text returns nothing for a text field i'd like to copy. Hence I'm trying to copy paste the values, but for whatever reason, the .send_keys works (as I'm able to see values being entered, the cursor moving etc, but after the command+c step, I dont have the values in my clipboard. I tried pasting the clipboard contents via xerox module and it retrieves only the stuff I'd previously copied manually- my selenium driven clipboard content is not seen. I'm wondering how to get around this issue?
/code
from selenium.webdriver.common.keys import Keys
import xerox
elem = browser.find_elements_by_name("callback_url_0")[0]
#elem.send_keys("bar") # for testing purposes, and it works
elem.send_keys(Keys.CONTROL, 'a') #highlight all in box
elem.send_keys(Keys.CONTROL, 'c') #copy
#elem.send_keys(Keys.CONTROL, 'v') #
#xerox.copy()
xerox.paste() #this pastes my old system junk, nothing from the webdriver session
I've even tried Key.COMMAND as I'm on a mac, but nothing changed. Any way to get around or even hack around this issue?
UPDATE:
So, the issue is that I'm working with a text field where in, I'm able to send_keys and type text, but am not able to get its content, both by webDriver Element.text as well as copy paste using above described method. My goal is to get its content and process it further in my script. What could be the issue here and what can I really try to get around this?
UPDATE:
Using command chaining (answer below) perform copy and paste. But my clipboard has no content i.e., returns blank value. The same as the .text method. What could be the issue? Something with the form?
Here's my form html:
<div class="row">
<div class="col-sm-12">
<input app-vast-url-validate="" type="url" class="input-full-width ng-valid-required ng-valid-vast-url ng-dirty ng-touched ng-valid ng-valid-url" id="callback_url_0" name="callback_url_0" ng-model="callback.url" placeholder="Enter Callback URL" ng-keyup="onAddCallbackFormControl($event, callback)" required="" style="">
</div>
</div>
UPDATE:
So I am instead choosing to right click and copy through the context menu as none of the methods seem to be working. However even with the context menu I’m unable to hit copy either through Keys.DOWN_ARRAY or send_keys(‘c’,’c’). I really need to pick up that data- any suggestions welcome- either hacks and workarounds or understanding what’s really going on here?
You could try actions for this :
key_down(value, element=None)
Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
key_up(value, element=None)
Releases a modifier key.
ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
For more reference you can follow this link :
WebDriver API
Update :
Here is my HTML :
<html>
<head>
<title>
Stack over flow
</title>
</head>
<body>
<form action="/action_page.php">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
In this page there are two input box I'm sending some keys to first check box and then I'm doing CTRL+A followed by CTRL+C.
Then Clicking on second input box and pasting the same value.
Here is the code :
driver.find_element_by_name('fname').send_keys("Deepak")
actions = ActionChains(driver)
actions.key_down(Keys.LEFT_CONTROL).send_keys('a').keyUp(Keys.LEFT_CONTROL).build().perform()
actions.keyDown(Keys.LEFT_CONTROL).sendKeys("c").keyUp(Keys.LEFT_CONTROL).build().perform()
time.sleep(2)
element = driver.find_element_by_name('lname')
element.click()
element.send_Keys(Keys.chord(Keys.CONTROL, "v"), "");
Assuming you are using Safari I've raised this with apple back in March.
https://bugreport.apple.com/web/?problemID=38222248 (though you'll not be able to see this bug as they are not shown to other users).
I was using:
mac OS: High Sierra 10.13.3
Safari Technology Preview: Release 50 (Safari 11.2, WebKit 13606.1.5)
Selenium-java: 3.7.1
JDK: 1.8.0_161
I tried lots of alternatives to get the copy event (COMMAND+C) to trigger, without success, including:
input.sendKeys(Keys.COMMAND, "c");
Using Keys.CONTROL, Keys.META and the ctrl+insert rather than COMMAND.
I got acknowledgment by email that my bug report had been looked at but nothing since then.
I didn't find a workaround other than extracting the text from the multiple webelements individually and combining it to create the entire string as if it had been copied with a ctrl+a and ctrl+c.
I'll update this issue if I ever hear back from apple.
This was my demo code from the bug. Before running the script, pre populate the OS clipboard with some known text (just highlight and copy some text by hand)
package com.sas.aft.overview;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.safari.SafariOptions;
public class Demo {
public static void main(String[] args) throws InterruptedException {
SafariOptions options = new SafariOptions();
options.setUseTechnologyPreview(true);
WebDriver webDriver = new SafariDriver(options);
webDriver.navigate().to("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_textarea");
webDriver.switchTo().frame("iframeResult");
Thread.sleep(1000);
WebElement input = webDriver.findElement(By.cssSelector("textarea"));
input.click();
Thread.sleep(1000);
new Actions(webDriver).keyDown(Keys.COMMAND).sendKeys("a").keyUp(Keys.COMMAND).perform();
Thread.sleep(1000);
new Actions(webDriver).keyDown(Keys.COMMAND).sendKeys("c").keyUp(Keys.COMMAND).perform();
Thread.sleep(1000);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
try {
System.out.print("Clipboard: " + (String)contents.getTransferData(DataFlavor.stringFlavor) + "\n");
} catch (UnsupportedFlavorException | IOException ex) {
//ignore
}
webDriver.quit();
}
}
UPDATE ON SAFARI BUG
The bug I raised:
38222248 Command key does not work with copy for safaridriver with selenium automation
Was updated by Apple on 2nd July '18 with this comment:
A solution is under investigation. We will follow up with you again when it is available.
Was updated by Apple on 17th July '18 with this comment:
We believe this issue has been resolved in the latest macOS 10.14 beta
Although this probably isn’t the elegant or right way to go about things but I managed to get the job done ie copy paste using browser automation. So the HTML input field returned null, so I resorted to copy paste. Command + A wasn’t working so resorted to manually selecting key_down left shift and pressing right_arrow like 300 times to select my full text using Action chaining. Command + C wasn’t working then, so I tried the context_menu which again worked but I couldn’t select copy option from the menu both by send_keys(‘c’) twice or by arrow_down six times. Instead I found a helpful trick on Mac (not sure about Linux or win) that let’s you copy with control and insert. Did that worked like a charm. My xerox.paste() has the content from the page as copied by selenium and I can proceed now to process that Data. Thank you all
1.
<p class="followText">Follow us</p>
<p><a class="symbol ss-social-circle ss-facebook" href="http://www.facebook.com/HowStuffWorks" target="_blank">Facebook</a></p>
2.
<p>Gyroscopes can be very perplexing objects because they move in peculiar ways and even seem to defy gravity. These special properties make gyroscopes extremely important in everything from your bicycle to the advanced navigation system on the space shuttle. A typical airplane uses about a dozen gyroscopes in everything from its compass to its autopilot. The Russian Mir space station used 11 gyroscopes to keep its orientation to the sun, and the Hubble Space Telescope has a batch of navigational gyros as well. Gyroscopic effects are also central to things like yo-yos and Frisbees!</p>
This is part of source of the website http://science.howstuffworks.com/gyroscope.htm, from which I'm trying to extract contents of the <p> tag from.
This is the code I'm using to do that
def trade_spider(max_pages):
page = 1
while page <= max_pages:
url = 'http://science.howstuffworks.com/gyroscope' + str(page) + ".htm"
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
for link in soup.findAll('p'):
paragraph = link.string
print paragraph
But I'm getting both types of data( both 1 and 2) inside the p tag.
I need to get only the data from the part 2 section and not part 1.
Please suggest me a way to leave out tags with attributes but keep the basic tags of the same html tag.
I have created my blog using Flask-FlatPages and the posts are in Markdown, the challenge I'm having is inserting images in my blog post. The traditional way of inserting images in markdown is not working.
I also tried this without success:
![image]({{ url_for('static', filename="img/my_image.jpg") }})
Here is a quick fix! let's say we have a images folder, and we want to use the images/flower.jpg
Step 1: Put the images folder in the static folder.
Step 2: In the text, link the image with ../static/images/flower.jpg.
for example:
![flower](../static/images/flower.jpg)
or
<img src="../static/images/flower.jpg" alt="flower">
Here is what worked for me. It turns out that FLATPAGES_HTML_RENDERER is needed to achieve this goal.
Here is the code:
def my_renderer(text):
prerendered_body = render_template_string(text)
return pygmented_markdown(prerendered_body)
app = Flask(__name__)
app.config['FLATPAGES_HTML_RENDERER'] = my_renderer
pages = FlatPages(app)
This is also discussed on this post:
https://github.com/SimonSapin/Flask-FlatPages/pull/1
There are nothing wrong during the markdown to html conversion process.
I think it because bleach.clean() function.
You can try to add to allowed_tags.
allowed_tags = ['img']
allowed_attrs = {'img':['src','alt']};
target.body_html = bleach.linkify(bleach.clean(markdown(value,output_format='html'),tags=allowed_tags,attributes=allowed_attrs,strip=True));