Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Homepage "compute pi" example: Dart sources, tests, and HTML-version generator #448

Merged
merged 7 commits into from
Nov 30, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions examples/lib/pi_monte_carlo.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// ignore_for_file: type_annotate_public_apis
// Note: this DartPad version has a few extra lines of code,
// marked "web-only", to make the sample execution nicer on the web
// (approximations of π are added to the DOM in addition to being
// printed on the console).

import 'dart:async'; //!tip("import")
import 'dart:html'; //!web-only
import 'dart:math' show Random; //!tip("dart:math")
//!web-only
int numIterations = 500; //!web-only

main() async { //!tip("main()")
print('Compute π using the Monte Carlo method.'); //!tip("π")
var output = querySelector("#value-of-pi"); //!web-only
await for (var estimate in computePi().take(numIterations)) { //!tip("await")
print('π ≅ $estimate'); //!tip("$estimate")
output.text = estimate.toStringAsFixed(5); //!web-only
await window.animationFrame; //!web-only
}
}

/// Generates a stream of increasingly accurate estimates of π. //!tip("///")
Stream<double> computePi({int batch: 100000}) async* { //!tip("async*") //!tip("{int batch: 100000}") //!tip("<double>")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was the change from batch of 1M to 100K intentional? No problem either way, just checking.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was to match the original sources in the published DartPad: https://dartpad.dartlang.org/fb763a4a770b5cdd896982e10ccf4118

var total = 0; //!tip("var")
var count = 0;
while (true) { //!tip("while (true)")
var points = generateRandom().take(batch); //!tip("take")
var inside = points.where((p) => p.isInsideUnitCircle); //!tip("=>")
total += batch;
count += inside.length; //!tip("length")
var ratio = count / total;
// Area of a circle is A = π⋅r², therefore π = A/r².
// So, when given random points with x ∈ <0,1>,
// y ∈ <0,1>, the ratio of those inside a unit circle
// should approach π / 4. Therefore, the value of π
// should be:
yield ratio * 4; //!tip("yield")
}
}

Iterable<Point> generateRandom([int seed]) sync* { //!tip("sync*") //!tip("[int seed]") //!tip("Iterable")
final random = new Random(seed); //!tip("final")
while (true) {
yield new Point(random.nextDouble(), random.nextDouble()); //!tip("yield")
}
}

class Point { //!tip("class")
final double x, y; //!tip("double")
const Point(this.x, this.y); //!tip("this.x") //!tip("const")
bool get isInsideUnitCircle => x * x + y * y <= 1; //!tip("get")
}

28 changes: 28 additions & 0 deletions examples/lib/pi_monte_carlo_tooltips.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<ul class="fp-tooltips" style="display: none">
<li name="import">Dart has one canonical way to import libraries, and one canonical (and easy) way to install library packages.</li>
<li name="dart:math">The whole standard library is meticulously maintained. It has been called “well-crafted” by none other than Erik Meijer.</li>
<li name="main()">The main() function is the single point of entry.</li>
<li name="π">Unicode support is baked in.</li>
<li name="await">Language-level asynchrony support makes you more productive when dealing with deeply asynchronous code (like most UI code, for example).</li>
<li name="$estimate">String interpolation is easy. Just put <code>${expression}</code> or <code>$variable</code> in your string literal.</li>
<li name="///">Add doc comments like this to flesh out the API reference docs that the SDK’s dartdoc tool generates.</li>
<li name="<double>">Generics are optional but extremely useful in large codebases.</li>
<li name="{int batch: 100000}">Named parameters make call sites more readable.</li>
<li name="async*">Dart has language-level support for asynchronous generators.</li>
<li name="var">The type is inferred in this variable declaration. Note: no JavaScript-style hoisting.</li>
<li name="while (true)">Because generators are lazy, we can safely do this.</li>
<li name="take">Synchronous generators produce (lazy) Iterables, and Iterables have a well-crafted API.</li>
<li name="=>">The optional arrow syntax makes simple functions more readable.</li>
<li name="length">Since the Iterable is lazy, the program doesn’t actually iterate over it until it’s needed by the length getter. No new array will be constructed.</li>
<li name="yield">In an async generator, yield takes care of sending the values through the stream (including the logic of suspending execution when needed).</li>
<li name="Iterable">Iterable is a core type extended by all iterable collections, which makes for some elegant Dart code.</li>
<li name="[int seed]">Optional parameters make call sites cleaner.</li>
<li name="sync*">Dart has language-level support for synchronous generators, too.</li>
<li name="final">Variables and fields can be final. Any attempt to change them later in the code will produce a static error.</li>
<li name="yield">Producing lazy Iterables through yield is readable and corresponds nicely with the same concept in asynchronous generators.</li>
<li name="class">Dart is purely object-oriented and class-based, with mixin-based inheritance.</li>
<li name="double">Although Dart can compile to JavaScript, it doesn’t lack the distinction between double and int.</li>
<li name="const">Constructors can be constant.</li>
<li name="this.x">Initializing fields through this shorthand syntax is both easier and more readable.</li>
<li name="get">Language-level support for getters means you can freely switch between properties and methods without changing the API.</li>
</ul>
36 changes: 36 additions & 0 deletions examples/test/pi_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
@Tags(const ['browser'])
@TestOn('browser')
import 'dart:html';
import 'package:test/test.dart';
import 'package:examples/pi_monte_carlo.dart' as mc_pi;

void main() {
test('pi', () async {
const numIterations = 10;
const expectedNumOutputLines = //
1 + // for the 'Compute π...' heading
numIterations + // lines 'π ≅ ...'
1; // for the trailing \n

final html = '''
<h1>π ≅ <span id="value-of-pi">?</span></h1>
''';
document.body.appendHtml(html);

// Run as async function to capture printed output.
expect(() async {
mc_pi.numIterations = numIterations;
await mc_pi.main();
var pi = querySelector('#value-of-pi') as SpanElement;
expect(pi.text, startsWith('3.'));
},
prints(allOf([
contains('Compute π using the Monte Carlo method.'),
contains('π ≅ 3.'),
predicate<String>((consoleOutput) {
final lines = consoleOutput.split('\n');
return lines.length == expectedNumOutputLines;
}, 'output $expectedNumOutputLines lines'),
])));
});
}
1 change: 1 addition & 0 deletions scripts/analyze-and-test-examples.sh
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ echo Running browser tests ...
$TEST --tags browser --platform chrome \
test/language_tour/browser_test.dart \
test/library_tour/html_test.dart \
test/pi_test.dart \
| tee $LOG_FILE | $FILTER1 | $FILTER2 "$FILTER_ARG"
LOG=$(grep 'All tests passed!' $LOG_FILE)
if [[ -z "$LOG" ]]; then EXIT_STATUS=1; fi
Expand Down
94 changes: 94 additions & 0 deletions scripts/create_site_main_example.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import 'dart:io';
import 'dart:convert' show HtmlEscape, HtmlEscapeMode;
import 'package:html_unescape/html_unescape.dart';
import 'package:logging/logging.dart';

final Logger _log = new Logger('');

final warning = '''{%- comment %}
WARNING: Do NOT EDIT this file directly. It is autogenerated by
${Platform.script.path.replaceFirst(new RegExp(r'^.*site-www/'), '')}
from sources in the example folder.
{% endcomment -%}
''';

void main() {
// Logger.root.level = Level.ALL;
Logger.root.onRecord.listen((LogRecord rec) => print('>> ${rec.message}'));

final mainExampleSrcAsHtmlWithTips = new Main().getSrcHtmlWithTips();

final html = [
warning,
'<pre class="prettyprint">\n',
mainExampleSrcAsHtmlWithTips.join('\n'),
'</pre>\n'
].join('');
new File('../src/_main-example.html').writeAsStringSync(html);
}

class Main {
final HtmlEscape _htmlEscape =
new HtmlEscape(new HtmlEscapeMode(escapeLtGt: true));
final HtmlUnescape _htmlUnescape = new HtmlUnescape();
final tipRegExp = new RegExp(r'^(.*?) //!tip\("([^"]+)"\)$');
final tooltips = _getTooltips();

int indexOfNextTooltip = 0;

Iterable<String> getSrcHtmlWithTips() =>
getMainExampleSrcLines().map(processTipInstruction);

/// Side-effect: increments [indexOfNextTooltip] as it processes tips.
String processTipInstruction(String line) {
_log.fine(line);
line = htmlEscape(line);

while (line.contains('//!tip(')) {
var match = tipRegExp.firstMatch(line);
if (match == null) throw 'Tip instruction match failed for line: $line';
final lineWithoutTipInstruction = match[1],
anchor = _htmlUnescape.convert(match[2]),
tooltip = tooltips[indexOfNextTooltip],
tooltipAnchor = tooltip[0],
tooltipText = tooltip[1];
indexOfNextTooltip += 1;
if (tooltipAnchor != anchor)
throw 'Expected tip for $anchor, but instead found tip for ${tooltip[0]}. Aborting.';
final escapedAnchor = htmlEscape(anchor);
_log.fine(' ** Replacing "$escapedAnchor" with span');
line = lineWithoutTipInstruction.replaceFirst(escapedAnchor,
'<span class="frontpage-highlight" data-text="$tooltipText">$escapedAnchor</span>');
}
return line;
}

String htmlEscape(String s) => _htmlEscape.convert(s);
}

Iterable<String> getMainExampleSrcLines() {
final _mainExampleFile = '../examples/lib/pi_monte_carlo.dart';
return new File(_mainExampleFile)
.readAsLinesSync()
.skipWhile((line) => !line.startsWith('import')) // initial comment block
.where((line) => !line.contains('web-only'))
.map((line) => line.replaceFirst('numIterations', '500'));
}

List<List<String>> _getTooltips() {
final _tooltipFile = '../examples/lib/pi_monte_carlo_tooltips.html';
final _tooltipLineRE = new RegExp(r'^\s*<li name="(.*?)">(.*)</li>');

// Read tooltips.
return new File(_tooltipFile)
.readAsLinesSync()
.where((line) => line.contains('<li'))
.map((line) {
final match = _tooltipLineRE.firstMatch(line);

return [
match[1], // anchor text, e.g. "import"
match[2], // tooltip HTML
];
}).toList();
}
22 changes: 3 additions & 19 deletions scripts/dartfmt.sh
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,9 @@ cd `dirname $0`/..
DARTFMT="dartfmt -w"
EXAMPLES=examples

# Format all example source files using default settings:
$DARTFMT -w $EXAMPLES

# Re-run dartfmt with custom settings for the few files that need it:
$DARTFMT -l 60 \
examples/language_tour/color/bin/main.dart \
examples/language_tour/factory-constructor/bin/main.dart \
examples/language_tour/mixins/bin/main.dart \
examples/language_tour/no-such-method/bin/main.dart \
examples/language_tour/optional-positional-parameter-default/bin/main.dart \
examples/language_tour/reference/immutable_point.dart \
examples/language_tour/string-interpolation/bin/main.dart

$DARTFMT -l 62 examples/language_tour/flow/exceptions/web/main.dart

$DARTFMT -l 75 examples/language_tour/flow/break-continue/web/main.dart

# New code
# Format all example source files under lib and tests
# except for the lib/pi_*.* files
$DARTFMT -w $EXAMPLES/lib/[^p] $EXAMPLES/test

$DARTFMT -l 60 \
examples/lib/language_tour/classes/immutable_point.dart \
Expand All @@ -46,7 +31,6 @@ $DARTFMT -l 65 \
examples/test/library_tour/io_test.dart \
examples/test/library_tour/mirrors_test.dart


# If any files were changed, then exit 1:
REFORMATTED_FILES=$(git status --short)
echo
Expand Down
11 changes: 5 additions & 6 deletions scripts/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
name: site_scripts
description: Utility scripts
dependencies:
http: any
path: any

#dependencies:
# js: any
# unittest: any
dependencies:
html_unescape: ^0.1.5
http: ^0.11.3+16
logging: ^0.11.3+1
path: ^1.4.0
48 changes: 48 additions & 0 deletions src/_main-example.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
{%- comment %}
WARNING: Do NOT EDIT this file directly. It is autogenerated by
scripts/create_site_main_example.dart
from sources in the example folder.
{% endcomment -%}
<pre class="prettyprint">
<span class="frontpage-highlight" data-text="Dart has one canonical way to import libraries, and one canonical (and easy) way to install library packages.">import</span> 'dart:async';
import '<span class="frontpage-highlight" data-text="The whole standard library is meticulously maintained. It has been called “well-crafted” by none other than Erik Meijer.">dart:math</span>' show Random;

<span class="frontpage-highlight" data-text="The main() function is the single point of entry.">main()</span> async {
print('Compute <span class="frontpage-highlight" data-text="Unicode support is baked in.">π</span> using the Monte Carlo method.');
<span class="frontpage-highlight" data-text="Language-level asynchrony support makes you more productive when dealing with deeply asynchronous code (like most UI code, for example).">await</span> for (var estimate in computePi().take(500)) {
print('π ≅ <span class="frontpage-highlight" data-text="String interpolation is easy. Just put <code>${expression}</code> or <code>$variable</code> in your string literal.">$estimate</span>');
}
}

<span class="frontpage-highlight" data-text="Add doc comments like this to flesh out the API reference docs that the SDK’s dartdoc tool generates.">///</span> Generates a stream of increasingly accurate estimates of π.
Stream<span class="frontpage-highlight" data-text="Generics are optional but extremely useful in large codebases.">&lt;double&gt;</span> computePi(<span class="frontpage-highlight" data-text="Named parameters make call sites more readable.">{int batch: 100000}</span>) <span class="frontpage-highlight" data-text="Dart has language-level support for asynchronous generators.">async*</span> {
<span class="frontpage-highlight" data-text="The type is inferred in this variable declaration. Note: no JavaScript-style hoisting.">var</span> total = 0;
var count = 0;
<span class="frontpage-highlight" data-text="Because generators are lazy, we can safely do this.">while (true)</span> {
var points = generateRandom().<span class="frontpage-highlight" data-text="Synchronous generators produce (lazy) Iterables, and Iterables have a well-crafted API.">take</span>(batch);
var inside = points.where((p) <span class="frontpage-highlight" data-text="The optional arrow syntax makes simple functions more readable.">=&gt;</span> p.isInsideUnitCircle);
total += batch;
count += inside.<span class="frontpage-highlight" data-text="Since the Iterable is lazy, the program doesn’t actually iterate over it until it’s needed by the length getter. No new array will be constructed.">length</span>;
var ratio = count / total;
// Area of a circle is A = π⋅r², therefore π = A/r².
// So, when given random points with x ∈ &lt;0,1&gt;,
// y ∈ &lt;0,1&gt;, the ratio of those inside a unit circle
// should approach π / 4. Therefore, the value of π
// should be:
<span class="frontpage-highlight" data-text="In an async generator, yield takes care of sending the values through the stream (including the logic of suspending execution when needed).">yield</span> ratio * 4;
}
}

<span class="frontpage-highlight" data-text="Iterable is a core type extended by all iterable collections, which makes for some elegant Dart code.">Iterable</span>&lt;Point&gt; generateRandom(<span class="frontpage-highlight" data-text="Optional parameters make call sites cleaner.">[int seed]</span>) <span class="frontpage-highlight" data-text="Dart has language-level support for synchronous generators, too.">sync*</span> {
<span class="frontpage-highlight" data-text="Variables and fields can be final. Any attempt to change them later in the code will produce a static error.">final</span> random = new Random(seed);
while (true) {
<span class="frontpage-highlight" data-text="Producing lazy Iterables through yield is readable and corresponds nicely with the same concept in asynchronous generators.">yield</span> new Point(random.nextDouble(), random.nextDouble());
}
}

<span class="frontpage-highlight" data-text="Dart is purely object-oriented and class-based, with mixin-based inheritance.">class</span> Point {
final <span class="frontpage-highlight" data-text="Although Dart can compile to JavaScript, it doesn’t lack the distinction between double and int.">double</span> x, y;
<span class="frontpage-highlight" data-text="Constructors can be constant.">const</span> Point(<span class="frontpage-highlight" data-text="Initializing fields through this shorthand syntax is both easier and more readable.">this.x</span>, this.y);
bool <span class="frontpage-highlight" data-text="Language-level support for getters means you can freely switch between properties and methods without changing the API.">get</span> isInsideUnitCircle =&gt; x * x + y * y &lt;= 1;
}
</pre>
Loading