-
Notifications
You must be signed in to change notification settings - Fork 676
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
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
2e1f4a6
Move main example HTML into its own file, unchanged
chalin 5c2c1c7
Main example HTML: minor fixes
chalin 717f36b
Main example source + script to generate tooltip annotated version
chalin d6e116f
Adjust dartfmt.sh script
chalin 0f56819
Post-review updates
chalin e88adcc
Remove temporary script conversions used by script to ensure backward…
chalin 0d06f29
The new generated main example in HTML
chalin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>") | ||
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") | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'), | ||
]))); | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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."><double></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.">=></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 ∈ <0,1>, | ||
// y ∈ <0,1>, 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><Point> 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 => x * x + y * y <= 1; | ||
} | ||
</pre> |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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