I am currently trying to highlight Ada code on my website using google prettify and a file I have found here.
However, I am not able to use the later file with prettify, and the automatic language detection messes up attributes with ' characters (such as Array'first or integer'image), and highlights them as string delimiters.
for instance, I have the following sample code, and I would like to have it formatted correctly in my page:
procedure mergesort (V: in out TV_integer; iterations: in out integer) is
-- {} => {V is sorted}
m : integer := (V'first + V'last) / 2;
begin -- mergesort
if V'length > 1 then
mergesort(V(V'first..m), iterations);
mergesort(V(m+1..V'last), iterations);
merge(V(V'first..m),V(m+1..V'last),V,iterations);
end if;
end mergesort;
Any help would be appreciated.
EDIT: I tried using a pre class="prettyprint lang-ada" tag so that it would use the lang-ada custom script, but without success.
I'm the author of the Ada lexer for google code prettify. To use it, add this to your page:
<head>
<!-- ... -->
<link href="css/prettify.css" media="screen" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/prettify.js"></script>
<script type="text/javascript" src="js/lang-ada.js"></script>
</head>
<body onload="prettyPrint()">
Do not use the auto-loader, it won't use custom lexers (change the paths to where you put the files of google code prettify). After you have done that, you can highlight code on your website like this:
<pre class="prettyprint lang-ada"><code>
-- Ada code
</code></pre>
or if you're using markdown or something else that prevents you from adding classes to your tags:
<?prettify lang=ada?>
<pre><code>
-- here goes your Ada code
</code></pre>
By the way, the Ada lexer will mark Ada attributes with the class atn (which is colored violet by default). If you want them to have the same color as other code, just edit prettify.css.
Ada is not supported. A lexer has been submitted by fordprefect86, but has not (yet) been included.
See Issue 312 for more information
Related
hey guys having trouble with vincent, im not sure exactly how to use it
So ive parsed some data from the UK house of commons petition site, and now have a list of countries and their corresponding number of votes into a certain petition and ive got the data from JSON to ('Austria', 40) format
Im using vincent to plot them onto a map with colour scaled to represent number of votes but dont really know how to use vincent
for example
to render a basic map of the world the code is
world_topo = r'world-countries.topo.json'
geo_data = [{'name': 'countries',
'url': world_topo,
'feature': 'world-countries'}]
vis = Map(geo_data=geo_data, scale=200)
vis.to_json('vega.json')
but that just outputs a JSON, not a picture of a map, even though that is what two tutorial examples are saying should happen (for example here: http://wrobstory.github.io/2013/10/mapping-data-python.html and another place I forgot to save the link)
could someone help me out? thanks in advance guys
First you should change the last line of your code. Try this simplified example:
import vincent
list_data = [10, 20, 30, 20, 15, 30, 45]
vega = vincent.Bar(list_data)
vega.to_json('vega.json',html_out=True,html_path='vega.html')
Then using the terminal CD to the location of your project, i.e. where vega.html is saved.
After that run a local server using Python -m SimpleHTTPServer 8000. After that you can open any browser and type http://localhost:8000/vega.html .
Note that the depending on the version of vincent the notation inside the .tojson may be different.
Hope that helps:)
P.S. I think you should add the Python tag as well so people can find it easier.
If you want to see a picture of a map you will have to create a html file that will read the json file and map it.
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script src="http://d3js.org/d3.geo.projection.v0.min.js" charset="utf-8"></script>
<script src="http://trifacta.github.com/vega/vega.js"></script>
</head>
<body>
<div id="vis"></div>
//This script will read your json file and print it to the map
<script type="text/javascript">
function parse(spec)
{
vg.parse.spec(spec, function(chart) { chart({el:"#vis"}).update(); });
}
//Put the name of your json file where vega.json is
parse("vega.json");
</script>
</body>
</html>
Then open your command line and type in:
Python -m SimpleHTTPServer 8000 # Python 2
Next open your browser at http://localhost:8000/path/to/json/file.
You should now see a map on the page. Note this will be a basic map depending on what data you passed from the json file.
I hope this helps and good luck!
I've installed the package control "evernote plugin"and view in browser for Sublime3. When I passed the code to evernote, Sublime3 come out an alert as follows.
Evernote complained:
The contents of the note are not valid.
The inline HTML tag 'iostream' is not allowed in Evernote notes.
Retry?
My code is as follows.
#include <iostream>
using namespace std;
int main ()
{
// declaring variables:
int a, b;
int result;
// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;
// print out the result:
cout << result;
// terminate the program:
return 0;
}
How can I cope with it?
From the sublime-evernote package wiki:
Raw HTML
Take extra care in not using prohibited elements (see here).
Evernote will complain if you use unsupported elements (such as <style>) or unsupported attributes (such as class or id).
If you wish to have the code within a raw html block interpreted as Markdown, specify a markdown="1" attribute for the outermost element:
<div markdown="1">
**Note**:
This is important!
</div>
Source: https://github.com/bordaigorl/sublime-evernote/wiki/Supported-Markdown#raw-html
You have to use
<iostream>
Otherwise it will be interpreted by Markdown as literal HTML (and passed as such to Evernote)
-- update--
You can deal with this problem by reinstall the sublime-evernot.I have tried, and it works well!
clone this repository with
$ git clone --recursive http://github.com/bordaigorl/sublime-evernote.git
in
Windows: %APPDATA%/Roaming/Sublime Text 3/Packages/
OSX: ~/Library/Application Support/Sublime Text 3/Packages/
Linux: ~/.Sublime Text 3/Packages/
https://github.com/timlockridge/SublimeEvernote
sublime-evernote supports Fenced Code Blocks of GitHub as mentioned in its wiki. Quoting the wiki:
Fenced code blocks GitHub style are supported. If a language is specified, pygments is used to highlight the code.
So the correct way to send code is to include it within a block of triple backticks. Quoting the Github help link for fenced code blocks:
You can create fenced code blocks by placing triple backticks ``` before and after the code block. We recommend placing a blank line before and after code blocks to make the raw formatting easier to read.
You can add an optional language identifier to enable syntax highlighting in your fenced code block.
We use Linguist to perform language detection and syntax highlighting. You can find out which keywords are valid in the languages YAML file.
As mentioned above, you can also specify the language after the backticks. For example, for your code, you need to enclose it within:
```c++
```
After enclosing it like this, send it to evernote, and it will appear with proper syntax highlighting.
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<style type="text/css">
body {background: #fff;}
</style>
</head>
<body>
<h1>Hello World</h1>
<script type="text/python" src="test.py"/>
<script type="text/javascript">
window.onload=function(){
alert("python: " + hello());
}
</script>
</body>
</html>
test.py
#!/usr/bin/env python
def hello():
return "hello"
In TideSDK develop says:
[Error] An error occured while paring Python on the page:invalid syntax ,('',2,1,'\r\n')
but this worked!! Why?
<script type="text/python">
def hello():
return "hello"
</script>
<script type="text/javascript">
window.onload=function(){
alert("python: " + hello());
}
</script>
I am new to TideSDK, my pc is WIN7 x86 with python2.7.3, TideSDK 1.3.1-beta installed,
I have no idea of this problem,Please help.
And I tried change test.py encoding,that's not help
We are working on this problem. The newer php we are planning to release with 1.3.2-beta should fix this problem.
I have the same issue. Unfortunately, I have yet to find the best fix. However implementing the source code in every html file is completely out of the question for me.
The error is complaining about the line endings. I presume are working in windows like I am, so the line endings are as follows: \r\n. TideSDK wrote a some sort of parser for external python files, but completely neglected windows line ending for whichever reason (and maintained unix style line endings). The \r\n is coming up as strange unparsable grammer and stops reading the rest of the file. Until they fix this glitch, I can only see one option. Change your line endings for all external python files from \r\n to \n.
You can do this either with your favorite IDE if it supports new line replacement. Or if it doesn't support changing your newlines, then you can use a python file to replace all of them like so:
fn = 'main.py'
with file(fn, 'rb') as f:
data = f.read()
with file(fn, 'wb') as f:
f.write(data.replace('\r\n', '\n'))
However, if you choose the second route you will be forced to run this script every time you save the file.
If I find a better answer I will let you know.
Try removing the #! line from the python file, it's not really useful for TideSDK anyway.
The issue for me was having empty lines before the def action():
I had an import that came first but it didn't seem to like the empty line before the def
I ran into this problem while using eclipse on Windows. It appears TideSDK python interpreter requires Unix style line delimiters (i.e. the non-printable character(s) that tell the computer to put text on a new line)
Windows uses two characters "\r\n" (carriage-return and line-feed) where as unix uses just the line feed character. So, if you are using a text editor on Widows, most likely it will insert "\r\n" every time you hit "enter" or "return".
If you are using Eclipse as your text editor, the fix is
File -> Convert Line Delimiters To
and select Unix.
To make the text editor do this for all new files, select "Other" and "Unix" in
Window -> Preferences -> General -> Workspace -> New text file line delimiter.
Hope this helps
Is it possible to strike text through in Restructured Text?
Something that for example renders as a <strike> tag when converted to HTML, like:
ReSTructuredText
I checked the docs better, as suggested by Ville Säävuori, and I decided to add the strikethrough like this:
.. role:: strike
:class: strike
In the document, this can be applied as follows:
:strike:`This text is crossed out`
Then in my css file I have an entry:
.strike {
text-decoration: line-through;
}
There is at least three ways of doing it:
.. role:: strike
An example of :strike:`strike through text`.
.. container:: strike
Here the full block of test is striked through.
An undecorated paragraph.
.. class:: strike
This paragraph too is is striked through.
.. admonition:: cancelled
:class: strike
I strike through cancelled text.
After applying rst2html you get:
<p>An example of <span class="strike">strike through text</span>.</p>
<div class="strike container">
Here the full block of test is striked through.</div>
<p>An undecorated paragraph.</p>
<p class="strike">This paragraph too is is striked through.</p>
<div class="strike admonition">
<p class="first admonition-title">cancelled</p>
<p class="last">I strike through cancelled text.</p>
You use them with a style
.strike {
text-decoration: line-through;
}
Here I have taken the admonition directive as example but any
directive that allow the :class: option would do.
As it generates a span the role directive is the only one that
allow to apply your style to a part of a paragraph.
It is redundant to add a class strike to a directive also named
strike, as suggest Gozzilli, because the directive name is the default
class for the html output.
I have checked these syntax both with rest2html and Sphinx. But
while everything works as expected with rest2html the class
directive fail with Sphinx. You have to replace it with
.. rst-class:: strike
This paragraph too is is striked through.
This is only stated in a small
footnote of Sphinx reSt Primer.
According to the official spec there is no directive for strikethrough markup in ReST.
However, if the environment allows for :raw: role or you are able to write your own roles, then you can write a custom plugin for it.
I found the other answers very helpful.
I am not very familiar with Sphinx but I am using it for a project. I too wanted the strike-through ability and have got it working based on the previous answers.
To be clear, I added my strikethrough role as gozzilli mentioned but I saved it inside my conf.py using the rst_prolog variable as discussed in the stack overflow thread here. This means that this role is available to all of your rest files.
I then extended the base html template as described above by creating layout.htmlwithin _templatesinside my source directory. The contents of this file are:
{% extends "!layout.html" %}
{% set css_files = css_files + ["_static/myStyle.css"] %}
This basically includes a custom css file to all your built default html docs.
Finally, in my _static directory within my source directory I included the file myStyle.css which contains:
.strike {
text-decoration: line-through;
}
Which the other answers have already provided.
I am merely writing this answer as it wasn't obvious to me with my limited Sphinx experience which files to edit.
Here's a Python definition of a del role, which works better than the accepted answer if you want to use the role in multiple pages of a Pelican blog or a Sphinx documentation project:
from docutils import nodes
from docutils.parsers.rst import roles
def deleted_role(_role, rawtext, text, _lineno, _inliner, options={}, _content=[]):
roles.set_classes(options)
options.setdefault('classes', []).append("del")
return [nodes.inline(rawtext, text, **options)], []
roles.register_canonical_role('del', deleted_role)
Even better would be to extend the HTML writer to produce a proper <del> tag, like this:
from docutils import nodes
from docutils.parsers.rst import roles
from docutils.writers._html_base import HTMLTranslator
class delnode(nodes.inline):
pass
def visit_delnode(self, node):
self.body.append(self.starttag(node, 'del', ''))
def depart_delnode(self, node):
self.body.append('</del>')
HTMLTranslator.visit_delnode = visit_delnode
HTMLTranslator.depart_delnode = depart_delnode
def deleted_role(_role, rawtext, text, _lineno, _inliner, options={}, _content=[]):
roles.set_classes(options)
return [delnode(rawtext, text, **options)], []
roles.register_canonical_role('del', deleted_role)
You can trivially adjust it to produce an <s>, of course.
Consider the user may have a different background, so here is no one solution that can be suitable for everyone.
1.Only one file
If you only use it only on one file. For example, you published a simple project to PyPI, and you may probably just only one README.rst file. The following may you want.
.. |ss| raw:: html
<strike>
.. |se| raw:: html
</strike>
single line
=============
|ss| abc\ |se|\defg
multiple line
=============
|ss|
line 1
line 2
|se|
789
you can copy and paste it on this website: https://livesphinx.herokuapp.com/
and will see the picture as the following:
It's simple, and you can on directly see the preview on some IDE, for example, PyCharm.
bellow is writing for the users of Sphinx
2.beginner of Sphinx
If you are a beginner of Sphinx. ( I mean maybe you want to use Sphinx to create a document, but Python is not familiar for you ) then try as following:
# conf.py
from pathlib import Path
html_static_path = ['_static', ]
html_css_files = ['css/user.define.css'] # If you want to control which HTML should contain it, you can put it on the HTML, which is very like the answer by #Gregory Kuhn.
with open(Path(__file__).parent / Path('_static/css/user.define.rst'), 'r') as f:
user_define_role = f.read()
rst_prolog = '\n'.join([ user_define_role + '\n',]) # will be included at the beginning of every source file that is read.
# rst_epilog = '\n'.join([ user_define_role + '\n',]) # it's ok if you put it on the end.
user.define.rst
.. role:: strike
user.define.css
.strike {text-decoration: line-through;}
With the rst_prolog, It can auto-add the role on each rst files, but if you change the content( that file, it contains a format that you define), then you must rebuild to make the render is correct.
3.Create roles
You can create an extension to achieve it.
# conf.py
extensions = ['_ext.rst_roles', ]
html_static_path = ['_static', ]
html_css_files = ['css/user.define.css']
# rst_roles.py
from sphinx.application import Sphinx
from docutils.parsers.rst import roles
from docutils import nodes
from docutils.parsers.rst.states import Inliner
def strike_role(role, rawtext, text, lineno, inliner: Inliner, options={}, content=[]):
your_css_strike_name = 'strike'
return nodes.inline(rawtext, text, **dict(classes=[your_css_strike_name])), []
def setup(app: Sphinx):
roles.register_canonical_role('my-strike', strike_role) # usage: :my-strike:`content ...`
The full architecture:
conf.py
_ext/
rst_roles.py
_static/
css/
user.define.css
about the rules, you can reference this link rst-roles
And I vary recommended you to see the docutils.parsers.rst.roles.py .
I wrote an extension for this.
Just pip install sphinxnotes-strike and use:
:strike:`text`
or
:del:`text`
to show strike text.
For more info: https://sphinx-notes.github.io/strike/
Since Docutils 0.17, the HTML5-writer uses <del> if a matching class value is found in inline, literal, or container elements:
.. role:: del
:del:`This text has been deleted`, here is the rest of the paragraph.
.. container:: del
This paragraph has been deleted.
I've spent my requisite two hours Googling this, and I can not find any good answers, so let's see if humans can beat Google computers.
I want to parse a stylesheet in Ruby so that I can apply those styles to elements in my document (to make the styles inlined). So, I want to take something like
<style>
.mystyle {
color:white;
}
</style>
And be able to extract it into a Nokogiri object of some sort.
The Nokogiri class "CSS::Parser" (http://nokogiri.rubyforge.org/nokogiri/Nokogiri/CSS/Parser.html) certainly has a promising name, but I can't find any documentation on what it is or how it works, so I have no idea if it can do what I'm after here.
My end goal is to be able to write code something like:
a_web_page = Nokogiri::HTML(html_page_as_string)
parsed_styles = Nokogiri::CSS.parse(html_page_as_string)
parsed_styles.each do |style|
existing_inlined_style = a_web_page.css(style.declaration) || ''
a_web_page.css(style.declaration)['css'] = existing_inlined_style + style.definition
end
Which would extract styles from a stylesheet and add them all as inlined styles to my document.
Nokogiri can't parse CSS stylesheets.
The CSS::Parser that you came across parses CSS expressions. It is used whenever you traverse a HTML tree by CSS selectors rather than XPath (this is a cool feature of Nokogiri).
There is a Ruby CSS parser, though. You can use it together with Nokogiri to achieve what you want.
require "nokogiri"
require "css_parser"
html = Nokogiri::HTML(html_string)
css = CssParser::Parser.new
css.add_block!(css_string)
css.each_selector do |selector, declarations, specificity|
html.css(selector).each do |element|
style = element.attributes["style"]&.value || ""
element.set_attribute('style', [style, declarations].compact.join(" "))
end
end
#molf definitely had a great start there, but it still required debugging a handful of problems to get it working in production. Here is the current, tested version of this:
html = Nokogiri::HTML(html_string)
css = CssParser::Parser.new
css.add_block!(html_string) # Warning: This line modifies the string passed into it. In potentially bad ways. Make sure the string has been duped and stored elsewhere before passing this.
css.each_selector do |selector, declarations, specificity|
next unless selector =~ /^[\d\w\s\#\.\-]*$/ # Some of the selectors given by css_parser aren't actually selectors.
begin
elements = html.css(selector)
elements.each do |match|
match["style"] = [match["style"], declarations].compact.join(" ")
end
rescue
logger.info("Couldn't parse selector '#{selector}'")
end
end
html_with_inline_styles = html.to_s