<section xml:id="activecode">
<title>ActiveCode</title>
<p>
Programs in supported languages are made interactive in HTML when <attr>interactive</attr> is set to <c>activecode</c>.
Some languages can be made interactive on any server,
while others require being served from Runestone servers.
See
<url href="https://pretextbook.org/doc/guide/html/topic-program-console.html#interactive-program-capabilities">Interactive Programs Capabilities in the PreTeXt Guide</url>
for a list of what languages are supported in which environs.
</p>
<listing xml:id="program-activecode-python">
<caption>An interactive Python program, using <pubtitle>Runestone</pubtitle></caption>
<program xml:id="python-hello-world" interactive="activecode" language="python" label="hello-world">
<code>
print("Hello, World!")
</code>
</program>
</listing>
<listing xml:id="program-activecode-javascript">
<caption>An interactive JavaScript program, using <pubtitle>Runestone</pubtitle></caption>
<program xml:id="javascript-hello-world" interactive="activecode" language="javascript">
<code>
document.write('Hello, world!');
</code>
</program>
</listing>
<p>
Some languages,
like Java or C++, are only interactive when run on a Runestone server where the code can be compiled and run.
Those languages can specify <attr>compiler-args</attr> and <attr>linker-args</attr> or <attr>interpreter-args</attr> as appropriate to the language.
Default values for those options can be set in <tag>docinfo/programs</tag> - any defaults set there will be used for any program that lacks the corresponding attribute.
</p>
<listing>
<caption>A C++ program with compiler-args and stdin</caption>
<p>It may be convenient to set <attr>compiler-args</attr> and <attr>linker-args</attr> at the book level in <tag>docinfo/programs</tag>. Values specified in that location will be used for any <tag>program</tag> that does not override the values by specifying its own attributes.</p>
<program interactive="activecode" label="hello-world-cpp" language="cpp" compiler-args="-std=c++17,-Wall,-g" linker-args="-g,-s">
<code>
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
cin >> name;
cout << "Hello, " << name << endl;
return 0;
}
</code>
<stdin>Jane</stdin>
</program>
</listing>
<listing xml:id="program-activecode-java-flags">
<caption>Java <q>Hello, World</q>, with flags</caption>
<program xml:id="java-hello-world-flags" interactive="activecode" language="java" interpreter-args="-Xrs,-Xss8m,-Xmx128m">
<code>
import javax.swing.JFrame; //Importing class JFrame
import javax.swing.JLabel; //Importing class JLabel
public class HelloWorld {
public static void main(String[] args) {
JFrame frame = new JFrame(); //Creating frame
frame.setTitle("Hi!"); //Setting title frame
frame.add(new JLabel("Hello, world!"));//Adding text to frame
frame.pack(); //Setting size to smallest
frame.setLocationRelativeTo(null); //Centering frame
frame.setVisible(true); //Showing frame
}
}
</code>
</program>
</listing>
<p>
An Octave program will also only be interactive if hosted on a Runestone server.
Octave is meant to be a drop-in replacement for Matlab.
</p>
<listing xml:id="program-activecode-octave">
<caption>A simple Octave program</caption>
<program xml:id="octave-simple" interactive="activecode" language="octave">
<code>
x = 2 + 2
printf("%d\n", x)
</code>
</program>
</listing>
<p>
A language not supported by Runestone Services will always be rendered static.
</p>
<listing xml:id="program-mistake-pascal">
<caption>A Pascal program that cannot be interactive on Runestone</caption>
<program xml:id="pascal-mistake" interactive="activecode" language="pascal">
<code>
program HelloWorld;
begin
WriteLn('Hello, world!');
end.
</code>
</program>
</listing>
<p>
A program can have a <tag>preamble</tag> and/or <tag>postamble</tag> which are added to the code that the user writes before it is run.
They are visible by default,
but can be made invisible with <attr>visible</attr> set to <c>"no"</c>.
When visible,
the code editor will prevent those regions from being modified.
The indentation for lines in the <c>preamble/code/postamble</c> elements will be calculated relative to each other - make sure to indent them all to a similar extent. (In the source for the sample below,
the <c># TODO...</c> is intentially indented one stop extra so that the user's code is part of the <c>add</c> function.
</p>
<p>
<tag>tests</tag> are similar to <tag>postamble</tag> in that it represents code that is added to the users submission.
However, <tag>tests</tag> is intended specifically for unit testing code
(see examples below for unit testing in Python, Java, C++, SQL).
Tests are invisble by default and can be made visible with <attr>visible</attr> set to <c>"yes"</c>.
For historical reasons,
the indentation of the <tag>tests</tag> is treated separately from the rest of the program.
</p>
<xi:include xmlns="http://www.w3.org/2001/XInclude" href="./rune-examples/activecode-ambles.xml" />
<p>
Here is the same Python program from the previous section,
but now with a <tag>preamble</tag> and <tag>postamble</tag> that are invisible.
The user will not see the code that is added to their submission.
Not actually useful in this case,
but it might be if you wanted to hide boilerplate setup from the reader.
</p>
<listing>
<caption>A Python program with invisible pre/post ambles</caption>
<program interactive="activecode" language="python" label="program-activecode-python-ambles-invisible">
<preamble visible="no">
def add(a, b):
</preamble>
<code>
# TODO - complete the add function
</code>
<postamble visible="no">
# Use the function
result = add(2, 3)
if result == 5:
print("Test passed")
else:
print("Test failed")
</postamble>
</program>
</listing>
<p>
The following Python program is in a <tag>listing</tag> since we will want to reference it shortly.
The program does not do very much,
it just defines four variables whose values are lists of statistics.
It should run, and there will be no syntax errors,
but it is a bit boring since there is no output.
Note that it does not have an <attr>language</attr> and is relying on the default one specified in <tag>docinfo/programs</tag>
</p>
<listing xml:id="listing-python-included">
<caption>A Python program that defines some statistics</caption>
<program xml:id="python-statistics" interactive="activecode" label="statistics">
<code>
loan_amount = [1250.0, 500.0, 1450.0, 200.0, 700.0, 100.0, 250.0, 225.0, 1200.0, 150.0, 600.0, 300.0, 700.0, 125.0, 650.0, 175.0, 1800.0, 1525.0, 575.0, 700.0, 1450.0, 400.0, 200.0, 1000.0, 350.0]
country_name = ['Azerbaijan', 'El Salvador', 'Bolivia', 'Paraguay', 'El Salvador', 'Philippines', 'Philippines', 'Nicaragua', 'Guatemala', 'Philippines', 'Paraguay', 'Philippines', 'Bolivia', 'Philippines', 'Philippines', 'Madagascar', 'Georgia', 'Uganda', 'Kenya', 'Tajikistan', 'Jordan', 'Kenya', 'Philippines', 'Ecuador', 'Kenya']
time_to_raise = [193075.0, 1157108.0, 1552939.0, 244945.0, 238797.0, 1248909.0, 773599.0, 116181.0, 2288095.0, 51668.0, 26717.0, 48030.0, 1839190.0, 71117.0, 580401.0, 800427.0, 1156218.0, 1166045.0, 2924705.0, 470622.0, 24078.0, 260044.0, 445938.0, 201408.0, 2370450.0]
num_lenders_total = [38, 18, 51, 3, 21, 1, 10, 8, 42, 1, 18, 6, 28, 5, 16, 7, 54, 1, 18, 22, 36, 12, 8, 24, 8]
</code>
</program>
</listing>
<p>
Now a programming exercise.
The program upcoming is going to <term>include</term>
all the code of the program preceding.
This is accomplished with an <attr>include</attr> attribute on the <em>including</em>
program whose value is the <attr>xml:id</attr> of the
<em>included</em> program.
So by running the next program,
it should pass all of its three tests
(for example another example using unit tests,
see <xref ref="unit-test-example" />).
Now reload the page, do not run the program in the listing,
and then see that the program in the exercise still runs correctly.
</p>
<p>
You'll see nothing that tells the reader that the one chunk of code is prefacing the other.
And in static formats it might be even less obvious.
So you will want to say <em>something</em> to alert the reader.
Here it is easy:
<xref ref="exercise-python-including" /> includes all the code from <xref ref="listing-python-included" />.
</p>
<p>
This program also makes use of <attr>autorun</attr> to execute on page load and the <attr>codelens</attr>to disable the codelens feature.
</p>
<exercise xml:id="exercise-python-including">
<title>A Python program, including another</title>
<statement>
<p>
Compute the total amount of money loaned and store it in the variable <c>loan_total</c>.
</p>
</statement>
<program autorun="yes" codelens="no" xml:id="python-summation" interactive="activecode" language="python" label="python-sum-total" include="python-statistics">
<code>
loan_total = 0
for loan in loan_amount:
loan_total += loan
print(loan_total)
</code>
<tests>
from unittest.gui import TestCaseGui
class MyTests(TestCaseGui):
def testOne(self):
self.assertTrue('loan_total' in self.getEditorText(), "you need a loan_total variable")
self.assertEqual(loan_total, sum(loan_amount), "Use the accumulator pattern to add up all the loans")
self.assertFalse('sum(' in self.getEditorText(), "you may not use sum()")
MyTests().main()
</tests>
</program>
</exercise>
<p>
Exact same exercise again, but now we include <em>two</em> programs.
We first get the simple
<q>Hello, world!</q>
program at <xref ref="program-activecode-python" /> and then the same program defining the variables with lists of statistics at <xref ref="listing-python-included" />.
So the output just includes the extra result from the <c>print()</c> statement.
</p>
<p>
This program also makes use of <attr>hidecode</attr> to initially keep the code hidden and <attr>download</attr> to enable a file download of the program
(that includes all the included code).
</p>
<exercise xml:id="exercise-python-including-two">
<title>A Python program, including two others</title>
<statement>
<p>
Compute the total amount of money loaned and store it in the variable <c>loan_total</c>.
</p>
</statement>
<program xml:id="python-summation-two" interactive="activecode" language="python" label="python-sum-total-two" include="python-hello-world python-statistics " hidecode="yes" download="yes">
<code>
loan_total = 0
for loan in loan_amount:
loan_total += loan
print(loan_total)
</code>
<tests>
from unittest.gui import TestCaseGui
class MyTests(TestCaseGui):
def testOne(self):
self.assertTrue('loan_total' in self.getEditorText(), "you need a loan_total variable")
self.assertEqual(loan_total, sum(loan_amount), "Use the accumulator pattern to add up all the loans")
self.assertFalse('sum(' in self.getEditorText(), "you may not use sum")
MyTests().main()
</tests>
</program>
</exercise>
<p>
Here is an activecode with <attr>language</attr> set to <c>sql</c> uses the <attr>database</attr> to load a SQLite database file.
</p>
<exercise xml:id="exercise-sql-using-db">
<title>An SQL program that uses an SQLite database file</title>
<statement>
<p>
Select all the columns of all the rows in the <c>test</c> database table.
</p>
</statement>
<program xml:id="sql-using-db" interactive="activecode" language="sql" label="sql-using-db" database="sql/test.db">
<code>
SELECT * FROM test
</code>
<tests>
assert 1,1 == world
assert 0,1 == hello
assert 2,1 == 35
</tests>
</program>
</exercise>
<p>
A nonsense paragraph just to check on spacing.
A nonsense paragraph just to check on spacing.
A nonsense paragraph just to check on spacing.
A nonsense paragraph just to check on spacing.
</p>
</section>
Section 3.2 ActiveCode
View Source for section
Programs in supported languages are made interactive in HTML when for a list of what languages are supported in which environs.
@interactive
is set to activecode
. Some languages can be made interactive on any server, while others require being served from Runestone servers. See Interactive Programs Capabilities in the PreTeXt Guide1
pretextbook.org/doc/guide/html/topic-program-console.html#interactive-program-capabilities
Some languages, like Java or C++, are only interactive when run on a Runestone server where the code can be compiled and run. Those languages can specify
@compiler-args
and @linker-args
or @interpreter-args
as appropriate to the language. Default values for those options can be set in <docinfo/programs>
- any defaults set there will be used for any program that lacks the corresponding attribute.An Octave program will also only be interactive if hosted on a Runestone server. Octave is meant to be a drop-in replacement for Matlab.
A language not supported by Runestone Services will always be rendered static.
A program can have a
<preamble>
and/or <postamble>
which are added to the code that the user writes before it is run. They are visible by default, but can be made invisible with @visible
set to "no"
. When visible, the code editor will prevent those regions from being modified. The indentation for lines in the preamble/code/postamble
elements will be calculated relative to each other - make sure to indent them all to a similar extent. (In the source for the sample below, the # TODO...
is intentially indented one stop extra so that the user’s code is part of the add
function.<tests>
are similar to <postamble>
in that it represents code that is added to the users submission. However, <tests>
is intended specifically for unit testing code (see examples below for unit testing in Python, Java, C++, SQL). Tests are invisble by default and can be made visible with @visible
set to "yes"
. For historical reasons, the indentation of the <tests>
is treated separately from the rest of the program.Here is the same Python program from the previous section, but now with a
<preamble>
and <postamble>
that are invisible. The user will not see the code that is added to their submission. Not actually useful in this case, but it might be if you wanted to hide boilerplate setup from the reader.The following Python program is in a
<listing>
since we will want to reference it shortly. The program does not do very much, it just defines four variables whose values are lists of statistics. It should run, and there will be no syntax errors, but it is a bit boring since there is no output. Note that it does not have an @language
and is relying on the default one specified in <docinfo/programs>
Now a programming exercise. The program upcoming is going to include all the code of the program preceding. This is accomplished with an
@include
attribute on the including program whose value is the @xml:id
of the included program. So by running the next program, it should pass all of its three tests (for example another example using unit tests, see [cross-reference to target(s) "unit-test-example" missing or not unique]
). Now reload the page, do not run the program in the listing, and then see that the program in the exercise still runs correctly.You’ll see nothing that tells the reader that the one chunk of code is prefacing the other. And in static formats it might be even less obvious. So you will want to say something to alert the reader. Here it is easy: Checkpoint 3.2.9 includes all the code from Listing 3.2.8.
This program also makes use of
@autorun
to execute on page load and the @codelens
to disable the codelens feature.Checkpoint 3.2.9. A Python program, including another.
View Source for exercise
<exercise xml:id="exercise-python-including">
<title>A Python program, including another</title>
<statement>
<p>
Compute the total amount of money loaned and store it in the variable <c>loan_total</c>.
</p>
</statement>
<program autorun="yes" codelens="no" xml:id="python-summation" interactive="activecode" language="python" label="python-sum-total" include="python-statistics">
<code>
loan_total = 0
for loan in loan_amount:
loan_total += loan
print(loan_total)
</code>
<tests>
from unittest.gui import TestCaseGui
class MyTests(TestCaseGui):
def testOne(self):
self.assertTrue('loan_total' in self.getEditorText(), "you need a loan_total variable")
self.assertEqual(loan_total, sum(loan_amount), "Use the accumulator pattern to add up all the loans")
self.assertFalse('sum(' in self.getEditorText(), "you may not use sum()")
MyTests().main()
</tests>
</program>
</exercise>
Compute the total amount of money loaned and store it in the variable
loan_total
.Exact same exercise again, but now we include two programs. We first get the simple “Hello, world!” program at Listing 3.2.1 and then the same program defining the variables with lists of statistics at Listing 3.2.8. So the output just includes the extra result from the
print()
statement.This program also makes use of
@hidecode
to initially keep the code hidden and @download
to enable a file download of the program (that includes all the included code).Checkpoint 3.2.10. A Python program, including two others.
View Source for exercise
<exercise xml:id="exercise-python-including-two">
<title>A Python program, including two others</title>
<statement>
<p>
Compute the total amount of money loaned and store it in the variable <c>loan_total</c>.
</p>
</statement>
<program xml:id="python-summation-two" interactive="activecode" language="python" label="python-sum-total-two" include="python-hello-world python-statistics " hidecode="yes" download="yes">
<code>
loan_total = 0
for loan in loan_amount:
loan_total += loan
print(loan_total)
</code>
<tests>
from unittest.gui import TestCaseGui
class MyTests(TestCaseGui):
def testOne(self):
self.assertTrue('loan_total' in self.getEditorText(), "you need a loan_total variable")
self.assertEqual(loan_total, sum(loan_amount), "Use the accumulator pattern to add up all the loans")
self.assertFalse('sum(' in self.getEditorText(), "you may not use sum")
MyTests().main()
</tests>
</program>
</exercise>
Compute the total amount of money loaned and store it in the variable
loan_total
.Here is an activecode with
@language
set to sql
uses the @database
to load a SQLite database file.Checkpoint 3.2.11. An SQL program that uses an SQLite database file.
View Source for exercise
<exercise xml:id="exercise-sql-using-db">
<title>An SQL program that uses an SQLite database file</title>
<statement>
<p>
Select all the columns of all the rows in the <c>test</c> database table.
</p>
</statement>
<program xml:id="sql-using-db" interactive="activecode" language="sql" label="sql-using-db" database="sql/test.db">
<code>
SELECT * FROM test
</code>
<tests>
assert 1,1 == world
assert 0,1 == hello
assert 2,1 == 35
</tests>
</program>
</exercise>
Select all the columns of all the rows in the
test
database table.A nonsense paragraph just to check on spacing. A nonsense paragraph just to check on spacing. A nonsense paragraph just to check on spacing. A nonsense paragraph just to check on spacing.