How to set codes in html page? - html

I am new in html and i'm making a html page in which i want to display some code, but it not showing proper way like what we are writing in notepad. So, i have to write each and every line or any other solution is there. Suppose this is the code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.liste);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Setup the list view
final ListView prestListView = (ListView) findViewById(R.id.list);
final prestationAdapterEco prestationAdapterEco = new prestationAdapterEco(this, R.layout.prestation);
prestListView.setAdapter(prestationAdapterEco);
// Populate the list, through the adapter
for(final prestationEco entry : getPrestations()) {
prestationAdapterEco.add(entry);
}
prestListView.setClickable(true);
prestListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Object o = prestListView.getItemAtPosition(position);
String str=(String)o;//As you are using Default String Adapter
Toast.makeText(getApplicationContext(),str,Toast.LENGTH_SHORT).show();
}
});
}
and i want to show it on html page like this only. Please help.. Thanks

<pre><code> code... </code></pre>
This seems to be the best method they've found here: <code> vs <pre> vs <samp> for inline and block code snippets
It also happens to be the recommended way to show a sample of computer code on W3.org.

I think you're looking for code/syntax highlighting in HTML pages. Unfortunately there is no highlighting feature using tags in HTML.
In HTML You can use:
<code>You code goes here..</code>
For more reference: http://www.w3schools.com/tags/tag_code.asp and the list of global attributes code tag supports: http://www.w3schools.com/tags/ref_standardattributes.asp
However, you can make use of some javascripts which enables syntaxt highlighting in HTML.
You can check this thread: "Syntax highlighting code with Javascript" for more info.

Related

Add Code and pre tags to include code sample to angular component template

I was using <code> & <pre> tags in html pages to include code samples in my website...
Like:
<pre class="code">
// Host creation
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
services.AddTransient<IDataAccessLayer>(a => new DataAccessLayer(_config));
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
</pre>
The same pre tag when I use inside my angular component file its showing error for opening brace { and 'IDataAccessLayer' is not a known element.
I replaced all my "{", "}" with ( and )
Now the C# sample code inside <pre> is still showing error. Is there any way of displaying the sample code block in the component as I have multiple code block returning the html through function is not feasible.
package
version installed
angular cli
13.2.6
TS
4.5.5
Have you seen this lib ngx-highlight ?

How to get all of the headlines from a google news search using Jsoup

public static void main(String[] args) throws IOException {
Document doc = Jsoup.connect("https://www.google.com/search?q=tesla&oq=tesla&aqs=chrome.0.69i59l3j0l3.494j0j9&sourceid=chrome&ie=UTF-8#q=tesla&tbm=nws").userAgent("Mozilla").get();
Elements links = doc.select("div[class=_cnc]");
for (Element link : links) {
Elements titles = link.select("h3.r_U6c");
String title = titles.text();
System.out.println(title);
System.out.println("Headline: " + link.text());
System.out.println("Link: " + link.attr("data-href"));
}
}}
Here is the HTMl layout. I want to extract the titles for each of the links. I am just not sure on how to format the CSS selector portions of my code. I tried to look through some old threads but couldn't get anything to work. I am just looking for the text of the headlines not the actual links. The print link statements were just for some testing that I couldn't get running.
Thanks guys
Picture of HTML
The page you're trying to fetch is loaded with Javascript. Jsoup don't process Javascript scripts.
Instead use some tools like Selenium or ui4j.

Parsing html page content without using selector

I am going to parse some web pages using Java program. For this purpose I wrote a small code for parsing page content by using xpath as selector. For parsing different sites you need to find the appropriate xpath per each site. The problem is for doing that you need an operator to find the write xpath for you. (for example using firepath firefox addon) Suppose you dont know what page you should parse or the number of sites get really big for operator to find right xpath. In this case you need a way for parsing pages without using any selector. (same scenario exist for CSS selector) Or there should be a way to find xpath automatically! I was wondering what is the method of parsing web pages in this way?
Here is the small code which I wrote for this purpose, please feel free to extend that in presenting your solutions.
public downloadHTML(String url) throws IOException{
CleanerProperties props = new CleanerProperties();
// set some properties to non-default values
props.setTranslateSpecialEntities(true);
props.setTransResCharsToNCR(true);
props.setOmitComments(true);
// do parsing
TagNode tagNode = new HtmlCleaner(props).clean(
new URL(url)
);
// serialize to xml file
new PrettyXmlSerializer(props).writeToFile(
tagNode, "c:\\TEMP\\clean.xml", "utf-8"
);
}
public static void testJavaxXpath(String pattern)
throws ParserConfigurationException, SAXException, IOException,
FileNotFoundException, XPathExpressionException {
DocumentBuilder b = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
org.w3c.dom.Document doc = b.parse(new FileInputStream(
"c:\\TEMP\\clean.xml"));
// Evaluate XPath against Document itself
javax.xml.xpath.XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList) xPath.evaluate(pattern,
doc.getDocumentElement(), XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); ++i) {
Element e = (Element) nodes.item(i);
System.out.println(e.getFirstChild().getTextContent());
}
}

How to add a <body> element to a manually generated Document?

I'm attempting to use JSoup to generate HTML from nothing i.e. not parsing a file, but rather generating HTML output in order to display the data in an object. I'm brand new to JSoup and have been looking for some examples of how to use it to generate HTML but haven't found much useful content for this specific task so I've been tinkering, but with minimal success. Here's some [non-working] code:
package jsouptest;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
public class JSoupTest {
public static void main(String[] args) {
Document doc = new Document("");
Element headline = doc.body().appendElement("h1").text("Some text");
Element pTag = doc.body().appendElement("p").text("some text ...");
Element span = pTag.prependElement("span").text("MoarTxt");
}
}
This line:
Element headline = doc.body().appendElement("h1").text("Some text");
Throws a NullPointerException. Through some trial and error, I believe that I've determined the problem is that doc.body() isn't defined anywhere. I assumed (apparently, incorrectly) that a newly instantiated Document would come with an empty body. That doesn't seem to be the case, however. I can't figure out if I need to instantiate a new body element. I've read through the javadoc for the Document class but don't see any kind of factory or setter methods that would generate the body element for me.
Recommendations for resources beyond the JSoup API JavadDoc that might be helpful are welcome as well.
To append a <body> element to a newly created document, in its simplest form, use:
doc.appendElement("body");
Heres' your full code:
public static void main(String[] args) {
Document doc = new Document("");
doc.appendElement("body");
Element headline = doc.body().appendElement("h1").text("Some text");
Element pTag = doc.body().appendElement("p").text("some text ...");
Element span = pTag.prependElement("span").text("MoarTxt");
System.out.println(doc);
}
Output:
<body>
<h1>Some text</h1>
<p><span>MoarTxt</span>some text ...</p>
</body>
As for documentation, I believe you are already there, their official site is the best place. I'd also take a look at their cookbok.

LibTiff.NET append mode bug?

I've started using LibTiff.NET for writing tiff IPTC tags lately and discovered strange behavior on some files that i have here. I'm using sample code that ships with LibTiff.NET binaries, and it works fine with most of the images, but some files are having image data corruption after these lines:
class Program
{
private const TiffTag TIFFTAG_GDAL_METADATA = (TiffTag)42112;
private static Tiff.TiffExtendProc m_parentExtender;
public static void TagExtender(Tiff tif)
{
TiffFieldInfo[] tiffFieldInfo =
{
new TiffFieldInfo(TIFFTAG_GDAL_METADATA, -1, -1, TiffType.ASCII,
FieldBit.Custom, true, false, "GDALMetadata"),
};
tif.MergeFieldInfo(tiffFieldInfo, tiffFieldInfo.Length);
if (m_parentExtender != null)
m_parentExtender(tif);
}
public static void Main(string[] args)
{
// Register the extender callback
// It's a good idea to keep track of the previous tag extender (if any) so that we can call it
// from our extender allowing a chain of customizations to take effect.
m_parentExtender = Tiff.SetTagExtender(TagExtender);
string destFile = #"d:\00000641(tiffed).tif";
File.Copy(#"d:\00000641.tif", destFile);
//Console.WriteLine("Hello World!");
// TODO: Implement Functionality Here
using (Tiff image = Tiff.Open(destFile, "a"))
{
// we should rewind to first directory (first image) because of append mode
image.SetDirectory(0);
// set the custom tag
string value = "<GDALMetadata>\n<Item name=\"IMG_GUID\">" +
"817C0168-0688-45CD-B799-CF8C4DE9AB2B</Item>\n<Item" +
" name=\"LAYER_TYPE\" sample=\"0\">athematic</Item>\n</GDALMetadata>";
image.SetField(TIFFTAG_GDAL_METADATA, value);
// rewrites directory saving new tag
image.CheckpointDirectory();
}
// restore previous tag extender
Tiff.SetTagExtender(m_parentExtender);
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
After opening i see mostly blank white image or multiple black and white lines instead of text that have been written there (i don't need to read\write tags to produce this behavior). I noticed this happens when image already has a custom tag (console window alerts about it) or one of tags have got 'bad value' (console window in this case says 'vsetfield:%pathToTiffFile%: bad value 0 for "%TagName%" tag').
Original image: http://dl.dropbox.com/u/1476402/00000641.tif
Image after LibTiff.NET: http://dl.dropbox.com/u/1476402/00000641%28tiffed%29.tif
I would be grateful for any help provided.
You probably should not use CheckpointDirectory method for files opened in append mode. Try using RewriteDirectory method instead.
It will rewrite the directory, but instead of place it at it's old
location (as WriteDirectory() would) it will place them at the end of
the file, correcting the pointer from the preceeding directory or file
header to point to it's new location. This is particularly important
in cases where the size of the directory and pointed to data has
grown, so it won’t fit in the space available at the old location.
Note that this will result in the loss of the previously used
directory space.