category-theory-presentation/js/highlight/test.html
2013-02-28 16:49:12 +01:00

1846 lines
41 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<head>
<title>highlight.js test</title>
<meta charset="utf-8">
<link rel="stylesheet" title="Default" href="styles/default.css">
<link rel="alternate stylesheet" title="Dark" href="styles/dark.css">
<link rel="alternate stylesheet" title="FAR" href="styles/far.css">
<link rel="alternate stylesheet" title="IDEA" href="styles/idea.css">
<link rel="alternate stylesheet" title="Sunburst" href="styles/sunburst.css">
<link rel="alternate stylesheet" title="Zenburn" href="styles/zenburn.css">
<link rel="alternate stylesheet" title="Visual Studio" href="styles/vs.css">
<link rel="alternate stylesheet" title="Ascetic" href="styles/ascetic.css">
<link rel="alternate stylesheet" title="Magula" href="styles/magula.css">
<link rel="alternate stylesheet" title="GitHub" href="styles/github.css">
<link rel="alternate stylesheet" title="Google Code" href="styles/googlecode.css">
<link rel="alternate stylesheet" title="Brown Paper" href="styles/brown_paper.css">
<link rel="alternate stylesheet" title="School Book" href="styles/school_book.css">
<link rel="alternate stylesheet" title="IR Black" href="styles/ir_black.css">
<link rel="alternate stylesheet" title="Solarized - Dark" href="styles/solarized_dark.css">
<link rel="alternate stylesheet" title="Solarized - Light" href="styles/solarized_light.css">
<link rel="alternate stylesheet" title="Arta" href="styles/arta.css">
<link rel="alternate stylesheet" title="Monokai" href="styles/monokai.css">
<style>
body {
font: small Arial, sans-serif;
}
h2 {
font: bold 100% Arial, sans-serif;
margin-top: 2em;
margin-bottom: 0.5em;
}
table {
width: 100%; padding: 0; border-collapse: collapse;
}
th {
width: 12em;
padding: 0; margin: 0;
}
td {
padding-bottom: 1em;
}
td, th {
vertical-align: top;
text-align: left;
}
pre {
margin: 0; font-size: medium;
}
#switch {
overflow: auto; width: 57em;
list-style: none;
padding: 0; margin: 0;
}
#switch li {
float: left; width: 10em;
padding: 0.1em; margin: 0.1em 1em 0.1em 0;
background: #EEE;
cursor: pointer;
}
#switch li.current {
background: #CCC;
font-weight: bold;
}
.test {
color: #888;
font-weight: normal;
margin: 2em 0 0 0;
}
.test var {
font-style: normal;
}
.passed {
color: green;
}
.failed {
color: red;
}
.code {
font: medium monospace;
}
.code .keyword {
font-weight: bold;
}
</style>
<script src="highlight.pack.js"></script>
<script>
hljs.tabReplace = ' ';
hljs.initHighlightingOnLoad();
</script>
<script>
// Stylesheet switcher © Vladimir Epifanov <voldmar@voldmar.ru>
(function(container_id) {
if (window.addEventListener) {
var attach = function(el, ev, handler) {
el.addEventListener(ev, handler, false);
}
} else if (window.attachEvent) {
var attach = function(el, ev, handler) {
el.attachEvent('on' + ev, handler);
}
} else {
var attach = function(el, ev, handler) {
ev['on' + ev] = handler;
}
}
attach(window, 'load', function() {
var current = null;
var info = {};
var links = document.getElementsByTagName('link');
var ul = document.createElement('ul')
for (var i = 0; (link = links[i]); i++) {
if (link.getAttribute('rel').indexOf('style') != -1
&& link.title) {
var title = link.title;
info[title] = {
'link': link,
'li': document.createElement('li')
}
ul.appendChild(info[title].li)
info[title].li.title = title;
info[title].link.disabled = true;
info[title].li.appendChild(document.createTextNode(title));
attach(info[title].li, 'click', (function (el) {
return function() {
current.li.className = '';
current.link.disabled = true;
current = el;
current.li.className = 'current';
current.link.disabled = false;
}})(info[title]));
}
}
current = info['Default']
current.li.className = 'current';
current.link.disabled = false;
ul.id = 'switch';
container = document.getElementById(container_id);
container.appendChild(ul);
});
})('styleswitcher');
</script>
<body>
<p>This is a demo/test page showing all languages supported by <a href="http://softwaremaniacs.org/soft/highlight/en/">highlight.js</a>.
Most snippets do not contain working code :-).
<div id="styleswitcher">
<h2>Styles</h2>
</div>
<h2>Automatically detected languages</h2>
<p id="summary">...</p>
<table id="autotest">
<tr>
<th>Python
<td class="python">
<pre>
<code>@requires_authorization
def somefunc(param1='', param2=0):
r'''A docstring'''
if param1 &gt; param2: # interesting
print 'Gre\'ater'
return (param2 - param1 + 1) or None
class SomeClass:<br> pass
</code></pre>
<tr>
<th>Python's profiler output
<td class="profile">
<pre><code> 261917242 function calls in 686.251 CPU seconds
ncalls tottime filename:lineno(function)
152824 513.894 {method 'sort' of 'list' objects}
129590630 83.894 rrule.py:842(__cmp__)
129590630 82.439 {cmp}
153900 1.296 rrule.py:399(_iter)
304393/151570 0.963 rrule.py:102(_iter_cached)
</code></pre>
<tr>
<th>Ruby
<td class="ruby">
<pre><code>class A &lt; B; def self.create(object = User) object end end
class Zebra; def inspect; "X#{2 + self.object_id}" end end
module ABC::DEF
include Comparable
# @param test
# @return [String] nothing
def foo(test)
Thread.new do |blockvar|
ABC::DEF.reverse(:a_symbol, :'a symbol' + 'test' + test)
end.join
end
def [](index) self[index] end
def ==(other) other == self end
end
anIdentifier = an_identifier
Constant = 1
</code></pre>
<tr>
<th>Perl
<td class="perl">
<pre><code># loads object
sub load
{
my $flds = $c-&gt;db_load($id,@_) || do {
Carp::carp "Can`t load (class: $c, id: $id): '$!'"; return undef
};
my $o = $c-&gt;_perl_new();
$id12 = $id / 24 / 3600;
$o-&gt;{'ID'} = $id12 + 123;
$o-&gt;{'PAPA'} = $flds-&gt;{'PAPA'};
#$o-&gt;{'SHCUT'} = $flds-&gt;{'SHCUT'};
my $p = $o-&gt;props;
my $vt;
$string =~ m/^sought_text$/;
$items = split //, 'abc';
for my $key (keys %$p)
{
if(${$vt.'::property'}) {
$o-&gt;{$key . '_real'} = $flds-&gt;{$key};
tie $o-&gt;{$key}, 'CMSBuilder::Property', $o, $key;
} else {
$o-&gt;{$key} = $flds-&gt;{$key};
$o->kill();
}
}
$o-&gt;save if delete $o-&gt;{'_save_after_load'};
return $o;
}
foreach my $num (0..$#array) {
# something
}
</code></pre>
<tr>
<th>PHP
<td class="php">
<pre><code>require_once 'Zend.php';
require_once 'Zend/Uri/Exception.php';
require_once 'Zend/Uri/Http.php';
require_once 'Zend/Uri/Mailto.php';
abstract class Zend_Uri
{
/**
* Return a string representation of this URI.
*
* @see getUri()
* @return string
*/
public function __toString()
{
return $this-&gt;getUri();
}
static public function factory($uri = 'http')
{
$uri = explode(':', $uri, 2);
$scheme = strtolower($uri[0]);
$schemeSpecific = isset($uri[1]) ? $uri[1] : '';
$desc = 'Multi
line description';
// Security check: $scheme is used to load a class file,
// so only alphanumerics are allowed.
if (!ctype_alnum($scheme)) {
throw new Zend_Uri_Exception('Illegal scheme');
}
}
}
__halt_compiler () ; datahere
datahere
datahere */
datahere
</code></pre>
<tr>
<th>Scala
<td class="scala">
<pre><code>object abstractTypes extends Application {
abstract class SeqBuffer {
type T; val element: Seq[T]; def length = element.length
}
}
/** Turn command line arguments to uppercase */
object Main {
def main(args: Array[String]) {
val res = for (a &lt;- args) yield a.toUpperCase
println("Arguments: " + res.toString)
}
}
/** Maps are easy to use in Scala. */
object Maps {
val colors = Map("red" -&gt; 0xFF0000,
"turquoise" -&gt; 0x00FFFF,
"black" -&gt; 0x000000,
"orange" -&gt; 0xFF8040,
"brown" -&gt; 0x804000)
def main(args: Array[String]) {
for (name &lt;- args) println(
colors.get(name) match {
case Some(code) =&gt;
name + " has code: " + code
case None =&gt;
"Unknown color: " + name
}
)
}
}
</code></pre>
<tr>
<th>Go
<td class="go">
<pre><code>package main
import (
"fmt"
"rand"
"os"
)
const (
Sunday = iota
Partyday
numberOfDays // this constant is not exported
)
type Foo interface {
FooFunc(int, float32) (complex128, []int)
}
// simple comment
type Bar struct {
os.File /* multi
line
comment */
PublicData chan int
}
func main() {
ch := make(chan int)
ch &lt;- 1
x, ok := &lt;- ch
ok = true
x = nil
float_var := 1.0e10
defer fmt.Println('\'')
defer fmt.Println(`exitting now\`)
var fv1 float64 = 0.75
go println(len("hello world!"))
return
}
</code></pre>
<tr>
<th>XML
<td class="xml">
<pre><code>&lt;?xml version="1.0"?&gt;
&lt;response value="ok" xml:lang="en"&gt;
&lt;text&gt;Ok&lt;/text&gt;
&lt;comment html_allowed="true"/&gt;
&lt;ns1:description&gt;&lt;![CDATA[
CDATA is &lt;not&gt; magical.
]]&gt;&lt;/ns1:description&gt;
&lt;a&gt;&lt;/a&gt; &lt;a/&gt;
&lt;/response&gt;
</code></pre>
<tr>
<th>HTML (with inline css and javascript)
<td class="xml">
<pre><code>&lt;!DOCTYPE html5&gt;
&lt;head&gt;
&lt;title&gt;Title&lt;/title&gt;
&lt;style&gt;
body {
width: 500px;
}
&lt;/style&gt;
&lt;script type="application/javascript"&gt;
function someFunction() {
return true;
}
&lt;/script&gt;
&lt;body&gt;
&lt;p class="something" id='12'&gt;Something&lt;/p&gt;
&lt;p class=something&gt;Something&lt;/p&gt;
&lt;!-- comment --&gt;
&lt;p class&gt;Something&lt;/p&gt;
&lt;p class="something" title="p"&gt;Something&lt;/p&gt;
&lt;/body&gt;
</code></pre>
<tr>
<th>Markdown
<td class="markdown">
<pre>
<code># hello world
you can write text [with links](http://example.com).
* one _thing_ has *em*phasis
* two __things__ are **bold**
---
hello world
===========
&lt;this_is inline="xml"&gt;&lt;/this_is&gt;
&gt; markdown is so cool
so are code segments
1. one thing (yeah!)
2. two thing `i can write code`, and `more` wipee!
</code></pre>
<tr>
<th>Django templates
<td class="django">
<pre><code>{% if articles|length %}
{% for article in articles %}
{# Striped table #}
&lt;tr class="{% cycle odd,even %}"&gt;
&lt;td&gt;{{ article|default:"Hi... "|escape }}&lt;/td&gt;
&lt;td {% if article.today %}class="today"{% endif %}&gt;{{ article.date|date:"d.m.Y" }}&lt;/td&gt;
&lt;/tr&gt;
{% endfor %}
{% endif %}
{% comment %}
Comments may be long and
multiline.
{% endcomment %}
</code></pre>
<tr>
<th>CSS
<td class="css">
<pre><code>body,
html {
font: Tahoma, Arial, san-serif;
background: url('hatch.png');
}
@import url('print.css');
@media screen and (-webkit-min-device-pixel-ratio: 0) {
body:first-of-type pre::after {
content: 'highlight: ' attr(class);
}
}
@page:right {
margin: 1cm 2cm 1.3cm 4cm;
}
@font-face {
font-family: Chunkfive;
src: url('Chunkfive.otf');
}
#content {
width: /* wide enough */ 100% /* 400px */;
height: 100%
}
p[lang=ru] {
color: #F0F0F0; background: white !important;
}
</code></pre>
<tr>
<th>JavaScript
<td class="javascript">
<pre><code>function $initHighlight(block) {
if (block.className.search(/\bno\-highlight\b/) != -1)
return false;
try {
blockText(block);
} catch (e) {
if (e == 'Complex markup')
return;
}//try
var classes = block.className.split(/\s+/);
for (var i = 0 / 2; i &lt; classes.length; i++) { // "0 / 2" should not be parsed as regexp start
if (LANGUAGES[classes[i]]) {
highlightLanguage(block, classes[i]);
return;
}//if
}//for
highlightAuto(block);
}//initHighlight</code></pre>
<tr>
<th>CoffeeScript
<td class="coffeescript">
<pre><code>grade = (student) -&gt;
if student.excellentWork
"A+"
else if student.okayStuff
if student.triedHard then "B" else "B-"
else
"C"
eldest = if 24 &gt; 21 then "Liz" else "Ike"
square = (x) -> x * x
two = -> 2
math =
root: Math.sqrt
square: square
cube: (x) -> x * square x
race = (winner, runners...) ->
print winner, runners
hi = `function() {
return [document.title, "Hello JavaScript"].join(": ");
}`
substr = "JavaScript numbers test #{ 010 / 0xf }"
heredoc = """
CoffeeScript numbers test #{ 010 / 0b10 }
"""
###
CoffeeScript Compiler v1.2.0
Released under the MIT License
###
OPERATOR = /// ^ (
?: [-=]> # function
| [-+*/%<>&|^!?=]= # compound assign / compare
| >>>=? # zero-fill right shift
| ([-+:])\1 # doubles
| ([&|<>])\2=? # logic / shift
| \?\. # soak access
| \.{2,3} # range or splat
) ///</code></pre>
<tr>
<th>ActionScript
<td class="actionscript">
<pre><code>package org.example.dummy {
import org.dummy.*;
/*define package inline interface*/
public interface IFooBarzable {
public function foo(... pairs):Array;
}
public class FooBar implements IFooBarzable {
static private var cnt:uint = 0;
private var bar:String;
//constructor
public function TestBar(bar:String):void {
bar = bar;
++cnt;
}
public function foo(... pairs):Array {
pairs.push(bar);
return pairs;
}
protected function includeTestFile():void {
include "Test.as";
}
}
}</code></pre>
<tr>
<th>VBScript
<td class="vbscript">
<pre><code>' creating configuration storage and initializing with default values
Set cfg = CreateObject("Scripting.Dictionary")
' reading ini file
for i = 0 to ubound(ini_strings)
s = trim(ini_strings(i))
' skipping empty strings and comments
if mid(s, 1, 1) &lt;&gt; "#" and len(s) &gt; 0 then
' obtaining key and value
parts = split(s, "=", -1, 1)
if ubound(parts)+1 = 2 then
parts(0) = trim(parts(0))
parts(1) = trim(parts(1))
' reading configuration and filenames
select case lcase(parts(0))
case "uncompressed""_postfix" cfg.item("uncompressed""_postfix") = parts(1)
case "f"
options = split(parts(1), "|", -1, 1)
if ubound(options)+1 = 2 then
' 0: filename, 1: options
ff.add trim(options(0)), trim(options(1))
end if
end select
end if
end if
next</code></pre>
<tr>
<th>Lua
<td class="lua">
<pre><code>--[[
Simple signal/slot implementation
]]
local signal_mt = {
__index = {
register = table.insert
}
}
function signal_mt.__index:emit(... --[[ Comment in params ]])
for _, slot in ipairs(self) do
slot(self, ...)
end
end
local function create_signal()
return setmetatable({}, signal_mt)
end
-- Signal test
local signal = create_signal()
signal:register(function (signal, ...)
print(...)
end)
signal:emit('Answer to Life, the Universe, and Everything:', 42)
--[==[ [=[ [[
Nested ]]
multi-line ]=]
comment ]==]
[==[ Nested
[=[ multi-line
[[ string
]] ]=] ]==]
</code></pre>
<tr>
<th>Delphi
<td class="delphi">
<pre><code>TList=Class(TObject)
Private
Some: String;
Public
Procedure Inside; // Suxx
End;{TList}
Procedure CopyFile(InFileName,var OutFileName:String);
Const
BufSize=4096; (* Huh? *)
Var
InFile,OutFile:TStream;
Buffer:Array[1..BufSize] Of Byte;
ReadBufSize:Integer;
Begin
InFile:=Nil;
OutFile:=Nil;
Try
InFile:=TFileStream.Create(InFileName,fmOpenRead);
OutFile:=TFileStream.Create(OutFileName,fmCreate);
Repeat
ReadBufSize:=InFile.Read(Buffer,BufSize);
OutFile.Write(Buffer,ReadBufSize);
Until ReadBufSize&lt;&gt;BufSize;
Log('File '''+InFileName+''' copied'#13#10);
Finally
InFile.Free;
OutFile.Free;
End;{Try}
End;{CopyFile}
</code></pre>
<tr>
<th>Java
<td class="java">
<pre><code>package l2f.gameserver.model;
import java.util.ArrayList;
/**
* Mother class of all character objects of the world (PC, NPC...)&lt;BR&gt;&lt;BR&gt;
*
*/
public abstract class L2Character extends L2Object
{
protected static final Logger _log = Logger.getLogger(L2Character.class.getName());
public static final Short ABNORMAL_EFFECT_BLEEDING = 0x0001; // not sure
public static final Short ABNORMAL_EFFECT_POISON = 0x0002;
public void detachAI() {
_ai = null;
//jbf = null;
if (1 &gt; 5) {
return;
}
}
public void moveTo(int x, int y, int z) {
moveTo(x, y, z, 0);
}
/** Task of AI notification */
@SuppressWarnings( { "nls", "unqualified-field-access", "boxing" })
public class NotifyAITask implements Runnable {
private final CtrlEvent _evt;
public void run() {
try {
getAI().notifyEvent(_evt, null, null);
} catch (Throwable t) {
_log.warning("Exception " + t);
t.printStackTrace();
}
}
}
}
</code></pre>
<tr>
<th>C++
<td class="cpp">
<pre><code>#include &lt;iostream&gt;
int main(int argc, char *argv[]) {
/* An annoying "Hello World" example */
for (auto i = 0; i &lt; 0xFFFF; i++)
cout &lt;&lt; "Hello, World!" &lt;&lt; endl;
char c = '\n';
unordered_map &lt;string, vector&lt;string&gt; &gt; m;
m["key"] = "\\\\"; // this is an error
return -2e3 + 12l;
}
</code></pre>
<tr>
<th>Objective C
<td class="objectivec">
<pre>
<code>
#import &lt;UIKit/UIKit.h&gt;
#import "Dependency.h"
@protocol WorldDataSource
@optional
- (NSString*)worldName;
@required
- (BOOL)allowsToLive;
@end
@interface Test : NSObject &lt;HelloDelegate, WorldDataSource&gt; {
NSString *_greeting;
}
@property (nonatomic, readonly) NSString *greeting;
- (IBAction) show;
@end
@implementation Test
@synthesize test=_test;
+ (id) test {
return [self testWithGreeting:@"Hello, world!\nFoo bar!"];
}
+ (id) testWithGreeting:(NSString*)greeting {
return [[[self alloc] initWithGreeting:greeting] autorelease];
}
- (id) initWithGreeting:(NSString*)greeting {
if ( (self = [super init]) ) {
_greeting = [greeting retain];
}
return self;
}
- (void) dealloc {
[_greeting release];
[super dealloc];
}
@end
</code></pre>
<tr>
<th>Vala
<td class="vala">
<pre><code>using DBus;
namespace Test {
class Foo : Object {
public signal void some_event (); // definition of the signal
public void method () {
some_event (); // emitting the signal (callbacks get invoked)
}
}
}
/* defining a class */
class Track : GLib.Object { /* subclassing 'GLib.Object' */
public double mass; /* a public field */
public double name { get; set; } /* a public property */
private bool terminated = false; /* a private field */
public void terminate() { /* a public method */
terminated = true;
}
}
const ALL_UPPER_CASE = "you should follow this convention";
var t = new Track(); // same as: Track t = new Track();
var s = "hello"; // same as: string s = "hello";
var l = new List&lt;int&gt;(); // same as: List&lt;int&gt; l = new List&lt;int&gt;();
var i = 10; // same as: int i = 10;
#if (ololo)
Regex regex = /foo/;
#endif
/*
* Entry point can be outside class
*/
void main () {
var long_string = """
Example of "verbatim string".
Same as in @"string" in C#
"""
var foo = new Foo ();
foo.some_event.connect (callback_a); // connecting the callback functions
foo.some_event.connect (callback_b);
foo.method ();
}
</code></pre>
<tr>
<th>C#
<td class="cs">
<pre><code>using System;
#pragma warning disable 414, 3021
public class Program
{
/// &lt;summary&gt;The entry point to the program.&lt;/summary&gt;
/// &lt;remarks&gt;
/// Using the Visual Studio style, the tags in this comment
/// should be grey, but this text should be green.
/// This comment should be green on the inside:
/// &lt;!-- I'm green! --&gt;
/// &lt;/remarks&gt;
public static int Main(string[] args)
{
Console.WriteLine("Hello, World!");
string s = @"This
""string""
spans
multiple
lines!";
return 0;
}
}
</code></pre>
<tr>
<th>RenderMan RSL
<td class="rsl">
<pre><code>#define TEST_DEFINE 3.14
/* plastic surface shader
*
* Pixie is:
* (c) Copyright 1999-2003 Okan Arikan. All rights reserved.
*/
surface plastic (float Ka = 1, Kd = 0.5, Ks = 0.5, roughness = 0.1;
color specularcolor = 1;) {
normal Nf = faceforward (normalize(N),I);
Ci = Cs * (Ka*ambient() + Kd*diffuse(Nf)) + specularcolor * Ks *
specular(Nf,-normalize(I),roughness);
Oi = Os;
Ci *= Oi;
}
</code></pre>
<tr>
<th>RenderMan RIB
<td class="rib">
<pre><code>FrameBegin 0
Display "Scene" "framebuffer" "rgb"
Option "searchpath" "shader" "+&amp;:/home/kew"
Option "trace" "int maxdepth" [4]
Attribute "visibility" "trace" [1]
Attribute "irradiance" "maxerror" [0.1]
Attribute "visibility" "transmission" "opaque"
Format 640 480 1.0
ShadingRate 2
PixelFilter "catmull-rom" 1 1
PixelSamples 4 4
Projection "perspective" "fov" 49.5502811377
Scale 1 1 -1
WorldBegin
ReadArchive "Lamp.002_Light/instance.rib"
Surface "plastic"
ReadArchive "Cube.004_Mesh/instance.rib"
# ReadArchive "Sphere.010_Mesh/instance.rib"
# ReadArchive "Sphere.009_Mesh/instance.rib"
ReadArchive "Sphere.006_Mesh/instance.rib"
WorldEnd
FrameEnd
</code></pre>
<tr>
<th>MEL (Maya Embedded Language)
<td class="mel">
<pre><code>proc string[] getSelectedLights()
{
string $selectedLights[];
string $select[] = `ls -sl -dag -leaf`;
for ( $shape in $select )
{
// Determine if this is a light.
//
string $class[] = getClassification( `nodeType $shape` );
if ( ( `size $class` ) &gt; 0 &amp;&amp; ( "light" == $class[0] ) )
{
$selectedLights[ `size $selectedLights` ] = $shape;
}
}
// Result is an array of all lights included in
// current selection list.
return $selectedLights;
}
</code></pre>
<tr>
<th>SQL
<td class="sql">
<pre><code>BEGIN;
CREATE TABLE "cicero_topic" (
"id" serial NOT NULL PRIMARY KEY,
"forum_id" integer NOT NULL,
"subject" varchar(255) NOT NULL,
"created" timestamp with time zone NOT NULL
);
ALTER TABLE "cicero_topic"
ADD CONSTRAINT forum_id_refs_id_4be56999
FOREIGN KEY ("forum_id")
REFERENCES "cicero_forum" ("id")
DEFERRABLE INITIALLY DEFERRED;
-- Initials
insert into "cicero_forum"
("slug", "name", "group", "ordering")
values
('test', 'Forum for te''sting', 'Test', 0);
-- Test
select count(*) from cicero_forum;
COMMIT;
</code></pre>
<tr>
<th>SmallTalk
<td class="smalltalk">
<pre><code>Object&gt;&gt;method: num
"comment 123"
| var1 var2 |
(1 to: num) do: [:i | |var| ^i].
Klass with: var1.
Klass new.
arr := #('123' 123.345 #hello Transcript var $@).
arr := #().
var2 = arr at: 3.
^ self abc
heapExample
"HeapTest new heapExample"
"Multiline
decription"
| n rnd array time sorted |
n := 5000.
"# of elements to sort"
rnd := Random new.
array := (1 to: n)
collect: [:i | rnd next].
"First, the heap version"
time := Time
millisecondsToRun: [sorted := Heap withAll: array.
1
to: n
do: [:i |
sorted removeFirst.
sorted add: rnd next]].
Transcript cr; show: 'Time for Heap: ' , time printString , ' msecs'.
"The quicksort version"
time := Time
millisecondsToRun: [sorted := SortedCollection withAll: array.
1
to: n
do: [:i |
sorted removeFirst.
sorted add: rnd next]].
Transcript cr; show: 'Time for SortedCollection: ' , time printString , ' msecs'
</code></pre>
<tr>
<th>Lisp
<td class="lisp">
<pre><code>(defun prompt-for-cd ()
"Prompts
for CD"
(prompt-read "Title" 1.53 1 2/4 1.7 1.7e0 2.9E-4 +42 -7 #b001 #b001/100 #o777 #O777 #xabc55 #c(0 -5.6))
(prompt-read "Artist" &amp;rest)
(or (parse-integer (prompt-read "Rating") :junk-allowed t) 0)
(if x (format t "yes") (format t "no" nil) ;and here comment
)
;; second line comment
'(+ 1 2)
(defvar *lines*) ; list of all lines
(position-if-not #'sys::whitespacep line :start beg))
(quote (privet 1 2 3))
'(hello world)
(* 5 7)
(1 2 34 5)
(:use "aaaa")
(let ((x 10) (y 20))
(print (+ x y))
)</code></pre>
<tr>
<th>Ini file
<td class="ini">
<pre><code>;Settings relating to the location and loading of the database
[Database]
ProfileDir=.
ShowProfileMgr=smart
Profile1_Name[] = "\|/_-=MegaDestoyer=-_\|/"
DefaultProfile=True
AutoCreate = no
[AutoExec]
Use="prompt"
Glob=autoexec_*.ini
AskAboutIgnoredPlugins=0
</code></pre>
<tr>
<th>Apache
<td class="apache">
<pre><code># rewrite`s rules for wordpress pretty url
LoadModule rewrite_module modules/mod_rewrite.so
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [NC,L]
ExpiresActive On
ExpiresByType application/x-javascript "access plus 1 days"
&lt;Location /maps/&gt;
RewriteMap map txt:map.txt
RewriteMap lower int:tolower
RewriteCond %{REQUEST_URI} ^/([^/.]+)\.html$ [NC]
RewriteCond ${map:${lower:%1}|NOT_FOUND} !NOT_FOUND
RewriteRule .? /index.php?q=${map:${lower:%1}} [NC,L]
&lt;/Location&gt;
</code></pre>
<tr>
<th>nginx
<td class="nginx">
<pre><code>user www www;
worker_processes 2;
pid /var/run/nginx.pid;
error_log /var/log/nginx.error_log debug | info | notice | warn | error | crit;
events {
connections 2000;
use kqueue | rtsig | epoll | /dev/poll | select | poll;
}
http {
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$gzip_ratio"';
send_timeout 3m;
client_header_buffer_size 1k;
gzip on;
gzip_min_length 1100;
#lingering_time 30;
server {
listen one.example.com;
server_name one.example.com www.one.example.com;
access_log /var/log/nginx.access_log main;
location / {
proxy_pass http://127.0.0.1/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
charset koi8-r;
}
location ~* \.(jpg|jpeg|gif)$ {
root /spool/www;
}
}
}
</code></pre>
<tr>
<th>Diff
<td class="diff">
<pre><code>Index: languages/ini.js
===================================================================
--- languages/ini.js (revision 199)
+++ languages/ini.js (revision 200)
@@ -1,8 +1,7 @@
hljs.LANGUAGES.ini =
{
case_insensitive: true,
- defaultMode:
- {
+ defaultMode: {
contains: ['comment', 'title', 'setting'],
illegal: '[^\\s]'
},
*** /path/to/original timestamp
--- /path/to/new timestamp
***************
*** 1,3 ****
--- 1,9 ----
+ This is an important
+ notice! It should
+ therefore be located at
+ the beginning of this
+ document!
! compress the size of the
! changes.
It is important to spell
</code></pre>
<tr>
<th>DOS batch files
<td class="dos">
<pre><code>cd \
copy a b
ping 192.168.0.1
@rem ping 192.168.0.1
net stop sharedaccess
del %tmp% /f /s /q
del %temp% /f /s /q
ipconfig /flushdns
taskkill /F /IM JAVA.EXE /T
cd Photoshop/Adobe Photoshop CS3/AMT/
if exist application.sif (
ren application.sif _application.sif
) else (
ren _application.sif application.sif
)
taskkill /F /IM proquota.exe /T
sfc /SCANNOW
set path = test
xcopy %1\*.* %2
</code></pre>
<tr>
<th>Bash
<td class="bash">
<pre><code>#!/bin/bash
###### BEGIN CONFIG
ACCEPTED_HOSTS="/root/.hag_accepted.conf"
BE_VERBOSE=false
###### END CONFIG
if [ "$UID" -ne 0 ]
then
echo "Superuser rights is required"
echo 'Printing the # sign'
exit 2
fi
genApacheConf(){
if [[ "$2" = "www" ]]
then
full_domain=$1
else
full_domain=$2.$1
fi
host_root="${APACHE_HOME_DIR}$1/$2"
echo -e "# Host $1/$2 :"
}
</code></pre>
<tr>
<th>CMake
<td class="cmake">
<pre><code>project(test)
cmake_minimum_required(VERSION 2.6)
# IF LINUX
if (${CMAKE_SYSTEM_NAME} MATCHES Linux)
message("\nOS:\t\tLinux")
endif()
# IF WINDOWS
if (${CMAKE_SYSTEM_NAME} MATCHES Windows)
message("\nOS:\t\tWindows")
endif()
set(test test0.cpp test1.cpp test2.cpp)
include_directories(./)
set(EXECUTABLE_OUTPUT_PATH ../bin)
add_subdirectory(src)
add_executable(test WIN32 ${test})
target_link_libraries(test msimg32)
</code></pre>
<tr>
<th>Axapta
<td class="axapta">
<pre><code>class ExchRateLoadBatch extends RunBaseBatch {
ExchRateLoad rbc;
container currencies;
boolean actual;
boolean overwrite;
date beg;
date end;
#define.CurrentVersion(5)
#localmacro.CurrentList
currencies,
actual,
beg,
end
#endmacro
}
public boolean unpack(container packedClass) {
container base;
boolean ret;
Integer version = runbase::getVersion(packedClass);
switch (version) {
case #CurrentVersion:
[version, #CurrentList] = packedClass;
return true;
default:
return false;
}
return ret;
}
</code></pre>
<tr>
<th>1С
<td class="1c">
<pre><code>
#Если Клиент Тогда
Перем СимвольныйКодКаталога = "ля-ля-ля"; //комментарий
Функция Сообщить(Знач ТекстСообщения, ТекстСообщения2) Экспорт //комментарий к функции
x=ТекстСообщения+ТекстСообщения2+"
|строка1
|строка2
|строка3";
КонецФункции
#КонецЕсли
// Процедура ПриНачалеРаботыСистемы
//
Процедура ПриНачалеРаботыСистемы()
Обработки.Помощник.ПолучитьФорму("Форма").Открыть();
d = '21.01.2008'
КонецПроцедуры
</code></pre>
<tr>
<th>AVR Assembler
<td class="avrasm">
<pre><code>;* Title: Block Copy Routines
;* Version: 1.1
.include "8515def.inc"
rjmp RESET ;reset handle
.def flashsize=r16 ;size of block to be copied
flash2ram:
lpm ;get constant
st Y+,r0 ;store in SRAM and increment Y-pointer
adiw ZL,1 ;increment Z-pointer
dec flashsize
brne flash2ram ;if not end of table, loop more
ret
.def ramtemp =r1 ;temporary storage register
.def ramsize =r16 ;size of block to be copied
</code></pre>
<tr>
<th>VHDL
<td class="vhdl">
<pre><code>------------------------------------
-- RS Trigger with Assynch. Reset --
------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.all;
entity RS_AR is
generic (T: Time := 0ns);
port(
-- Default RS Trigger
R : in STD_LOGIC;
S : in STD_LOGIC;
Q : out STD_LOGIC;
nQ : out STD_LOGIC;
-- Special Input Signals
AR : in STD_LOGIC; -- assynch. reset
C : in STD_LOGIC -- synch. signal
);
end RS_AR;
architecture RS_AR of RS_AR is
signal QT: std_logic; -- Q(t)
begin
process(C, AR) is
subtype RS is std_logic_vector ( 1 downto 0 );
begin
if AR='0' then
QT &lt;= '0';
else
if rising_edge(C) then
if not (R'stable(T) and S'stable(T)) then
QT &lt;= 'X';
else
case RS'(R&amp;S) is
when "01" =&gt; QT &lt;= '1';
when "10" =&gt; QT &lt;= '0';
when "11" =&gt; QT &lt;= 'X';
when others =&gt; null;
end case;
end if;
end if;
end if;
end process;
Q &lt;= QT;
nQ &lt;= not QT;
end RS_AR;
</code></pre>
<tr>
<th>Parser 3
<td class="parser3">
<pre><code>@CLASS
base
@USE
module.p
@BASE
class
# Comment for code
@create[aParam1;aParam2][local1;local2]
^connect[mysql://host/database?ClientCharset=windows-1251]
^for[i](1;10){
&lt;p class=&quot;paragraph&quot;&gt;^eval($i+10)&lt;/p&gt;
^connect[mysql://host/database]{
$tab[^table::sql{select * from `table` where a='1'}]
$var_Name[some${value}]
}
}
^rem{
Multiline comment with code: $var
^while(true){
^for[i](1;10){
^sleep[]
}
}
}
^taint[^#0A]
@GET_base[]
## Comment for code
# Isn't comment
$result[$.hash_item1[one] $.hash_item2[two]]
</code></pre>
<tr>
<th>TeX
<td class="tex">
<pre>
<code>\documentclass{article}
\usepackage[koi8-r]{inputenc}
\hoffset=0pt
\voffset=.3em
\tolerance=400
\newcommand{\eTiX}{\TeX}
\begin{document}
\section*{Highlight.js}
\begin{table}[c|c]
$\frac 12\, + \, \frac 1{x^3}\text{Hello \! world}$ &amp; \textbf{Goodbye\~ world} \\\eTiX $ \pi=400 $
\end{table}
Ch\'erie, \c{c}a ne me pla\^\i t pas! % comment \b
G\"otterd\"ammerung~45\%=34.
$$
\int\limits_{0}^{\pi}\frac{4}{x-7}=3
$$
\end{document}
</code></pre>
<tr>
<th>Haskell
<td class="haskell">
<pre>
<code>module Shapes
( Point(..) ,
Shape(..) ,
surface ,
baseCircle ,
baseRect
) where
-- Single line comment
{-
multi
line
comment
-}
data Point = Point Float Float deriving (Show)
data Shape = Circle Point Float | Rectangle Point Point deriving (Show)
surface :: Shape -> Float
surface (Circle _ r) = pi * r^2
surface (Rectangle (Point x1 y1) (Point x2 y2)) = (abs $ x2 - x1) * (abs $ y2 - y1)
baseCircle :: Float -> Shape
baseCircle r = Circle(Point 0 0) r
baseRect :: Float -> Float -> Shape
baseRect w h = Rectangle (Point 0 0) (Point w h)
</code></pre>
<tr>
<th>Erlang
<td class="erlang">
<pre><code>-module(ssh_cli).
-behaviour(ssh_channel).
-include("ssh.hrl").
%% backwards compatibility
-export([listen/1, listen/2, listen/3, listen/4, stop/1]).
%% state
-record(state, {
cm,
channel
}).
test(Foo)->Foo.
init([Shell, Exec]) ->
{ok, #state{shell = Shell, exec = Exec}};
init([Shell]) ->
false = not true,
io:format("Hello, \"~p!~n", [atom_to_list('World')]),
{ok, #state{shell = Shell}}.
concat([Single]) -> Single;
concat(RList) ->
EpsilonFree = lists:filter(
fun (Element) ->
case Element of
epsilon -> false;
_ -> true
end
end,
RList),
case EpsilonFree of
[Single] -> Single;
Other -> {concat, Other}
end.
union_dot_union({union, _}=U1, {union, _}=U2) ->
union(lists:flatten(
lists:map(
fun (X1) ->
lists:map(
fun (X2) ->
concat([X1, X2])
end,
union_to_list(U2)
)
end,
union_to_list(U1)
))).
</code></pre>
<tr>
<th>Erlang REPL
<td class="erlang_repl">
<pre><code>1> Str = "abcd".
"abcd"
2> L = test:length(Str).
4
3> Descriptor = {L, list_to_atom(Str)}.
{4,abcd}
4> L.
4
5> b().
Descriptor = {4,abcd}
L = 4
Str = "abcd"
ok
6> f(L).
ok
7> b().
Descriptor = {4,abcd}
Str = "abcd"
ok
8> {L, _} = Descriptor.
{4,abcd}
9> L.
4
10> 2#101.
5
11> 1.85e+3.
1850
</code></pre>
<tr>
<th>Rust
<td class="rust">
<pre>
<code>use std;
import std::io;
export fac, test1;
123; // type int
123u; // type uint
123_u; // type uint
0xff00; // type int
0xff_u8; // type u8
0b1111_1111_1001_0000_i32; // type i32
123.0; // type float
0.1; // type float
3f; // type float
0.1f32; // type f32
12E+99_f64; // type f64
/* Factorial */
fn fac(n: int) -> int {
let s: str = "This is
a multi-line string.
It ends with an unescaped '\"'.";
let c: char = 'Ф';
let result = 1, i = 1;
while i <= n { // No parens around the condition
result *= i;
i += 1;
}
ret result;
}
pure fn pure_length&lt;T>(ls: list&lt;T>) -> uint { /* ... */ }
type t = map::hashtbl&lt;int,str>;
let x = id::&lt;int>(10);
// Define some modules.
#[path = "foo.rs"]
mod foo;
iface seq&lt;T> {
fn len() -> uint;
}
impl &lt;T> of seq&lt;T> for [T] {
fn len() -> uint { vec::len(self) }
fn iter(b: fn(T)) {
for elt in self { b(elt); }
}
}
enum list&lt;T> {
nil;
cons(T, @list&lt;T>);
}
let a: list&lt;int> = cons(7, @cons(13, @nil));
</code></pre>
<tr>
<th>Matlab
<td class="matlab">
<pre><code>n = 20; % number of points
points = [random('unid', 100, n, 1), random('unid', 100, n, 1)];
len = zeros(1, n - 1);
points = sortrows(points);
%% Initial set of points
plot(points(:,1),points(:,2));
for i = 1: n-1
len(i) = points(i + 1, 1) - points(i, 1);
end
while(max(len) > 2 * min(len))
[d, i] = max(len);
k = on_margin(points, i, d, -1);
m = on_margin(points, i + 1, d, 1);
xm = 0; ym = 0;
%% New point
if(i == 1 || i + 1 == n)
xm = mean(points([i,i+1],1))
ym = mean(points([i,i+1],2))
else
[xm, ym] = dlg1(points([k, i, i + 1, m], 1), ...
points([k, i, i + 1, m], 2))
end
points = [ points(1:i, :); [xm, ym]; points(i + 1:end, :)];
end
function [net] = get_fit_network(inputs, targets)
% Create Network
numHiddenNeurons = 20; % Adjust as desired
net = newfit(inputs,targets,numHiddenNeurons);
net.trainParam.goal = 0.01;
net.trainParam.epochs = 1000;
% Train and Apply Network
[net,tr] = train(net,inputs,targets);
end
</code></pre>
</table>
<script>
function testDetection() {
if (!hljs.initHighlighting.called) {
window.setTimeout(testDetection, 500);
return;
}
var table = document.getElementById('autotest');
var tds = table.getElementsByTagName('TD');
var failed = [];
for (var i = 0; i < tds.length; i++) {
var tdClass = tds[i].className;
if (!hljs.LANGUAGES.hasOwnProperty(tdClass)) {
tds[i].parentNode.style.display = 'none';
continue;
}
var code = tds[i].getElementsByTagName('CODE')[0];
var passed = tdClass == code.className;
var result = document.createElement('DIV');
result.className = 'test';
result.innerHTML = '<var class="'+ (passed ? 'passed' : 'failed') +'">' + code.className + '</var>';
function counts(r) {
return ' (' + r.kw + '+' + r.re + '=' + (r.kw + r.re) + ')';
}
result.innerHTML += counts(code.result);
if (code.second_best) {
result.innerHTML += '<br>' + code.second_best.language +
counts(code.second_best) ;
}
tds[i].parentNode.getElementsByTagName('th')[0].appendChild(result);
if (!passed) {
failed.push(tdClass);
}
}
var summary = document.getElementById('summary');
summary.innerHTML = failed.length ? ('Failed tests: ' + failed.join(', ')) : 'All tests passed';
summary.className = failed.length ? 'failed' : 'passed';
}
testDetection();
</script>
<h2>Special tests</h2>
<table>
<tr>
<th>Explicit Python highlighting
<td>
<pre><code class="python">for x in [1, 2, 3]:
count(x)
</code></pre>
<tr>
<th>Language set on &lt;pre&gt;
<td>
<pre class="python"><code>for x in [1, 2, 3]:
count(x)
</code></pre>
<tr>
<th>HTML5-style language class (language-python)
<td>
<pre><code class="language-python">for x in [1, 2, 3]:
count(x)
</code></pre>
<tr>
<th>Replacing TAB with 4 spaces
<td>
<pre><code class="python">for x in [1, 2, 3]:
count(x)
</code></pre>
<tr>
<th>Custom markup
<td>
<pre><code>&lt;<a href="http://dev.w3.org/html5/spec/Overview.html#the-div-element">div</a> id="contents"&gt;
<del>&lt;p&gt;Hello, World!</del><!-- A comment should not break merging --><ins>Goodbye, cruel world!</ins>
&lt;/div&gt;
</code></pre>
<tr>
<th>Custom markup + TAB replacement
<td>
<pre><code class="python">for x in [1, 2, 3]:
<span style="background:yellow"> </span>count(x)
if x == 3:
<span style="background:yellow"> </span>count(x + 1)
</code></pre>
<tr>
<th>Non-pre container
<td>
<div id="codecontainer" class="code">for x in [1, 2, 3]:<br>
&nbsp;&nbsp;count(x)<br>
</div>
<script>hljs.highlightBlock(document.getElementById('codecontainer'), null, true);</script>
<tr>
<th>Disabled highlighting
<td>
<pre><code class="no-highlight">&lt;div id="contents"&gt;
&lt;p&gt;Hello, World!
&lt;/div&gt;
</code></pre>
</table>