0% found this document useful (0 votes)
89 views55 pages

Complete 500 Lines or Less Experienced Programmers Solve Interesting Problems Michael Dibernardo PDF For All Chapters

Lines

Uploaded by

ilskeritha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views55 pages

Complete 500 Lines or Less Experienced Programmers Solve Interesting Problems Michael Dibernardo PDF For All Chapters

Lines

Uploaded by

ilskeritha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Experience Seamless Full Ebook Downloads for Every Genre at textbookfull.

com

500 Lines Or Less Experienced Programmers Solve


Interesting Problems Michael Dibernardo

https://textbookfull.com/product/500-lines-or-less-
experienced-programmers-solve-interesting-problems-michael-
dibernardo/

OR CLICK BUTTON

DOWNLOAD NOW

Explore and download more ebook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Hypernomics: Using Hidden Dimensions to Solve Unseen


Problems 1st Edition Doug Howarth

https://textbookfull.com/product/hypernomics-using-hidden-dimensions-
to-solve-unseen-problems-1st-edition-doug-howarth/

textboxfull.com

How to Solve Real-world Optimization Problems: From Theory


to Practice 1st Edition Zak

https://textbookfull.com/product/how-to-solve-real-world-optimization-
problems-from-theory-to-practice-1st-edition-zak/

textboxfull.com

Microwave and RF Design Volume 2 Transmission Lines


Michael Steer

https://textbookfull.com/product/microwave-and-rf-design-
volume-2-transmission-lines-michael-steer/

textboxfull.com

Team Savage Complete Series Box Set Includes Kill or Be


Killed Dead or Alive and Vengeance or Death Michael Todd -
Michael Anderle
https://textbookfull.com/product/team-savage-complete-series-box-set-
includes-kill-or-be-killed-dead-or-alive-and-vengeance-or-death-
michael-todd-michael-anderle/
textboxfull.com
Everything, More or Less : a defence of generality
relativism First Edition. Edition James Studd

https://textbookfull.com/product/everything-more-or-less-a-defence-of-
generality-relativism-first-edition-edition-james-studd/

textboxfull.com

Cruel Inhuman or Degrading Treatment Michael Adler

https://textbookfull.com/product/cruel-inhuman-or-degrading-treatment-
michael-adler/

textboxfull.com

Acupressure for Horses Hands On Techniques to Solve


Performance Problems and Ease Pain and Discomfort Gosmeier
Ina
https://textbookfull.com/product/acupressure-for-horses-hands-on-
techniques-to-solve-performance-problems-and-ease-pain-and-discomfort-
gosmeier-ina/
textboxfull.com

Can Markets Solve Problems An Empirical Inquiry into


Neoliberalism in Action Goldsmiths Press PERC Papers 1st
Edition Neyland
https://textbookfull.com/product/can-markets-solve-problems-an-
empirical-inquiry-into-neoliberalism-in-action-goldsmiths-press-perc-
papers-1st-edition-neyland/
textboxfull.com

Civil Engineering Solved Problems 8th Edition Michael R.


Lindeburg

https://textbookfull.com/product/civil-engineering-solved-
problems-8th-edition-michael-r-lindeburg/

textboxfull.com
Experienced programmers solve interesting problems
500 Lines or Less
Edited by Michael DiBernardo
This work is licensed under the Creative Commons Attribution 3.0 Unported license (CC BY 3.0). You are free:
• to Share—to copy, distribute and transmit the work
• to Remix—to adapt the work
under the following conditions:
• Attribution—you must attribute the work in the manner specified by the author or licensor (but not in any
way that suggests that they endorse you or your use of the work).
with the understanding that:
• Waiver—Any of the above conditions can be waived if you get permission from the copyright holder.
• Public Domain—Where the work or any of its elements is in the public domain under applicable law,
that status is in no way affected by the license.
• Other Rights—In no way are any of the following rights affected by the license:
– Your fair dealing or fair use rights, or other applicable copyright exceptions and limitations;
– The author’s moral rights;
– Rights other persons may have either in the work itself or in how the work is used, such as publicity
or privacy rights.
• Notice—For any reuse or distribution, you must make clear to others the license terms of this work. The
best way to do this is with a link to http://creativecommons.org/licenses/by/3.0/.
To view a copy of this license, visit http://creativecommons.org/licenses/by/3.0/ or send a letter to
Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.

The full text of this book is available online at http://www.aosabook.org/.


All royalties from its sale will be donated to Amnesty International.

Product and company names mentioned herein may be the trademarks of their respective owners.

While every precaution has been taken in the preparation of this book, the editors and authors assume no
responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.

Front cover photo ©Kellar Wilson


Copyediting, cover design, and publishing support by Amy Brown: http://amyrbrown.ca

Revision Date: September 9, 2016

ISBN: 978-1-329-87127-4
Contents

Introduction ix
by Michael DiBernardo

1 Blockcode: A visual programming toolkit 1


by Dethe Elza

2 A Continuous Integration System 17


by Malini Das

3 Clustering by Consensus 33
by Dustin J. Mitchell

4 Contingent: A Fully Dynamic Build System 61


by Brandon Rhodes and Daniel Rocco

5 A Web Crawler With asyncio Coroutines 83


by A. Jesse Jiryu Davis and Guido van Rossum

6 Dagoba: an in-memory graph database 109


by Dann Toliver

7 DBDB: Dog Bed Database 141


by Taavi Burns

8 An Event-Driven Web Framework 153


by Leo Zovic

9 A Flow Shop Scheduler 175


by Dr. Christian Muise

10 An Archaeology-Inspired Database 191


by Yoav Rubin

11 Making Your Own Image Filters 215


by Cate Huston

12 A Python Interpreter Written in Python 243


by Allison Kaptur
13 A 3D Modeller 267
by Erick Dransch

14 A Simple Object Model 291


by Carl Friedrich Bolz

15 Optical Character Recognition (OCR) 309


by Marina Samuel

16 A Pedometer in the Real World 323


by Dessy Daskalov

17 The Same-Origin Policy 347


by Eunsuk Kang, Santiago Perez De Rosso, and Daniel Jackson

18 A Rejection Sampler 375


by Jessica B. Hamrick

19 Web Spreadsheet 395


by Audrey Tang

20 Static Analysis 409


by Leah Hanson

21 A Template Engine 431


by Ned Batchelder

22 A Simple Web Server 451


by Greg Wilson

vi CONTENTS
Introduction
Michael DiBernardo

This is the fourth volume in the Architecture of Open Source Applications series, and the first to not
feature the words “open source applications” anywhere in the title.
The first three volumes in the series were about big problems that big programs have to solve.
For an engineer who is early in their career, it may be a challenge to understand and build upon
programs that are much bigger than a few thousand lines of code, so, while big problems can be
interesting to read about, they can also be challenging to learn from.
500 Lines or Less focuses on the design decisions that programmers make in the small when they
are building something new. The programs you will read about in this book were all written from
scratch for this purpose (although several of them were inspired by larger projects that the authors
had worked on previously).
Before reading each chapter, we encourage you to first think about how you might solve the
problem. What design considerations or constraints do you think the author is going to consider
important? What abstractions do you expect to see? How do you think the problem is going to be
decomposed? Then, when reading the chapter, try to identify what surprised you. It is our hope that
you will learn more by doing this than by simply reading through each chapter from beginning to
end.
Writing a useful program in fewer than 500 lines of source code—without resorting to cheap
tricks—is a challenging exercise in itself; writing one to be read for pedagogical purposes when
neatly rendered in a printed book is even tougher. As such, the editors have occasionally taken
liberties with some of the source formatting when porting it into the book. The original source for
each chapter can be found in the code subdirectory of its project folder.
We hope that the experiences of the authors in this book will help you grow out of your comfort
zone in your own programming practice.
— Michael DiBernardo
Contributors
Michael DiBernardo (editorial): Michael DiBernardo is an engineer and director of delivery at
Wave, and a past PyCon Canada chair. He writes at mikedebo.ca.
Amy Brown (editorial): Amy Brown is a freelance editor based in Toronto. She specializes
in science and academic editing, and working with self-publishing authors. She co-edited the
Architecture of Open Source Applications books with Greg Wilson.
Dethe Elza (Blockcode): Dethe is a geek dad, aesthetic programmer, mentor, and creator of the
Waterbear visual programming tool. He co-hosts the Vancouver Maker Education Salons and wants
to fill the world with robotic origami rabbits.
Malini Das (CI): Malini is a software engineer who is passionate about developing quickly (but
safely!), and solving cross-functional problems. She has worked at Mozilla as a tools engineer and is
currently honing her skills at Twitch.
Dustin J. Mitchell (Cluster): Dustin is an open source software developer and release engineer at
Mozilla. He has worked on projects as varied as a host configuration system in Puppet, a Flask-based
web framework, unit tests for firewall configurations, and a continuous integration framework in
Twisted Python.
Daniel Rocco (Contingent): Daniel loves Python, coffee, craft, stout, object and system design,
bourbon, teaching, trees, and Latin guitar. Thrilled that he gets to write Python for a living, he is
always on the lookout for opportunities to learn from others in the community, and to contribute by
sharing knowledge. He is a frequent speaker at PyAtl on introductory topics, testing, design, and
shiny things; he loves seeing the spark of delight in people’s eyes when someone shares a surprising
or beautiful idea. Daniel lives in Atlanta with a microbiologist and four aspiring rocketeers.
Brandon Rhodes (Contingent): Brandon Rhodes started using Python in the late 1990s, and for
17 years has maintained the PyEphem library for amateur astronomers. He works at Dropbox, has
taught Python programming courses for corporate clients, consulted on projects like the New England
Wildflower Society’s “Go Botany” Django site, and will be the chair of the PyCon conference in
2016 and 2017. Brandon believes that well-written code is a form of literature, that beautifully
formatted code is a work of graphic design, and that correct code is one of the most transparent
forms of thought.
A. Jesse Jiryu Davis (Crawler): Jesse is a staff engineer at MongoDB in New York. He wrote
Motor, the async MongoDB Python driver, and he is the lead developer of the MongoDB C Driver and
a member of the PyMongo team. He contributes to asyncio and Tornado. He writes at emptysqua.re.
Guido van Rossum (Crawler): Guido is the creator of Python, one of the major programming
languages on and off the web. The Python community refers to him as the BDFL (Benevolent
Dictator For Life), a title straight from a Monty Python skit.
Dann Toliver (Dagoba): Dann enjoys building things, like programming languages, databases,
distributed systems, communities of smart friendly humans, and pony castles with his two-year-old.
Taavi Burns (DBDB): As the newest bass (and sometimes tenor) in Countermeasure, Taavi strives
to break the mould. . . sometimes just by ignoring its existence. This is certainly true through the
diversity of workplaces in his career: IBM (doing C and Perl), FreshBooks (all the things), Points.com
(doing Python), and now at PagerDuty (doing Scala). Aside from that—when not gliding along
on his Brompton folding bike—you might find him playing Minecraft with his son or engaging in
parkour (or rock climbing, or other adventures) with his wife. He knits continental.
Leo Zovic: Leo (better known online as inaimathi) is a recovering graphic designer who has
professionally written Scheme, Common Lisp, Erlang, Javascript, Haskell, Clojure, Go, Python,

viii Introduction
PHP and C. He currently blogs about programming, plays board games and works at a Ruby-based
startup in Toronto, Ontario.
Dr. Christian Muise (Flow shop): Dr. Muise is a Research Fellow with the Model-based Embedded
and Robotic Systems group at MIT’s Computer Science and Artificial Intelligence Laboratory. He is
interested in a variety of topics including AI, data-driven projects, mapping, graph theory, and data
visualization, as well as Celtic music, carving, soccer, and coffee.
Yoav Rubin (CircleDB): Yoav is a Senior Software Engineer at Microsoft, and prior to that was
a Research Staff Member and a Master Inventor at IBM Research. He works now in the domain
of data security in the cloud, and in the past his work focused on developing cloud- or web-based
development environments. Yoav holds an MSc in Medical Research in the field of Neuroscience
and BSc in Information Systems Engineering.
Cate Huston (Image filters): Cate is a developer and entrepreneur focused on mobile. She’s lived
and worked in the UK, Australia, Canada, China and the United States, as an engineer at Google, an
Extreme Blue intern at IBM, and a ski instructor. Cate speaks internationally on mobile development,
and her writing has been published on sites as varied as Lifehacker, The Daily Beast, The Eloquent
Woman and Model View Culture. She co-curates Technically Speaking, blogs at Accidentally in
Code and is @catehstn on Twitter.
Allison Kaptur (Interpreter): Allison is an engineer at Dropbox, where she helps maintain one
of the largest networks of Python clients in the world. Before Dropbox, she was a facilitator at the
Recurse Center, a writers’ retreat for programmers in New York. She’s spoken at PyCon North
America about Python internals, and loves weird bugs.
Erick Dransch (Modeller): Erick is a software developer and 2D and 3D computer graphics
enthusiast. He has worked on video games, 3D special effects software, and computer-aided design
tools. If it involves simulating reality, chances are he’d like to learn more about it. You can find him
online at erickdransch.com.
Carl Friedrich Bolz (Object model): Carl is a researcher at King’s College London and is broadly
interested in the implementation and optimization of all kinds of dynamic languages. He is one of
the core authors of PyPy/RPython and has worked on implementations of Prolog, Racket, Smalltalk,
PHP and Ruby.
Marina Samuel (OCR): Marina is an engineer at Mozilla and a current MSc student in Applied
Computing (Artifical Intelligence) at the University of Toronto. She hopes to one day build robots
that will take over the planet.
Dessy Daskalov (Pedometer): Dessy is an engineer by trade, an entrepreneur by passion, and
a developer at heart. She’s currently the CTO and co-founder of Nudge Rewards. When she’s not
busy building product with her team, she can be found teaching others to code, attending or hosting
a Toronto tech event, and online at dessydaskalov.com and @dess_e.
Eunsuk Kang (Same-origin policy): Eunsuk is a PhD candidate and a member of the Software
Design Group at MIT. He received his SM (Master of Science) in Computer Science from MIT
(2010), and a Bachelor of Software Engineering from the University of Waterloo (2007). His research
projects have focused on developing tools and techniques for software modeling and verification,
with applications to security and safety-critical systems.
Santiago Perez (Same-origin policy): Santiago is a PhD student in the Software Design Group at
MIT. He received his SM in Computer Science from MIT (2015), and an undergraduate degree from
ITBA (2011). He used to work at Google, developing frameworks and tools to make engineers more
productive (2012). He currently spends most of his time thinking about design and version control.
Daniel Jackson (Same-origin policy): Daniel is a professor in the Department of Electrical
Engineering and Computer Science at MIT, and leads the Software Design Group in the Computer

Michael DiBernardo ix
Science and Artificial Intelligence Laboratory. He received an MA from Oxford University (1984)
in Physics, and his SM (1988) and PhD (1992) in Computer Science from MIT. He was a software
engineer for Logica UK Ltd. (1984-1986), Assistant Professor of Computer Science at Carnegie
Mellon University (1992-1997), and has been at MIT since 1997. He has broad interests in software
engineering, especially in development methods, design and specification, formal methods, and
safety-critical systems.
Jessica B. Hamrick (Sampler): Jess is a PhD student at UC Berkeley where she studies human
cognition by combining probabilistic models from machine learning with behavioral experiments
from cognitive science. In her spare time, Jess is a core contributor to IPython and Jupyter. She also
holds a BS and MEng in Computer Science from MIT.
Audrey Tang (Spreadsheet): A self-educated programmer and translator, Audrey works with
Apple as an independent contractor on cloud service localization and natural language technologies.
Audrey has previously designed and led the first working Perl 6 implementation, and served in
computer language design committees for Haskell, Perl 5, and Perl 6. Currently Audrey is a full-time
g0v contributor and leads Taiwan’s first e-Rulemaking project.
Leah Hanson (Static analysis): Leah Hanson is a proud alum of Hacker School and loves helping
people learn about Julia. She blogs at blog.leahhanson.us and tweets at @astrieanna.
Ned Batchelder (Template engine): Ned is a software engineer with a long career, currently
working at edX to build open source software to educate the world. He’s the maintainer of coverage.py,
an organizer of Boston Python, and has spoken at many PyCons. He blogs at nedbatchelder.com.
He once had dinner at the White House.
Greg Wilson (Web server): Greg is the founder of Software Carpentry, a crash course in computing
skills for scientists and engineers. He has worked for 30 years in both industry and academia, and is
the author or editor of several books on computing, including the 2008 Jolt Award winner Beautiful
Code and the first two volumes of The Architecture of Open Source Applications. Greg received a
PhD in Computer Science from the University of Edinburgh in 1993.

x Introduction
Acknowledgments
The Architecture of Open Source Applications series would not exist without the hard work of Amy
Brown and Greg Wilson. This particular book would not have been possible without the incredible
efforts of our army of technical reviewers:

Amber Yust Gregory Eric Sanderson Matthias Bussonnier


Andrew Gwozdziewycz James O’Beirne Max Mautner
Andrew Kuchling Jan de Baat Meggin Kearney
Andrew Svetlov Jana Beck Mike Aquino
Andy Shen Jessica McKellar Natalie Black
Anton Beloglazov Jo Van Eyck Nick Presta
Ben Trofatter Joel Crocker Nikhil Almeida
Borys Pierov Johan Thelin Nolan Prescott
Carise Fernandez Johannes Fürmann Paul Martin
Charles Stanhope John Morrissey Piotr Banaszkiewicz
Chris AtLee Joseph Kaptur Preston Holmes
Chris Seaton Josh Crompton Pulkit Sethi
Cyryl Płotnicki-Chudyk Joshua T. Corbin Rail Aliiev
Dan Langer Kevin Huang Ronen Narkis
Dan Shapiro Maggie Zhou Rose Ames
David Pokorny Marc Towler Sina Jahan
Eric Bouwers Marcin Milewski Stefan Turalski
Frederic De Groef Marco Lancini William Lachance
Graham Lee Mark Reid

Chris Seaton, John Morrissey, and Natalie Black deserve extended thanks for going above and beyond
in their technical reviewing. The quantity and depth of their reviews was instrumental in moving the
book forward at several sticking points.
We are very grateful to PagerDuty for their financial support.

Contributing
If you’d like to report errors or translate the content into other languages, please open an issue at
github.com/aosabook/500lines/ or contact us at [email protected].

xi
[chapter 1]

Blockcode: A visual programming toolkit


Dethe Elza

In block-based programming languages, you write programs by dragging and connecting blocks
that represent parts of the program. Block-based languages differ from conventional programming
languages, in which you type words and symbols.
Learning a programming language can be difficult because they are extremely sensitive to even
the slightest of typos. Most programming languages are case-sensitive, have obscure syntax, and will
refuse to run if you get so much as a semicolon in the wrong place—or worse, leave one out. Further,
most programming languages in use today are based on English and their syntax cannot be localized.
In contrast, a well-done block language can eliminate syntax errors completely. You can still
create a program which does the wrong thing, but you cannot create one with the wrong syntax: the
blocks just won’t fit that way. Block languages are more discoverable: you can see all the constructs
and libraries of the language right in the list of blocks. Further, blocks can be localized into any
human language without changing the meaning of the programming language.

Figure 1.1: The Blockcode IDE in use

Block-based languages have a long history, with some of the prominent ones being Lego Mind-
storms1 , Alice3D2 , StarLogo3 , and especially Scratch4 . There are several tools for block-based
1 http://www.lego.com/en-us/mindstorms/
2 http://www.alice.org/index.php
3 http://education.mit.edu/projects/starlogo-tng
4 http://scratch.mit.edu/
programming on the web as well: Blockly5 , AppInventor6 , Tynker7 , and many more8 .
The code in this chapter is loosely based on the open-source project Waterbear9 , which is not
a language but a tool for wrapping existing languages with a block-based syntax. Advantages of
such a wrapper include the ones noted above: eliminating syntax errors, visual display of available
components, ease of localization. Additionally, visual code can sometimes be easier to read and
debug, and blocks can be used by pre-typing children. (We could even go further and put icons on
the blocks, either in conjunction with the text names or instead of them, to allow pre-literate children
to write programs, but we don’t go that far in this example.)
The choice of turtle graphics for this language goes back to the Logo language, which was created
specifically to teach programming to children. Several of the block-based languages above include
turtle graphics, and it is a small enough domain to be able to capture in a tightly constrained project
such as this.
If you would like to get a feel for what a block-based-language is like, you can experiment with
the program that is built in this chapter from author’s GitHub repository10 .

1.1 Goals and Structure


I want to accomplish a couple of things with this code. First and foremost, I want to implement a
block language for turtle graphics, with which you can write code to create images through simple
dragging-and-dropping of blocks, using as simple a structure of HTML, CSS, and JavaScript as
possible. Second, but still important, I want to show how the blocks themselves can serve as a
framework for other languages besides our mini turtle language.
To do this, we encapsulate everything that is specific to the turtle language into one file
(turtle.js) that we can easily swap with another file. Nothing else should be specific to the turtle
language; the rest should just be about handling the blocks (blocks.js and menu.js) or be generally
useful web utilities (util.js, drag.js, file.js). That is the goal, although to maintain the small
size of the project, some of those utilities are less general-purpose and more specific to their use
with the blocks.
One thing that struck me when writing a block language was that the language is its own IDE.
You can’t just code up blocks in your favourite text editor; the IDE has to be designed and developed
in parallel with the block language. This has some pros and cons. On the plus side, everyone will
use a consistent environment and there is no room for religious wars about what editor to use. On
the downside, it can be a huge distraction from building the block language itself.

The Nature of Scripts


A Blockcode script, like a script in any language (whether block- or text-based), is a sequence of
operations to be followed. In the case of Blockcode the script consists of HTML elements which
are iterated over, and which are each associated with a particular JavaScript function which will be
run when that block’s turn comes. Some blocks can contain (and are responsible for running) other
blocks, and some blocks can contain numeric arguments which are passed to the functions.
5 https://developers.google.com/blockly/
6 http://appinventor.mit.edu/explore/
7 http://www.tynker.com/
8 http://en.wikipedia.org/wiki/Visual_programming_language
9 http://waterbearlang.com/
10 https://dethe.github.io/500lines/blockcode/

2 Blockcode: A visual programming toolkit


In most (text-based) languages, a script goes through several stages: a lexer converts the text
into recognized tokens, a parser organizes the tokens into an abstract syntax tree, then depending on
the language the program may be compiled into machine code or fed into an interpreter. That’s a
simplification; there can be more steps. For Blockcode, the layout of the blocks in the script area
already represents our abstract syntax tree, so we don’t have to go through the lexing and parsing
stages. We use the Visitor pattern to iterate over those blocks and call predefined JavaScript functions
associated with each block to run the program.
There is nothing stopping us from adding additional stages to be more like a traditional language.
Instead of simply calling associated JavaScript functions, we could replace turtle.js with a block
language that emits byte codes for a different virtual machine, or even C++ code for a compiler. Block
languages exist (as part of the Waterbear project) for generating Java robotics code, for programming
Arduino, and for scripting Minecraft running on Raspberry Pi.

Web Applications
In order to make the tool available to the widest possible audience, it is web-native. It’s written in
HTML, CSS, and JavaScript, so it should work in most browsers and platforms.
Modern web browsers are powerful platforms, with a rich set of tools for building great apps. If
something about the implementation became too complex, I took that as a sign that I wasn’t doing it
“the web way” and, where possible, tried to re-think how to better use the browser tools.
An important difference between web applications and traditional desktop or server applications
is the lack of a main() or other entry point. There is no explicit run loop because that is already
built into the browser and implicit on every web page. All our code will be parsed and executed on
load, at which point we can register for events we are interested in for interacting with the user. After
the first run, all further interaction with our code will be through callbacks we set up and register,
whether we register those for events (like mouse movement), timeouts (fired with the periodicity we
specify), or frame handlers (called for each screen redraw, generally 60 frames per second). The
browser does not expose full-featured threads either (only shared-nothing web workers).

1.2 Stepping Through the Code


I’ve tried to follow some conventions and best practices throughout this project. Each JavaScript file
is wrapped in a function to avoid leaking variables into the global environment. If it needs to expose
variables to other files it will define a single global per file, based on the filename, with the exposed
functions in it. This will be near the end of the file, followed by any event handlers set by that file, so
you can always glance at the end of a file to see what events it handles and what functions it exposes.
The code style is procedural, not object-oriented or functional. We could do the same things in
any of these paradigms, but that would require more setup code and wrappers to impose on what
exists already for the DOM. Recent work on Custom Elements11 make it easier to work with the
DOM in an OO way, and there has been a lot of great writing on Functional JavaScript12 , but either
would require a bit of shoe-horning, so it felt simpler to keep it procedural.
There are eight source files in this project, but index.html and blocks.css are basic structure
and style for the app and won’t be discussed. Two of the JavaScript files won’t be discussed in
any detail either: util.js contains some helpers and serves as a bridge between different browser
11 http://webcomponents.org/
12 https://leanpub.com/javascript-allonge/read

Dethe Elza 3
implementations—similar to a library like jQuery but in less than 50 lines of code. file.js is a
similar utility used for loading and saving files and serializing scripts.
These are the remaining files:
• block.js is the abstract representation of a block-based language.
• drag.js implements the key interaction of the language: allowing the user to drag blocks
from a list of available blocks (the “menu”) to assemble them into a program (the “script”).
• menu.js has some helper code and is also responsible for actually running the user’s program.
• turtle.js defines the specifics of our block language (turtle graphics) and initializes its
specific blocks. This is the file that would be replaced in order to create a different block
language.

blocks.jsblocks.js
Each block consists of a few HTML elements, styled with CSS, with some JavaScript event handlers
for dragging-and-dropping and modifying the input argument. The blocks.js file helps to create
and manage these groupings of elements as single objects. When a type of block is added to the
block menu, it is associated with a JavaScript function to implement the language, so each block in
the script has to be able to find its associated function and call it when the script runs.

Figure 1.2: An example block

Blocks have two optional bits of structure. They can have a single numeric parameter (with a
default value), and they can be a container for other blocks. These are hard limits to work with, but
would be relaxed in a larger system. In Waterbear there are also expression blocks which can be
passed in as parameters; multiple parameters of a variety of types are supported. Here in the land of
tight constraints we’ll see what we can do with just one type of parameter.

<!-- The HTML structure of a block -->


<div class="block" draggable="true" data-name="Right">
Right
<input type="number" value="5">
degrees
</div>

It’s important to note that there is no real distinction between blocks in the menu and blocks in
the script. Dragging treats them slightly differently based on where they are being dragged from,
and when we run a script it only looks at the blocks in the script area, but they are fundamentally the
same structures, which means we can clone the blocks when dragging from the menu into the script.
The createBlock(name, value, contents) function returns a block as a DOM element
populated with all internal elements, ready to insert into the document. This can be used to create
blocks for the menu, or for restoring script blocks saved in files or localStorage. While it is flexible
this way, it is built specifically for the Blockcode “language” and makes assumptions about it, so
if there is a value it assumes the value represents a numeric argument and creates an input of type
“number”. Since this is a limitation of the Blockcode, this is fine, but if we were to extend the blocks
to support other types of arguments, or more than one argument, the code would have to change.

4 Blockcode: A visual programming toolkit


function createBlock(name, value, contents){
var item = elem('div',
{'class': 'block', draggable: true, 'data-name': name},
[name]
);
if (value !== undefined && value !== null){
item.appendChild(elem('input', {type: 'number', value: value}));
}
if (Array.isArray(contents)){
item.appendChild(
elem('div', {'class': 'container'}, contents.map(function(block){
return createBlock.apply(null, block);
})));
}else if (typeof contents === 'string'){
// Add units (degrees, etc.) specifier
item.appendChild(document.createTextNode(' ' + contents));
}
return item;
}

We have some utilities for handling blocks as DOM elements:


• blockContents(block) retrieves the child blocks of a container block. It always returns a
list if called on a container block, and always returns null on a simple block
• blockValue(block) returns the numerical value of the input on a block if the block has an
input field of type number, or null if there is no input element for the block
• blockScript(block) will return a structure suitable for serializing with JSON, to save blocks
in a form they can easily be restored from
• runBlocks(blocks) is a handler that runs each block in an array of blocks
function blockContents(block){
var container = block.querySelector('.container');
return container ? [].slice.call(container.children) : null;
}

function blockValue(block){
var input = block.querySelector('input');
return input ? Number(input.value) : null;
}

function blockUnits(block){
if (block.children.length > 1 &&
block.lastChild.nodeType === Node.TEXT_NODE &&
block.lastChild.textContent){
return block.lastChild.textContent.slice(1);
}
}

function blockScript(block){
var script = [block.dataset.name];
var value = blockValue(block);
if (value !== null){

Dethe Elza 5
script.push(blockValue(block));
}
var contents = blockContents(block);
var units = blockUnits(block);
if (contents){script.push(contents.map(blockScript));}
if (units){script.push(units);}
return script.filter(function(notNull){ return notNull !== null; });
}

function runBlocks(blocks){
blocks.forEach(function(block){ trigger('run', block); });
}

drag.jsdrag.js
The purpose of drag.js is to turn static blocks of HTML into a dynamic programming language
by implementing interactions between the menu section of the view and the script section. The
user builds their program by dragging blocks from the menu into the script, and the system runs the
blocks in the script area.
We’re using HTML5 drag-and-drop; the specific JavaScript event handlers it requires are defined
here. (For more information on using HTML5 drag-and-drop, see Eric Bidleman’s article13 .) While
it is nice to have built-in support for drag-and-drop, it does have some oddities and some pretty major
limitations, like not being implemented in any mobile browser at the time of this writing.
We define some variables at the top of the file. When we’re dragging, we’ll need to reference
these from different stages of the dragging callback dance.

var dragTarget = null; // Block we're dragging


var dragType = null; // Are we dragging from the menu or from the script?
var scriptBlocks = []; // Blocks in the script, sorted by position

Depending on where the drag starts and ends, drop will have different effects:
• If dragging from script to menu, delete dragTarget (remove block from script).
• If dragging from script to script, move dragTarget (move an existing script block).
• If dragging from menu to script, copy dragTarget (insert new block in script).
• If dragging from menu to menu, do nothing.
During the dragStart(evt) handler we start tracking whether the block is being copied from
the menu or moved from (or within) the script. We also grab a list of all the blocks in the script
which are not being dragged, to use later. The evt.dataTransfer.setData call is used for dragging
between the browser and other applications (or the desktop), which we’re not using, but have to call
anyway to work around a bug.

function dragStart(evt){
if (!matches(evt.target, '.block')) return;
if (matches(evt.target, '.menu .block')){
dragType = 'menu';
}else{
dragType = 'script';
13 http://www.html5rocks.com/en/tutorials/dnd/basics/

6 Blockcode: A visual programming toolkit


}
evt.target.classList.add('dragging');
dragTarget = evt.target;
scriptBlocks = [].slice.call(
document.querySelectorAll('.script .block:not(.dragging)'));
// For dragging to take place in Firefox, we have to set this, even if
// we don't use it
evt.dataTransfer.setData('text/html', evt.target.outerHTML);
if (matches(evt.target, '.menu .block')){
evt.dataTransfer.effectAllowed = 'copy';
}else{
evt.dataTransfer.effectAllowed = 'move';
}
}

While we are dragging, the dragenter, dragover, and dragout events give us opportunities to
add visual cues by highlighting valid drop targets, etc. Of these, we only make use of dragover.

function dragOver(evt){
if (!matches(evt.target, '.menu, .menu *, .script, .script *, .content')) {
return;
}
// Necessary. Allows us to drop.
if (evt.preventDefault) { evt.preventDefault(); }
if (dragType === 'menu'){
// See the section on the DataTransfer object.
evt.dataTransfer.dropEffect = 'copy';
}else{
evt.dataTransfer.dropEffect = 'move';
}
return false;
}

When we release the mouse, we get a drop event. This is where the magic happens. We have
to check where we dragged from (set back in dragStart) and where we have dragged to. Then we
either copy the block, move the block, or delete the block as needed. We fire off some custom events
using trigger() (defined in util.js) for our own use in the block logic, so we can refresh the
script when it changes.

function drop(evt){
if (!matches(evt.target, '.menu, .menu *, .script, .script *')) return;
var dropTarget = closest(
evt.target, '.script .container, .script .block, .menu, .script');
var dropType = 'script';
if (matches(dropTarget, '.menu')){ dropType = 'menu'; }
// stops the browser from redirecting.
if (evt.stopPropagation) { evt.stopPropagation(); }
if (dragType === 'script' && dropType === 'menu'){
trigger('blockRemoved', dragTarget.parentElement, dragTarget);
dragTarget.parentElement.removeChild(dragTarget);
}else if (dragType ==='script' && dropType === 'script'){

Dethe Elza 7
if (matches(dropTarget, '.block')){
dropTarget.parentElement.insertBefore(
dragTarget, dropTarget.nextSibling);
}else{
dropTarget.insertBefore(dragTarget, dropTarget.firstChildElement);
}
trigger('blockMoved', dropTarget, dragTarget);
}else if (dragType === 'menu' && dropType === 'script'){
var newNode = dragTarget.cloneNode(true);
newNode.classList.remove('dragging');
if (matches(dropTarget, '.block')){
dropTarget.parentElement.insertBefore(
newNode, dropTarget.nextSibling);
}else{
dropTarget.insertBefore(newNode, dropTarget.firstChildElement);
}
trigger('blockAdded', dropTarget, newNode);
}
}

The dragEnd(evt) is called when we mouse up, but after we handle the drop event. This is
where we can clean up, remove classes from elements, and reset things for the next drag.

function _findAndRemoveClass(klass){
var elem = document.querySelector('.' + klass);
if (elem){ elem.classList.remove(klass); }
}

function dragEnd(evt){
_findAndRemoveClass('dragging');
_findAndRemoveClass('over');
_findAndRemoveClass('next');
}

menu.jsmenu.js
The file menu.js is where blocks are associated with the functions that are called when they run,
and contains the code for actually running the script as the user builds it up. Every time the script is
modified, it is re-run automatically.
“Menu” in this context is not a drop-down (or pop-up) menu, like in most applications, but is the
list of blocks you can choose for your script. This file sets that up, and starts the menu off with a
looping block that is generally useful (and thus not part of the turtle language itself). This is kind of
an odds-and-ends file, for things that may not fit anywhere else.
Having a single file to gather random functions in is useful, especially when an architecture is
under development. My theory of keeping a clean house is to have designated places for clutter, and
that applies to building a program architecture too. One file or module becomes the catch-all for
things that don’t have a clear place to fit in yet. As this file grows it is important to watch for emerging
patterns: several related functions can be spun off into a separate module (or joined together into a
more general function). You don’t want the catch-all to grow indefinitely, but only to be a temporary
holding place until you figure out the right way to organize the code.

8 Blockcode: A visual programming toolkit


We keep around references to menu and script because we use them a lot; no point hunting
through the DOM for them over and over. We’ll also use scriptRegistry, where we store the
scripts of blocks in the menu. We use a very simple name-to-script mapping which does not support
either multiple menu blocks with the same name or renaming blocks. A more complex scripting
environment would need something more robust.
We use scriptDirty to keep track of whether the script has been modified since the last time it
was run, so we don’t keep trying to run it constantly.

var menu = document.querySelector('.menu');


var script = document.querySelector('.script');
var scriptRegistry = {};
var scriptDirty = false;

When we want to notify the system to run the script during the next frame handler, we call
runSoon() which sets the scriptDirty flag to true. The system calls run() on every frame, but
returns immediately unless scriptDirty is set. When scriptDirty is set, it runs all the script
blocks, and also triggers events to let the specific language handle any tasks it needs before and after
the script is run. This decouples the blocks-as-toolkit from the turtle language to make the blocks
re-usable (or the language pluggable, depending how you look at it).
As part of running the script, we iterate over each block, calling runEach(evt) on it, which sets
a class on the block, then finds and executes its associated function. If we slow things down, you
should be able to watch the code execute as each block highlights to show when it is running.
The requestAnimationFrame method below is provided by the browser for animation. It takes
a function which will be called for the next frame to be rendered by the browser (at 60 frames per
second) after the call is made. How many frames we actually get depends on how fast we can get
work done in that call.

function runSoon(){ scriptDirty = true; }

function run(){
if (scriptDirty){
scriptDirty = false;
Block.trigger('beforeRun', script);
var blocks = [].slice.call(
document.querySelectorAll('.script > .block'));
Block.run(blocks);
Block.trigger('afterRun', script);
}else{
Block.trigger('everyFrame', script);
}
requestAnimationFrame(run);
}
requestAnimationFrame(run);

function runEach(evt){
var elem = evt.target;
if (!matches(elem, '.script .block')) return;
if (elem.dataset.name === 'Define block') return;
elem.classList.add('running');
scriptRegistry[elem.dataset.name](elem);

Dethe Elza 9
elem.classList.remove('running');
}

We add blocks to the menu using menuItem(name, fn, value, contents) which takes a
normal block, associates it with a function, and puts in the menu column.

function menuItem(name, fn, value, units){


var item = Block.create(name, value, units);
scriptRegistry[name] = fn;
menu.appendChild(item);
return item;
}

We define repeat(block) here, outside of the turtle language, because it is generally useful in
different languages. If we had blocks for conditionals and reading and writing variables they could
also go here, or into a separate trans-language module, but right now we only have one of these
general-purpose blocks defined.

function repeat(block){
var count = Block.value(block);
var children = Block.contents(block);
for (var i = 0; i < count; i++){
Block.run(children);
}
}
menuItem('Repeat', repeat, 10, []);

turtle.jsturtle.js
turtle.js is the implementation of the turtle block language. It exposes no functions to the rest of
the code, so nothing else can depend on it. This way we can swap out the one file to create a new
block language and know nothing in the core will break.
Turtle programming is a style of graphics programming, first popularized by Logo, where you
have an imaginary turtle carrying a pen walking on the screen. You can tell the turtle to pick up
the pen (stop drawing, but still move), put the pen down (leaving a line everywhere it goes), move
forward a number of steps, or turn a number of degrees. Just those commands, combined with
looping, can create amazingly intricate images.
In this version of turtle graphics we have a few extra blocks. Technically we don’t need both
turn right and turn left because you can have one and get the other with negative numbers.
Likewise move back can be done with move forward and negative numbers. In this case it felt
more balanced to have both.
The image above was formed by putting two loops inside another loop and adding a move
forward and turn right to each loop, then playing with the parameters interactively until I liked
the image that resulted.

var PIXEL_RATIO = window.devicePixelRatio || 1;


var canvasPlaceholder = document.querySelector('.canvas-placeholder');
var canvas = document.querySelector('.canvas');
var script = document.querySelector('.script');
var ctx = canvas.getContext('2d');

10 Blockcode: A visual programming toolkit


Figure 1.3: Example of Turtle code running

var cos = Math.cos, sin = Math.sin, sqrt = Math.sqrt, PI = Math.PI;


var DEGREE = PI / 180;
var WIDTH, HEIGHT, position, direction, visible, pen, color;

The reset() function clears all the state variables to their defaults. If we were to support multiple
turtles, these variables would be encapsulated in an object. We also have a utility, deg2rad(deg),
because we work in degrees in the UI, but we draw in radians. Finally, drawTurtle() draws the
turtle itself. The default turtle is simply a triangle, but you could override this to draw a more
aesthetically-pleasing turtle.
Note that drawTurtle uses the same primitive operations that we define to implement the turtle
drawing. Sometimes you don’t want to reuse code at different abstraction layers, but when the
meaning is clear it can be a big win for code size and performance.

function reset(){
recenter();
direction = deg2rad(90); // facing "up"
visible = true;
pen = true; // when pen is true we draw, otherwise we move without drawing
color = 'black';
}

function deg2rad(degrees){ return DEGREE * degrees; }

function drawTurtle(){
var userPen = pen; // save pen state
if (visible){
penUp(); _moveForward(5); penDown();
_turn(-150); _moveForward(12);

Dethe Elza 11
_turn(-120); _moveForward(12);
_turn(-120); _moveForward(12);
_turn(30);
penUp(); _moveForward(-5);
if (userPen){
penDown(); // restore pen state
}
}
}

We have a special block to draw a circle with a given radius at the current mouse position. We
special-case drawCircle because, while you can certainly draw a circle by repeating MOVE 1 RIGHT
1 360 times, controlling the size of the circle is very difficult that way.
function drawCircle(radius){
// Math for this is from http://www.mathopenref.com/polygonradius.html
var userPen = pen; // save pen state
if (visible){
penUp(); _moveForward(-radius); penDown();
_turn(-90);
var steps = Math.min(Math.max(6, Math.floor(radius / 2)), 360);
var theta = 360 / steps;
var side = radius * 2 * Math.sin(Math.PI / steps);
_moveForward(side / 2);
for (var i = 1; i < steps; i++){
_turn(theta); _moveForward(side);
}
_turn(theta); _moveForward(side / 2);
_turn(90);
penUp(); _moveForward(radius); penDown();
if (userPen){
penDown(); // restore pen state
}
}
}

Our main primitive is moveForward, which has to handle some elementary trigonometry and
check whether the pen is up or down.
function _moveForward(distance){
var start = position;
position = {
x: cos(direction) * distance * PIXEL_RATIO + start.x,
y: -sin(direction) * distance * PIXEL_RATIO + start.y
};
if (pen){
ctx.lineStyle = color;
ctx.beginPath();
ctx.moveTo(start.x, start.y);
ctx.lineTo(position.x, position.y);
ctx.stroke();
}

12 Blockcode: A visual programming toolkit


}

Most of the rest of the turtle commands can be easily defined in terms of what we’ve built above.

function penUp(){ pen = false; }


function penDown(){ pen = true; }
function hideTurtle(){ visible = false; }
function showTurtle(){ visible = true; }
function forward(block){ _moveForward(Block.value(block)); }
function back(block){ _moveForward(-Block.value(block)); }
function circle(block){ drawCircle(Block.value(block)); }
function _turn(degrees){ direction += deg2rad(degrees); }
function left(block){ _turn(Block.value(block)); }
function right(block){ _turn(-Block.value(block)); }
function recenter(){ position = {x: WIDTH/2, y: HEIGHT/2}; }

When we want a fresh slate, the clear function restores everything back to where we started.

function clear(){
ctx.save();
ctx.fillStyle = 'white';
ctx.fillRect(0,0,WIDTH,HEIGHT);
ctx.restore();
reset();
ctx.moveTo(position.x, position.y);
}

When this script first loads and runs, we use our reset and clear to initialize everything and
draw the turtle.

onResize();
clear();
drawTurtle();

Now we can use the functions above, with the Menu.item function from menu.js, to make blocks
for the user to build scripts from. These are dragged into place to make the user’s programs.

Menu.item('Left', left, 5, 'degrees');


Menu.item('Right', right, 5, 'degrees');
Menu.item('Forward', forward, 10, 'steps');
Menu.item('Back', back, 10, 'steps');
Menu.item('Circle', circle, 20, 'radius');
Menu.item('Pen up', penUp);
Menu.item('Pen down', penDown);
Menu.item('Back to center', recenter);
Menu.item('Hide turtle', hideTurtle);
Menu.item('Show turtle', showTurtle);

Dethe Elza 13
1.3 Lessons Learned
Why Not Use MVC?
Model-View-Controller (MVC) was a good design choice for Smalltalk programs in the ’80s and it
can work in some variation or other for web apps, but it isn’t the right tool for every problem. All
the state (the “model” in MVC) is captured by the block elements in a block language anyway, so
replicating it into Javascript has little benefit unless there is some other need for the model (if we
were editing shared, distributed code, for instance).
An early version of Waterbear went to great lengths to keep the model in JavaScript and sync it
with the DOM, until I noticed that more than half the code and 90% of the bugs were due to keeping
the model in sync with the DOM. Eliminating the duplication allowed the code to be simpler and
more robust, and with all the state on the DOM elements, many bugs could be found simply by
looking at the DOM in the developer tools. So in this case there is little benefit to building further
separation of MVC than we already have in HTML/CSS/JavaScript.

Toy Changes Can Lead to Real Changes


Building a small, tightly scoped version of the larger system I work on has been an interesting
exercise. Sometimes in a large system there are things you are hesitant to change because they affect
too many other things. In a tiny, toy version you can experiment freely and learn things which you
can then take back to the larger system. For me, the larger system is Waterbear and this project has
had a huge impact on the way Waterbear is structured.

Small Experiments Make Failure OK


Some of the experiments I was able to do with this stripped-down block language were:
• using HTML5 drag-and-drop,
• running blocks directly by iterating through the DOM calling associated functions,
• separating the code that runs cleanly from the HTML DOM,
• simplified hit testing while dragging,
• building our own tiny vector and sprite libraries (for the game blocks), and
• “live coding” where the results are shown whenever you change the block script.
The thing about experiments is that they do not have to succeed. We tend to gloss over failures
and dead ends in our work, where failures are punished instead of treated as important vehicles for
learning, but failures are essential if you are going to push forward. While I did get the HTML5
drag-and-drop working, the fact that it isn’t supported at all on any mobile browser means it is
a non-starter for Waterbear. Separating the code out and running code by iterating through the
blocks worked so well that I’ve already begun bringing those ideas to Waterbear, with excellent
improvements in testing and debugging. The simplified hit testing, with some modifications, is also
coming back to Waterbear, as are the tiny vector and sprite libraries. Live coding hasn’t made it to
Waterbear yet, but once the current round of changes stabilizes I may introduce it.

What Are We Trying to Build, Really?


Building a small version of a bigger system puts a sharp focus on what the important parts really
are. Are there bits left in for historical reasons that serve no purpose (or worse, distract from the

14 Blockcode: A visual programming toolkit


purpose)? Are there features no-one uses but you have to pay to maintain? Could the user interface be
streamlined? All these are great questions to ask while making a tiny version. Drastic changes, like
re-organizing the layout, can be made without worrying about the ramifications cascading through a
more complex system, and can even guide refactoring the complex system.

A Program is a Process, Not a Thing


There are things I wasn’t able to experiment with in the scope of this project that I may use the
blockcode codebase to test out in the future. It would be interesting to create “function” blocks which
create new blocks out of existing blocks. Implementing undo/redo would be simpler in a constrained
environment. Making blocks accept multiple arguments without radically expanding the complexity
would be useful. And finding various ways to share block scripts online would bring the webbiness
of the tool full circle.

15
[chapter 2]

A Continuous Integration System


Malini Das

2.1 What is a Continuous Integration System?


When developing software, we want to be able to verify that our new features or bug fixes are safe
and work as expected. We do this by running tests against our code. Sometimes, developers will run
tests locally to verify that their changes are safe, but developers may not have the time to test their
code on every system their software runs in. Further, as more and more tests are added the amount
of time required to run them, even only locally, becomes less viable. Because of this, continuous
integration systems have been created.
Continuous Integration (CI) systems are dedicated systems used to test new code. Upon a commit
to the code repository, it is the responsibility of the continuous integration system to verify that this
commit will not break any tests. To do this, the system must be able to fetch the new changes, run
the tests and report its results. Like any other system, it should also be failure resistant. This means
if any part of the system fails, it should be able to recover and continue from that point.
This test system should also handle load well, so that we can get test results in a reasonable
amount of time in the event that commits are being made faster than the tests can be run. We can
achieve this by distributing and parallelizing the testing effort. This project will demonstrate a small,
bare-bones distributed continuous integration system that is designed for extensibility.

2.2 Project Limitations and Notes


This project uses Git as the repository for the code that needs to be tested. Only standard source code
management calls will be used, so if you are unfamiliar with Git but are familiar with other version
control systems (VCS) like svn or Mercurial, you can still follow along.
Due to the limitations of code length and unittest, I simplified test discovery. We will only run
tests that are in a directory named tests within the repository.
Continuous integration systems monitor a master repository which is usually hosted on a web
server, and not local to the CI’s file systems. For the cases of our example, we will use a local
repository instead of a remote repository.
Continuous integration systems need not run on a fixed, regular schedule. You can also have them
run every few commits, or per-commit. For our example case, the CI system will run periodically.
This means if it is set up to check for changes in five-second periods, it will run tests against the most
Another Random Scribd Document
with Unrelated Content
tariff act have been proclaimed with Portugal, with Italy and
with Germany. Commercial conventions under the general
limitations of the fourth section of the same act have been
concluded with Nicaragua, with Ecuador, with the Dominican
Republic, with Great Britain on behalf of the island of
Trinidad and with Denmark on behalf of the island of St.
Croix. These will be early communicated to the Senate.
Negotiations with other governments are in progress for the
improvement and security of our commercial relations."

The question of the ratification of all these treaties was


pending in the Senate when the term of the 56th Congress
expired, March 4, 1901. Opposing interests in the United
States seemed likely then to defeat their ratification. On the
last day of the special session of the Senate, March 5-9, an
agreement extending the time for the ratification of the
French reciprocity treaty was received and referred to the
committee on foreign relations. On the 15th of March,
Secretary Hay and Lord Pauncefote signed protocols extending
for one year the time of ratification for four of the British
West Indian reciprocity treaties, namely, Jamaica, Bermuda,
Guiana and Turks and Caicos islands.

UNITED STATES OF AMERICA: A. D. 1900.


Naval strength.

See (in this volume)


NAVIES OF THE SEA POWERS.

UNITED STATES OF AMERICA: A. D. 1900.


State of Indian schools.
Recent Indian policy.
Indian population.

See (in this volume)


INDIANS, AMERICAN: A. D. 1899-1900.
UNITED STATES OF AMERICA: A. D. 1900 (January).
Report of the First Philippine Commission.

See (in this volume)


PHILIPPINE ISLANDS: A. D. 1900 (JANUARY).

UNITED STATES OF AMERICA: A. D. 1900 (January-March).


The outbreak of the "Boxers" in northern China.

See (in this volume)


CHINA: A. D. 1900 (JANUARY-MARCH).

UNITED STATES OF AMERICA: A. D. 1900 (February).


Negotiation of the Hay-Pauncefote Convention relative
to the Nicaragua Canal.

See (in this volume)


CANAL, INTEROCEANIC: A. D. 1900 (DECEMBER).

UNITED STATES OF AMERICA: A. D. 1900 (March-December).


Passage of the Financial Bill.
Settlement of the question of the monetary standard.
The working of the act.

Legislation in the direction sought by the advocates of the


gold standard and of a reformed monetary system for the
country, whose agitations are referred to above, was attained
in the spring of 1900, by the passage of an important
"Financial Bill" which became law on the 14th of March.

See (in this volume)


UNITED STATES OF AMERICA: A. D. 1896-1898

The provisions and the effect of the Act were summarized at


the time by the Secretary of the Treasury, Mr. Gage, in a
published statement, as follows:
"The financial bill has for its first object what its title
indicates, the fixing of the standard of value and the
maintaining at a parity with that standard of all forms of
money issued or coined by the United States. It reaffirms that
the unit of value is the dollar, consisting of 25.8 grains of
gold, nine tenths fine, but from that point it goes on to make
it the duty of the Secretary of the Treasury to maintain all
forms of money issued or coined at a parity with this
standard. It puts into the hands of the Secretary ample power
to do that.
{640}
For that purpose, the bill provides in the Treasury bureaus of
issue and redemption and transfers from the general fund of
the Treasury's cash $150,000,000 in gold coin and bullion to
redemption fund, that gold to be used for the redemption of
United States notes and Treasury notes. That fund is
henceforth absolutely cut out of and separated from the cash
balance in the Treasury and the available cash balance will
hereafter show a reduction of $150,000,000 from the figures
that have heretofore prevailed. This $150,000,000 redemption
fund is to be used for no other purpose than the redemption of
United States notes and Treasury notes and those notes so
redeemed may be exchanged for the gold in the general fund or
with the public, so that the reserve fund is kept full with
gold to the $150,000,000 limit. If redemptions go on so that
the gold in this reserve fund is reduced below $100,000,000,
and the Secretary is unable to build it up to the $150,000,000
mark by exchange for gold in the general fund or otherwise, he
is given power to sell bonds and it is made his duty to
replenish the gold to the $150,000,000 mark by such means.

"The 'endless chain' is broken by a provision which prohibits


the use of notes so redeemed to meet deficiencies in the
current revenues. The act provides for the ultimate retirement
of all the Treasury notes issued in payment for silver bullion
under the Sherman act. As fast as that bullion is coined into
silver dollars Treasury notes are to be retired and replaced
with an equal amount of silver certificates. The measure
authorizes the issue of gold certificates in exchange for
deposits of gold coin, the same as at present, but suspends
that authority whenever and so long as the gold in the
redemption fund is below $100,000,000 and gives to the
Secretary the option to suspend the issue of such certificates
whenever the silver certificates and United States notes in
the general fund of the Treasury exceed $40,000,000. The bill
provides for a larger issue of silver certificates, by
declaring that hereafter silver certificates shall be issued
only in denominations of $10 and under except as to 10 per
cent. of the total volume. Room is made for this larger use of
silver certificates in the way of small bills by another
provision which makes it necessary as fast as the present
silver certificates of high denominations are broken up into
small bills to cancel a similar volume of United States notes
of small denominations and replace them with notes of
denominations of $10 and upward. Further room is made for the
circulation of small silver certificates by a clause which
permits national banks to have only one third of their capital
in denomination under $10.

"One clause of the bill which the public will greatly


appreciate is the right it gives to the Secretary to coin any
of the 1890 bullion into subsidiary silver coins up to a limit
of $100,000,000. There has for years been a scarcity of
subsidiary silver during periods of active retail trade, but
this provision will give the Treasury ample opportunity to
supply all the subsidiary silver that is needed. Another
provision that the public will greatly appreciate is the
authority given to the Secretary to recoin worn and uncurrent
subsidiary silver now in the Treasury or hereafter received.

"A distinct feature of the bill is in reference to refunding


the 3 per cent. Spanish war loan, the 2 per cent. bonds
maturing in 1907 and the 5 per cent. bonds maturing in 1904, a
total of $839,000,000, into new 2 per cent. bonds. These new 2
per cent. bonds will not be offered for sale, but will only be
issued in exchange for an equal amount, face value, of old
bonds. This exchange will save the Government, after deducting
the premium paid, nearly $23,000,000, if all the holders of the
old bonds exchange them for the new ones. National banks that
take out circulation based on the new bonds are to be taxed
only one half of 1 per cent. on the average amount of
circulation outstanding, while those who have circulation
based on a deposit of old bonds will be taxed, as at present,
1 per cent. There are some other changes in the national
banking act. The law permits national banks with $25,000
capital to be organized in places of 3,000 inhabitants or
less, whereas heretofore the minimum capital has been $50,000.
It also permits banks to issue circulation on all classes of
bonds deposited up to the par value of the bonds, instead of
90 per cent. of their face, as heretofore. This ought to make
an immediate increase in national bank circulation of
something like $24,000,000, as the amount of bonds now
deposited to secure circulation is about $242,000,000. If the
price of the new 2s is not forced so high in the market that
there is no profit left to national banks in taking out
circulation, we may also look for a material increase in
national bank circulation based on additional deposits of
bonds. National banks are permitted under the law to issue
circulation up to an amount equal to their capital. The total
capital of all national banks is $616,000,000. The total
circulation outstanding is $253,000,000. There is, therefore,
a possibility of an increase in circulation of $363,000,000,
although the price of the 2 per cent. bonds, as already
foreshadowed by market quotations in advance of their issue,
promises to be so high that the profit to the banks in taking
out circulation will not be enough to make the increase
anything like such a possible total."

Upon the working of the Act, during the first nine months of
its operation, Secretary Gage remarked as follows, in his
annual report dated December 14, 1900:
"The operation of the act of March 14 last with respect to
these two important matters of our finances has well
exemplified its wisdom. Confidence in the purpose and power of
the Government to maintain the gold standard has been greatly
strengthened. The result is that gold flows toward the
Treasury instead of away from it. At the date of this report
the free gold in the Treasury is larger in amount than at any
former period in our history. Including the $150,000,000
reserve, the gold in the Treasury belonging to the Government
amounts to over $242,000,000, while the Treasury holds,
besides, more than $230,000,000, against which certificates
have been issued. That provision of the act which liberalized
the conditions of bank-note issue was also wise and timely.
Under it, … there has been an increase of some $77,000,000 in
bank-note issues. To this fact may be chiefly attributed the
freedom from stress for currency to handle the large harvests
of cotton, wheat, and corn. In this respect the year has been
an exception to the general rule of stringency which for
several years has so plainly marked the autumn season.

{641}

"Nevertheless, the measures referred to, prolific as they have


been in good results, will yet need re-enforcement in some
important particulars. Thus, as to the redemption fund
provided for in said act, while the powers conferred upon the
Secretary are probably ample to enable a zealous and watchful
officer to protect fully the gold reserve, there appears to be
lacking sufficient mandatory requirement to furnish complete
confidence in the continued parity, under all conditions,
between our two forms of metallic money, silver and gold. Upon
this point further legislation may become desirable. As to the
currency, while the liberalizing of conditions has, as previously
noted, found response in a necessary increase of bank-note
issues, there is under our present system no assurance
whatever that the volume of bank currency will be continuously
responsive to the country's needs, either by expanding as such
needs require or by contracting when superfluous in amount.
The truth is that safe and desirable as is our currency system
in many respects, it is not properly related. The supply of
currency is but remotely, if at all, influenced by the ever
changing requirements of trade and industry. It is related
most largely, if not entirely, to the price of Government
bonds in the market."

Annual Report of the Secretary of the Treasury, 1900,


pages 72-73.

UNITED STATES OF AMERICA: A. D. 1900 (April).


Speech of Senator Hoar in denial of the right of the
government of the United States, under the Constitution, to
hold the Philippine Islands as a subject state.

On the 17th of April, the following joint resolution was under


consideration in the Senate: "Be it resolved by the Senate and
House of Representatives of the United States of America in
Congress assembled, that the Philippine Islands are territory
belonging to the United States; that it is the intention of
the United States to retain them as such and to establish and
maintain such governmental control throughout the archipelago
as the situation may demand." Senator Hoar, of Massachusetts,
spoke in opposition to the resolution, and some passages from
his speech are quoted here, because they are notably
representative of the ground and spirit of an opposition which
existed within the party controlling the government to the war
of subjugation in the Philippine Islands, to which the party
and the government were finally committed by the adoption of
this Congressional declaration. The attitude and argument of
parties on the question are set forth below, in the platforms
and manifestos of the presidential election. This speech
exhibits a feeling on that question which was overridden in
the winning party, and it has an importance both forensic and
historical:
"The American people, so far as I know, were all agreed that
their victory [in the Spanish American war] brought with it
the responsibility of protecting the liberated peoples from
the cupidity of any other power until they could establish
their own independence in freedom and in honor. I stand here
to-day to plead with you not to abandon the principles that
have brought these things to pass. I implore you to keep to
the policy that has made the country great, that has made the
Republican party great, that has made the President great. I
have nothing new to say. But I ask you to keep in the old
channels, and to keep off the old rocks laid down in the old
charts, and to follow the old sailing orders that all the old
captains of other days have obeyed, to take your bearings, as
of old, from the north star,

Of whose true fixed and resting quality


There is no fellow in the firmament,

and not from this meteoric light of empire.

"Especially, if I could, would I persuade the great Republican


party to come back again to its old faith, to its old
religion, before it is too late. There is yet time. The
President has said again and again that his is only an ad
interim policy until Congress shall act. It is not yet too
late. Congress has rejected, unwisely, as I think, some
declarations for freedom. But the two Houses have not as yet
committed themselves to despotism. The old, safe path, the
path alike of justice and of freedom, is still easy. It is a
path familiar, of old, to the Republican party. If we have
diverged from it for the first time, everything in our
history, everything in our own nature calls us back. The great
preacher of the English church tells you how easy is the
return of a great and noble nature from the first departure
from rectitude:—
'For so a taper, when its crown of flame is newly blown off,
retains a nature so symbolical to light,
that it will with greediness reenkindle and snatch a ray
from the neighbor fire.'

"I, for one, believed, and still believe that the pathway to
prosperity and glory for the country was also the pathway to
success and glory for the Republican party. I thought the two
things inseparable. If, when we made the treaty of peace, we
had adhered to the purpose we declared when we declared war;
if we had dealt with the Philippine Islands as we promised to
deal, have dealt, and expect to deal with Cuba, the country
would have escaped the loss of 6,000 brave soldiers, other
thousands of wrecked and shattered lives, the sickness of many
more, the expenditure of hundreds of millions, and, what is
far worse than all, the trampling under foot of its cherished
ideals. There would have been to-day a noble republic in the
East, sitting docile at our feet, receiving from us
civilization, laws, manners, and giving in turn everything the
gratitude of a free people could give-love, obedience, trade.
The Philippine youth would throng our universities; our
Constitution, our Declaration, the lives of Washington and
Lincoln, the sayings of Jefferson and Franklin would have been
the textbooks of their schools. How our orators and poets
would have delighted to contrast America liberating and
raising up the republic of Asia, with England subduing and
trampling under foot the republic of Africa. Nothing at home
could have withstood the great party and the great President
who had done these things. We should have come from the next
election with a solid North and have carried half the South.
You would at least have been spared the spectacle of great
Republican States rising in revolt against Republican
policies. I do not expect to accomplish anything for liberty
in the Philippine Islands but through the Republican party.
Upon it the fate of these Islands for years to come is to
depend. If that party can not be persuaded, the case is in my
judgment for the present hopeless. …
{642}

"The practical question which divided the American people last


year, and which divides them to-day, is this: Whether in
protecting the people of the Philippine Islands from the
ambition and cupidity of other nations we are bound to protect
them from our own. … In dealing with this question, Mr.
President, I do not mean to enter upon any doubtful ground. I
shall advance no proposition ever seriously disputed in this
country till within twelve months. … If to think as I do in
regard to the interpretation of the Constitution; in regard to
the mandates of the moral law or the law of nations, to which
all men and all nations must render obedience; in regard to
the policies which are wisest for the conduct of the State, or
in regard to those facts of recent history in the light of
which we have acted or are to act hereafter, be treason, then
Washington was a traitor; then Jefferson was a traitor; then
Jackson was a traitor; then Franklin was a traitor; then
Sumner was a traitor; then Lincoln was a traitor; then Webster
was a traitor; then Clay was a traitor; then Corwin was a
traitor; then Kent was a traitor; then Seward was a traitor;
then McKinley, within two years, was a traitor; then the
Supreme Court of the United States has been in the past a nest
and hotbed of treason; then the people of the United States,
for more than a century, have been traitors to their own flag
and their own Constitution.

"'We are presented with an issue that can be clearly and


sharply stated as a question of constitutional power, a
question of international law, a question of justice and
righteousness, or a question of public expediency. This can be
stated clearly and sharply in the abstract, and it can be put
clearly and sharply by an illustration growing out of existing
facts.

"The constitutional question is: Has Congress the power, under


our Constitution, to hold in subjection unwilling vassal
States?

"The question of international law is: Can any nation


rightfully convey to another sovereignty over an unwilling
people who have thrown off its dominion, asserted their
independence, established a government of their own, over whom
it has at the time no practical control, from whose territory
it has been disseized, and which it is beyond its power to
deliver?

"The question of justice and righteousness is: Have we the


right to crush and hold under our feet an unwilling and
subject people whom we had treated as allies, whose
independence we are bound in good faith to respect, who had
established their own free government, and who had trusted us?

"The question of public expediency is: Is it for our advantage


to promote our trade at the cannon's mouth and at the point of
the bayonet?

"All these questions can be put in a way of practical


illustration by inquiring whether we ought to do what we have
done, are doing, and mean to do in the case of Cuba; or what
we have done, are doing, and some of you mean to do in the
case of the Philippine Islands.

"It does not seem to me to be worth while to state again at


length the constitutional argument which I have addressed to
the Senate heretofore. It has been encountered with eloquence,
with clearness and beauty of statement, and, I have no doubt,
with absolute sincerity by Senators who have spoken upon the
other side. But the issue between them and me can be summed up
in a sentence or two, and if, so stated, it can not be made
clear to any man's apprehension, I despair of making it clear
by any elaboration or amplification. I admit that the United
States may acquire and hold property, and may make rules and
regulations for its disposition. I admit that, like other
property, the United States may acquire and hold land. It may
acquire it by purchase. It may acquire it by treaty. It may
acquire it by conquest. And it may make rules and regulations
for its disposition and government, however it be acquired.
When there are inhabitants upon the land so acquired it may
make laws for their government. But the question between me
and the gentlemen on the other side is this: Is this
acquisition of territory, of land or other property, whether
gained by purchase, conquest, or treaty, a constitutional end
or only a means to a constitutional end? May you acquire,
hold, and govern territory or other property as an end for
which our Constitution was framed, or is it only a means
toward some other and further end? May you acquire, hold, and
govern property by conquest, treaty, or purchase for the sole
object of so holding and governing it, without the
consideration of any further constitutional purpose? Or must
you hold it for a constitutional purpose only, such as the
making of new States, the national defense and security, the
establishment of a seat of government, or the construction of
forts, harbors, and like works, which, of course, are
themselves for the national defense and security?

"I hold that this acquisition, holding and governing, can be


only a means for a constitutional end—the creation of new
States or some other of the constitutional purposes to which I
have adverted. And I maintain that you can no more hold and
govern territory than you can hold and manage cannon or fleets
for any other than a constitutional end; and I maintain that
the holding in subjection an alien people, governing them
against their will for any fancied advantage to them, is not
only not an end provided for by the Constitution, but is an
end prohibited therein. … It is an end which the generation
which framed the Constitution and the Declaration of
Independence declared was unrighteous and abhorrent. So, in my
opinion, we have no constitutional power to acquire territory
for the purpose of holding it in subjugation, in a state of
vassalage or serfdom, against the will of its people.

"It is to be noted just here that we have acquired no


territory or other property in the Philippine Islands, save at
few public buildings. By every other acquisition of territory
the United States became a great land owner. She owned the
public lands as she had owned the public lands in the
Northwest ceded to her by the old States. But you own nothing
in the Philippines. The people own their farms and dwellings
and cities. The religious orders own the rest. The Filipinos
desire to do what our English ancestors did in the old days
when England was Catholic. The laity feared that the Church
would engross all the land. So they passed their statute of
mortmain. You have either got to let the people of the
Philippine Islands settle this matter for themselves, or you
must take upon you the delicate duty of settling it for them.
{643}
Your purchase or conquest is a purchase or conquest of nothing
but sovereignty. It is a sovereignty over a people who are
never to be admitted to exercise it or to share it. In the
present case we have not, I repeat, bought any property. We
have undertaken to buy mere sovereignty. There were no public
lands in the Philippine Islands, the property of Spain, which
we have bought and paid for. The mountains of iron and the
nuggets of gold and the hemp-bearing fields—do you purpose to
strip the owners of their rightful title? We have undertaken
to buy allegiance, pure and simple. And allegiance is just
what the law of nations declares you can not buy. …

"I have been unable to find a single reputable authority more


than twelve months old for the power now claimed for Congress
to govern dependent nations or territories not expected to
become States. The contrary, until this war broke out, has
been taken as too clear for reasonable question. I content
myself with a few authorities. Among them are Daniel Webster,
William H. Seward, the Supreme Court of the United States,
James Madison.
"Daniel Webster said in the Senate, March 23, 1848: 'Arbitrary
governments may have territories and distant possessions,
because arbitrary governments may rule them by different laws
and different systems. We can do no such thing. They must be
of us, part of us, or else strangers. I think I see a course
adopted which is likely to turn the Constitution of the land
into a deformed monster, into a curse rather than a blessing;
in fact, a frame of an unequal government, not founded on
popular representation, not founded on equality, but on the
grossest inequality; and I think that this process will go on,
or that there is danger that it will go on, until this Union
shall fall to pieces. I resist it to-day and always! Whoever
falters or whoever flies, I continue the contest!'

"James Madison said in the Federalist: 'The object of the


Federal Constitution is to secure the union of the thirteen
primitive States, which we know to be practicable; and to add
to them such other States as may arise in their own bosoms, or
in their neighborhood, which we can not doubt will be
practicable.'

James Madison,
Federalist, Number 14.

"William H. Seward said: 'It is a remarkable feature of the


Constitution of the United States that its framers never
contemplated colonies, or provinces, or territories at all. On
the other hand, they contemplated States only, nothing less
than States, perfect States, equal States, as they are called
here, sovereign States. … There is reason—there is sound
political wisdom in this provision of the Constitution
excluding colonies, which are always subject to oppression,
and excluding provinces, which always tend to corrupt and
ultimately to break down the parent State.'

Seward's Works
Volume 1, page 122.

'By the Constitution of the United States, there are no


subjects, Every citizen of any one State is a free and equal
citizen of the United States. Again, by the Constitution of
the United States there are no permanent provinces or
dependencies.'

Seward's Works
Volume 4, page 167.

"The Supreme Court of the United States, in the case of


Fleming vs. Page, said: 'The genius and character of our
institutions are peaceful; and the power to declare war was
not conferred upon Congress for the purposes of aggression or
aggrandizement, but to enable the Government to vindicate by
arms, if it should become necessary, its own rights and the
rights of its citizens. A war, therefore, declared by
Congress, can never be presumed to be waged for the purpose of
conquest or the acquisition of territory; nor does the law
declaring the war imply an authority to the President to
enlarge the limits of the United States by subjugating the
enemy's country.'

"Our territories, so far, have all been places where Americans


would go to dwell as citizens, to establish American homes, to
obtain honorable employment, and to build a State. Will any
man go to the Philippine Islands to dwell, except to help
govern the people, or to make money by a temporary residence?

"When hostilities broke out, February 5, 1899, we had no


occupancy of and no title of any kind to any portion of the
Philippine territory, except the town and bay of Manila.
Everything else was in the peaceful possession of the
inhabitants. In such a condition of things, Mr. President,
international law speaks to us with its awful mandate. It
pronounces your proposed action sheer usurpation and robbery.
You have no better title, according to the law of nations, to
reduce this people to subjection than you have to subjugate
Mexico or Haiti or Belgium or Switzerland. This is the settled
doctrine, as declared by our own great masters of
jurisprudence. You have no right, according to tho law of
nations, to obtain by purchase or acquisition sovereignty over
a people which is not actually exercised by the country which
undertakes to convey it or yield it. We have not yet completed
the acquisition. But at the time we entered upon it, and at
the time of this alleged purchase, the people of the
Philippine Islands, as appears by General Otis's report, by
Admiral Dewey's report, and the reports of officers for whom
they vouched, held their entire territory, with the exception
of the single town of Manila. They had, as appears from these
reports, a full organized government. They had an army
fighting for independence, admirably disciplined, according to
the statement of zealous advocates of expansion.

"Why, Mr. President, is it credible that any American


statesman, that any American Senator, that any intelligent
American citizen anywhere, two years ago could have been found
to affirm that a proceeding like that of the Paris treaty
could give a just and valid title to sovereignty over a people
situated as were the people of those islands? A title of
Spain, originally by conquest, never submitted to nor admitted
by the people of the islands, with frequent insurrections at
different times for centuries, and then the yoke all thrown
off, a constitutional government, schools, colleges, churches,
universities, hospitals, town governments, a legislature, a
cabinet, courts, a code of laws, and the whole island occupied
and controlled by its people, with the single exception of one
city; with taxes lawfully levied and collected, with an army
and the beginning of a navy.

{644}
"And yet the Senate, the Congress enacted less than two years
ago that the people of Cuba—controlling peaceably no part of
their island, levying no taxes in any orderly or peaceable
way, with no administration of justice, no cabinet—not only of
right ought to be, but were, in fact, a free and independent
State. I did not give my assent to that declaration of fact. I
assented to the doctrine that they of right ought to be. But I
thought the statement of fact much calculated to embarrass the
Government of the United States, if it were bound by that
declaration; and it has been practically disregarded by the
Administration ever since. But the question now is a very
different one. You not only deny that the Filipinos are, but
you deny that they of right ought to be free and independent;
and you recognize Spain as entitled to sell to you the
sovereignty of an island where she was not at the time
occupying a foot of territory, where her soldiers were held
captives by the government of the island, a government to
which you had delivered over a large number of Spanish
prisoners to be held as captives. And yet you come here to-day
and say that they not only are not, but they of right ought
not to be free and independent; and when you are pressed you
answer us by talking about mountains of iron and nuggets of
gold, and trade with China.

"I affirm that you can not get by conquest, and you can not
get by purchase, according to the modern law of nations,
according to the law of nations as accepted and expounded by
the United States, sovereignty over a people, or title to a
territory, of which the power that undertakes to sell it or
the power from whom you undertake to wrest it has not the
actual possession and dominion. … You cannot buy a war. More
than this, you cannot buy a tyrant's claim to subject again an
oppressed people who have achieved their freedom. …

"Gentlemen tell us that the bill of the Senator from Wisconsin


is copied from that introduced in Jefferson's time for the
purchase of Louisiana. Do you claim that you propose to deal
with these people as Jefferson meant to deal with Louisiana?
You talk of Alaska, of Florida, of California; do you mean to
deal with the Philippines as we mean to deal with Alaska and
dealt with Florida or California?

"I have spoken of the Declaration of Independence as a solemn


affirmation of public law, but it is far more than that. It is
a solemn pledge of national faith and honor. It is a baptismal
vow. It is the bedrock of our republican institutions. It is,
as the Supreme Court declared, the soul and spirit of which
the Constitution is but the body and letter. It is the light
by which the Constitution must be read. … There is expansion
enough in it, but it is the expansion of freedom and not of
despotism; of life, not of death. Never was such growth in all
human history as that from the seed Thomas Jefferson planted.
The parable of the mustard seed, than which, as Edward Everett
said, 'the burning pen of inspiration, ranging heaven and
earth for a similitude, can find nothing more appropriate or
expressive to which to liken the Kingdom of God,' is repeated
again. 'Whereunto shall we liken it, or with what comparison
shall we compare it? It is like a grain of mustard seed,
which, when it is sown in the earth, is less than all the
seeds that be in the earth. But when it is sown, it groweth
up, and becometh greater than all herbs, and shooteth out
great branches, so that the fowls of the air may lodge under
the shadow of it.' This is the expansion of Thomas Jefferson.
It has covered the continent. It is on both the seas. It has
saved South America. It is revolutionizing Europe. It is the
expansion of freedom. It differs from your tinsel, pinchbeck,
pewter expansion as the growth of a healthy youth into a
strong man differs from the expansion of an anaconda when he
swallows his victim. Ours is the expansion of Thomas
Jefferson. Yours is the expansion of Aaron Burr. It is
destined to as short a life and to a like fate. …

"There are 1,200 islands in the Philippine group. They extend


as far as from Maine to Florida. They have a population
variously estimated at from 8,000,000 to 12,000,000. There are
wild tribes who never heard of Christ, and islands that never
heard of Spain. But among them are the people of the island of
Luzon, numbering 3,500,000, and the people of the Visayan
Islands, numbering 2,500,000 more. They are a Christian and
civilized people. They wrested their independence from Spain
and established a republic. Their rights are no more to be
affected by the few wild tribes in their own mountains or by
the dwellers in the other islands than the rights of our old
thirteen States were affected by the French in Canada, or the
Six Nations of New York, or the Cherokees of Georgia, or the
Indians west of the Mississippi. Twice our commanding
generals, by their own confession, assured these people of
their independence. Clearly and beyond all cavil we formed an
alliance with them. We expressly asked them to co-operate with
us. We handed over our prisoners to their keeping; we sought
their help in caring for our sick and wounded. We were told by
them again and again and again that they were fighting for
independence. Their purpose was as well known to our generals,
to the War Department, and to the President, as the fact that
they were in arms. We never undeceived them until the time
when hostilities were declared in 1899. The President declared
again and again that we had no title and claimed no right to
anything beyond the town of Manila. Hostilities were begun by
us at a place where we had no right to be, and were continued
by us in spite of Aguinaldo's disavowal and regret and offer
to withdraw to a line we should prescribe. If we crush that
republic, despoil that people of their freedom and
independence, and subject them to our rule, it will be a story
of shame and dishonor. …

"But we are told if we oppose the policy of our imperialistic


and expanding friends we are bound to suggest some policy of
our own as a substitute for theirs. We are asked what we would
do in this difficult emergency. It is a question not difficult
to answer. I for one am ready to answer it.
"1. I would declare now that we will not take these islands to
govern them against their will.

"2. I would reject a cession of sovereignty which implies that


sovereignty may be bought and sold and delivered without the
consent of the people. Spain had no rightful sovereignty over
the Philippine Islands. She could not rightfully sell it to
us. We could not rightfully buy it from her.

"3. I would require all foreign governments to keep out of


these islands.

"4. I would offer to the people of the Philippines our help in


maintaining order until they have a reasonable opportunity to
establish a government of their own.

{645}

"5. I would aid them by advice, if they desire it, to set up a


free and independent government.

"6. I would invite all the great powers of Europe to unite in


an agreement that that independence shall not be interfered
with by us, by themselves, or by any one of them with the
consent of the others. As to this I am not so sure. I should
like quite as well to tell them it is not to be done whether
they consent or not.

"7. I would declare that the United States will enforce the
same doctrine as applicable to the Philippines that we
declared as to Mexico and Haiti and the South American
Republics. It is true that the Monroe Doctrine, a doctrine
based largely on our regard for our own interests, is not
applicable either in terms or in principle to a distant
Asiatic territory. But, undoubtedly, having driven out Spain,
we are bound, and have the right, to secure to the people we
have liberated an opportunity, undisturbed and in peace, to
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like