100% found this document useful (3 votes)
29 views

Data Science Fundamentals for Python and MongoDB 1st Edition David Paper instant download

Ebook download

Uploaded by

berrynairnle
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
100% found this document useful (3 votes)
29 views

Data Science Fundamentals for Python and MongoDB 1st Edition David Paper instant download

Ebook download

Uploaded by

berrynairnle
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/ 67

Data Science Fundamentals for Python and MongoDB

1st Edition David Paper download

https://textbookfull.com/product/data-science-fundamentals-for-
python-and-mongodb-1st-edition-david-paper/

Download more ebook from https://textbookfull.com


We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!

Hands-on Scikit-Learn for machine learning


applications: data science fundamentals with Python
David Paper

https://textbookfull.com/product/hands-on-scikit-learn-for-
machine-learning-applications-data-science-fundamentals-with-
python-david-paper/

Introduction to Python for Science and Engineering 1st


Edition David J. Pine

https://textbookfull.com/product/introduction-to-python-for-
science-and-engineering-1st-edition-david-j-pine/

Python for Data Science 2nd Edition John Paul Mueller

https://textbookfull.com/product/python-for-data-science-2nd-
edition-john-paul-mueller/

Data Science with Python 1st Edition Coll.

https://textbookfull.com/product/data-science-with-python-1st-
edition-coll/
Python Data Science Handbook Essential Tools for
Working with Data 1st Edition Jake Vanderplas

https://textbookfull.com/product/python-data-science-handbook-
essential-tools-for-working-with-data-1st-edition-jake-
vanderplas/

Python Data Science Handbook Essential Tools for


Working with Data 1st Edition Jake Vanderplas

https://textbookfull.com/product/python-data-science-handbook-
essential-tools-for-working-with-data-1st-edition-jake-
vanderplas-2/

Data Science and Analytics with Python 1st Edition


Jesus Rogel-Salazar

https://textbookfull.com/product/data-science-and-analytics-with-
python-1st-edition-jesus-rogel-salazar/

Fundamentals Of Python: Data Structures 2nd Edition


Kenneth A. Lambert

https://textbookfull.com/product/fundamentals-of-python-data-
structures-2nd-edition-kenneth-a-lambert/

Introducing Data Science Big Data Machine Learning and


more using Python tools 1st Edition Davy Cielen

https://textbookfull.com/product/introducing-data-science-big-
data-machine-learning-and-more-using-python-tools-1st-edition-
davy-cielen/
David Paper

Data Science Fundamentals for Python


and MongoDB
David Paper
Apt 3, Logan, Utah, USA

Any source code or other supplementary material referenced by the


author in this book is available to readers on GitHub via the book’s
product page, located at www.​apress.​com/​9781484235966 . For more
detailed information, please visit http://​www.​apress.​com/​source-code
.

ISBN 978-1-4842-3596-6 e-ISBN 978-1-4842-3597-3


https://doi.org/10.1007/978-1-4842-3597-3

Library of Congress Control Number: 2018941864

© David Paper 2018

This work is subject to copyright. All rights are reserved by the


Publisher, whether the whole or part of the material is concerned,
specifically the rights of translation, reprinting, reuse of illustrations,
recitation, broadcasting, reproduction on microfilms or in any other
physical way, and transmission or information storage and retrieval,
electronic adaptation, computer software, or by similar or dissimilar
methodology now known or hereafter developed.

Trademarked names, logos, and images may appear in this book. Rather
than use a trademark symbol with every occurrence of a trademarked
name, logo, or image, we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark. The use in this publication
of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of
opinion as to whether or not they are subject to proprietary rights.
While the advice and information in this book are believed to be true
and accurate at the date of publication, neither the authors nor the
editors nor the publisher can accept any legal responsibility for any
errors or omissions that may be made. The publisher makes no
warranty, express or implied, with respect to the material contained
herein.

Distributed to the book trade worldwide by Springer Science+Business


Media New York, 233 Spring Street, 6th Floor, New York, NY 10013.
Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-
ny@springer-sbm.com, or visit www.springeronline.com. Apress Media,
LLC is a California LLC and the sole member (owner) is Springer
Science + Business Media Finance Inc (SSBM Finance Inc). SSBM
Finance Inc is a Delaware corporation.
To Lady, Sam, Bruce, Malik, John, Moonshadow, and Moonbeam whose
support and love is and always has been unconditional. To the Apress staff
for all of your support and hard work in making this project happen.
Finally, a special shout-out to Jonathan for finding me on Amazon, Jill for
putting up with a compulsive author, and Mark for a thourough and
constructive technical review.
Acknowledgments
My entrée into data analysis started by exploring Python for Data
Analysis by Wes McKinney, which I highly recommend to everyone. My
entrée into data science started by exploring Data Science from Scratch
by Joel Grus. Joel’s book may not be for the faint of heart, but it is
definitely a challenge that I am glad that I accepted! Finally, I thank all
of the contributors to stackoverflow , whose programming solutions are
indispensable.
Table of Contents
Chapter 1:​Introduction
Python Fundamentals
Functions and Strings
Lists, Tuples, and Dictionaries
Reading and Writing Data
List Comprehension
Generators
Data Randomization
MongoDB and JSON
Visualization
Chapter 2:​Monte Carlo Simulation and Density Functions
Stock Simulations
What-If Analysis
Product Demand Simulation
Randomness Using Probability and Cumulative Density
Functions
Chapter 3:​Linear Algebra
Vector Spaces
Vector Math
Matrix Math
Basic Matrix Transformations
Pandas Matrix Applications
Chapter 4:​Gradient Descent
Simple Function Minimization (and Maximization)
Sigmoid Function Minimization (and Maximization)
Euclidean Distance Minimization Controlling for Step Size
Stabilizing Euclidean Distance Minimization with Monte Carlo
Simulation
Substituting a NumPy Method to Hasten Euclidean Distance
Minimization
Stochastic Gradient Descent Minimization and Maximization
Chapter 5:​Working with Data
One-Dimensional Data Example
Two-Dimensional Data Example
Data Correlation and Basic Statistics
Pandas Correlation and Heat Map Examples
Various Visualization Examples
Cleaning a CSV File with Pandas and JSON
Slicing and Dicing
Data Cubes
Data Scaling and Wrangling
Chapter 6:​Exploring Data
Heat Maps
Principal Component Analysis
Speed Simulation
Big Data
Twitter
Web Scraping
Index
About the Author and About the Technical
Reviewer

About the Author


David Paper
is a full professor at Utah State
University in the Management
Information Systems department. His
book Web Programming for Business:
PHP Object-Oriented Programming with
Oracle was published in 2015 by
Routledge. He also has over 70
publications in refereed journals such as
Organizational Research Methods,
Communications of the ACM, Information
& Management, Information Resource
Management Journal, Communications of
the AIS, Journal of Information
Technology Case and Application Research , and Long Range Planning .
He has also served on several editorial boards in various capacities,
including associate editor. Besides growing up in family businesses, Dr.
Paper has worked for Texas Instruments, DLS, Inc., and the Phoenix
Small Business Administration. He has performed IS consulting work
for IBM, AT&T, Octel, Utah Department of Transportation, and the Space
Dynamics Laboratory. Dr. Paper’s teaching and research interests
include data science, machine learning, process reengineering, object-
oriented programming, electronic customer relationship management,
change management, e-commerce, and enterprise integration.

About the Technical Reviewer


Mark Furman, MBA
is a systems engineer, author, teacher, and entrepreneur. For the last 16
years he has worked in the Information Technology field, with a focus
on Linux-based systems and programming in Python, working for a
range of companies including Host Gator, Interland, Suntrust Bank,
AT&T, and Winn-Dixie. Currently he has been focusing his career on the
maker movement and has launched Tech Forge (techforge.org), which
will focus on helping people start a makerspace and help sustain
current spaces. He holds a Master of Business Administration from
Ohio University. You can follow him on Twitter @mfurman.
© David Paper 2018
David Paper, Data Science Fundamentals for Python and MongoDB
https://doi.org/10.1007/978-1-4842-3597-3_1

1. Introduction
David Paper1
(1) Apt 3, Logan, Utah, USA

Data science is an interdisciplinary field encompassing scientific


methods, processes, and systems to extract knowledge or insights from
data in various forms, either structured or unstructured. It draws
principles from mathematics, statistics, information science, computer
science, machine learning, visualization, data mining, and predictive
analytics. However, it is fundamentally grounded in mathematics.
This book explains and applies the fundamentals of data science crucial
for technical professionals such as DBAs and developers who are
making career moves toward practicing data science. It is an example-
driven book providing complete Python coding examples to
complement and clarify data science concepts, and enrich the learning
experience. Coding examples include visualizations whenever
appropriate. The book is a necessary precursor to applying and
implementing machine learning algorithms, because it introduces the
reader to foundational principles of the science of data.
The book is self-contained. All the math, statistics, stochastic, and
programming skills required to master the content are covered in the
book. In-depth knowledge of object-oriented programming isn’t
required, because working and complete examples are provided and
explained. The examples are in-depth and complex when necessary to
ensure the acquisition of appropriate data science acumen. The book
helps you to build the foundational skills necessary to work with and
understand complex data science algorithms.
Data Science Fundamentals by Example is an excellent starting point for
those interested in pursuing a career in data science. Like any science,
the fundamentals of data science are prerequisite to competency.
Without proficiency in mathematics, statistics, data manipulation, and
coding, the path to success is “rocky” at best. The coding examples in
this book are concise, accurate, and complete, and perfectly
complement the data science concepts introduced.
The book is organized into six chapters. Chapter 1 introduces the
programming fundamentals with “Python” necessary to work with,
transform, and process data for data science applications. Chapter 2
introduces Monte Carlo simulation for decision making, and data
distributions for statistical processing. Chapter 3 introduces linear
algebra applied with vectors and matrices. Chapter 4 introduces the
gradient descent algorithm that minimizes (or maximizes) functions,
which is very important because most data science problems are
optimization problems. Chapter 5 focuses on munging, cleaning, and
transforming data for solving data science problems. Chapter 6 focusing
on exploring data by dimensionality reduction, web scraping, and
working with large data sets efficiently.
Python programming code for all coding examples and data files are
available for viewing and download through Apress at
www.apress.com/9781484235966 . Specific linking instructions
are included on the copyright pages of the book.
To install a Python module, pip is the preferred installer program. So, to
install the matplotlib module from an Anaconda prompt: pip install
matplotlib. Anaconda is a widely popular open source distribution of
Python (and R) for large-scale data processing, predictive analytics, and
scientific computing that simplifies package management and
deployment. I have worked with other distributions with unsatisfactory
results, so I highly recommend Anaconda.

Python Fundamentals
Python has several features that make it well suited for learning and
doing data science. It’s free, relatively simple to code, easy to
understand, and has many useful libraries to facilitate data science
problem solving. It also allows quick prototyping of virtually any data
science scenario and demonstration of data science concepts in a clear,
easy to understand manner.
The goal of this chapter is not to teach Python as a whole, but present,
explain, and clarify fundamental features of the language (such as logic,
data structures, and libraries) that help prototype, apply, and/or solve
data science problems.
Python fundamentals are covered with a wide spectrum of activities
with associated coding examples as follows:
1. functions and strings

2. lists, tuples, and dictionaries

3. reading and writing data

4. list comprehension

5. generators

6. data randomization

7. MongoDB and JSON

8. visualization

Functions and Strings


Python functions are first-class functions, which means they can be
used as parameters, a return value, assigned to variable, and stored in
data structures. Simply, functions work like a typical variable. Functions
can be either custom or built-in. Custom are created by the
programmer, while built-in are part of the language. Strings are very
popular types enclosed in either single or double quotes.
The following code example defines custom functions and uses built-in
ones:
def num_to_str(n):
return str(n)

def str_to_int(s):
return int(s)

def str_to_float(f):
return float(f)

if __name__ == "__main__":
# hash symbol allows single-line comments
'''
triple quotes allow multi-line comments
'''
float_num = 999.01
int_num = 87
float_str = '23.09'
int_str = '19'
string = 'how now brown cow'
s_float = num_to_str(float_num)
s_int = num_to_str(int_num)
i_str = str_to_int(int_str)
f_str = str_to_float(float_str)
print (s_float, 'is', type(s_float))
print (s_int, 'is', type(s_int))
print (f_str, 'is', type(f_str))
print (i_str, 'is', type(i_str))
print ('\nstring', '"' + string + '" has',
len(string), 'characters')
str_ls = string.split()
print ('split string:', str_ls)
print ('joined list:', ' '.join(str_ls))

Output:
A popular coding style is to present library importation and functions
first, followed by the main block of code. The code example begins with
three custom functions that convert numbers to strings, strings to
numbers, and strings to float respectively. Each custom function returns
a built-in function to let Python do the conversion. The main block
begins with comments. Single-line comments are denoted with the #
(hash) symbol. Multiline comments are denoted with three consecutive
single quotes. The next five lines assign values to variables. The
following four lines convert each variable type to another type. For
instance, function num_to_str() converts variable float_num to string
type. The next five lines print variables with their associated Python
data type. Built-in function type() returns type of given object. The
remaining four lines print and manipulate a string variable.

Lists, Tuples, and Dictionaries


Lists are ordered collections with comma-separated values between
square brackets. Indices start at 0 (zero). List items need not be of the
same type and can be sliced, concatenated, and manipulated in many
ways.
The following code example creates a list, manipulates and slices it,
creates a new list and adds elements to it from another list, and creates
a matrix from two lists :

import numpy as np

if __name__ == "__main__":
ls = ['orange', 'banana', 10, 'leaf', 77.009,
'tree', 'cat']
print ('list length:', len(ls), 'items')
print ('cat count:', ls.count('cat'), ',',
'cat index:', ls.index('cat'))
print ('\nmanipulate list:')
cat = ls.pop(6)
print ('cat:', cat, ', list:', ls)
ls.insert(0, 'cat')
ls.append(99)
print (ls)
ls[7] = '11'
print (ls)
ls.pop(1)
print (ls)
ls.pop()
print (ls)
print ('\nslice list:')
print ('1st 3 elements:', ls[:3])
print ('last 3 elements:', ls[3:])
print ('start at 2nd to index 5:', ls[1:5])
print ('start 3 from end to end of list:',
ls[-3:])
print ('start from 2nd to next to end of
list:', ls[1:-1])
print ('\ncreate new list from another list:')
print ('list:', ls)
fruit = ['orange']
more_fruit = ['apple', 'kiwi', 'pear']
fruit.append(more_fruit)
print ('appended:', fruit)
fruit.pop(1)
fruit.extend(more_fruit)
print ('extended:', fruit)
a, b = fruit[2], fruit[1]
print ('slices:', a, b)
print ('\ncreate matrix from two lists:')
matrix = np.array([ls, fruit])
print (matrix)
print ('1st row:', matrix[0])
print ('2nd row:', matrix[1])
Output:

The code example begins by importing NumPy, which is the


fundamental package (library, module) for scientific computing. It is
useful for linear algebra, which is fundamental to data science. Think of
Python libraries as giant classes with many methods. The main block
begins by creating list ls , printing its length, number of elements
(items), number of cat elements, and index of the cat element. The code
continues by manipulating ls. First, the 7th element (index 6) is popped
and assigned to variable cat. Remember, list indices start at 0. Function
pop() removes cat from ls. Second, cat is added back to ls at the 1st
position (index 0) and 99 is appended to the end of the list. Function
append() adds an object to the end of a list. Third, string ‘11’ is
substituted for the 8th element (index 7). Finally, the 2nd element and
the last element are popped from ls. The code continues by slicing ls.
First, print the 1st three elements with ls[:3]. Second, print the last
three elements with ls[3:]. Third, print starting with the 2nd element to
elements with indices up to 5 with ls[1:5]. Fourth, print starting three
elements from the end to the end with ls[-3:]. Fifth, print starting from
the 2nd element to next to the last element with ls[1:-1]. The code
continues by creating a new list from another. First, create fruit with
one element. Second append list more_fruit to fruit. Notice that append
adds list more_fruit as the 2nd element of fruit, which may not be what
you want. So, third, pop 2nd element of fruit and extend more_fruit to
fruit. Function extend() unravels a list before it adds it. This way, fruit
now has four elements. Fourth, assign 3rd element to a and 2nd
element to b and print slices. Python allows assignment of multiple
variables on one line, which is very convenient and concise. The code
ends by creating a matrix from two lists—ls and fruit—and printing it.
A Python matrix is a two-dimensional (2-D) array consisting of rows
and columns, where each row is a list .
A tuple is a sequence of immutable Python objects enclosed by
parentheses. Unlike lists, tuples cannot be changed. Tuples are
convenient with functions that return multiple values.
The following code example creates a tuple, slices it, creates a list, and
creates a matrix from tuple and list:

import numpy as np

if __name__ == "__main__":
tup = ('orange', 'banana', 'grape', 'apple',
'grape')
print ('tuple length:', len(tup))
print ('grape count:', tup.count('grape'))
print ('\nslice tuple:')
print ('1st 3 elements:', tup[:3])
print ('last 3 elements', tup[3:])
print ('start at 2nd to index 5', tup[1:5])
print ('start 3 from end to end of tuple:',
tup[-3:])
print ('start from 2nd to next to end of
tuple:', tup[1:-1])
print ('\ncreate list and create matrix from
it and tuple:')
fruit = ['pear', 'grapefruit', 'cantaloupe',
'kiwi', 'plum']
matrix = np.array([tup, fruit])
print (matrix)
Output:

The code begins by importing NumPy. The main block begins by


creating tuple tup , printing its length, number of elements (items),
number of grape elements, and index of grape. The code continues by
slicing tup. First, print the 1st three elements with tup[:3]. Second,
print the last three elements with tup[3:]. Third, print starting with the
2nd element to elements with indices up to 5 with tup[1:5]. Fourth,
print starting three elements from the end to the end with tup[-3:].
Fifth, print starting from the 2nd element to next to the last element
with tup[1:-1]. The code continues by creating a new fruit list and
creating a matrix from tup and fruit.
A dictionary is an unordered collection of items identified by a
key/value pair. It is an extremely important data structure for working
with data. The following example is very simple, but the next section
presents a more complex example based on a dataset.
The following code example creates a dictionary, deletes an element,
adds an element, creates a list of dictionary elements, and traverses the
list:

if __name__ == "__main__":
audio = {'amp':'Linn', 'preamp':'Luxman',
'speakers':'Energy',
'ic':'Crystal Ultra', 'pc':'JPS',
'power':'Equi-Tech',
'sp':'Crystal Ultra', 'cdp':'Nagra',
'up':'Esoteric'}
del audio['up']
print ('dict "deleted" element;')
print (audio, '\n')
print ('dict "added" element;')
audio['up'] = 'Oppo'
print (audio, '\n')
print ('universal player:', audio['up'], '\n')
dict_ls = [audio]
video = {'tv':'LG 65C7 OLED', 'stp':'DISH',
'HDMI':'DH Labs',
'cable' : 'coax'}
print ('list of dict elements;')
dict_ls.append(video)
for i, row in enumerate(dict_ls):
print ('row', i, ':')
print (row)

Output:
The main block begins by creating dictionary audio with several
elements. It continues by deleting an element with key up and value
Esoteric, and displaying. Next, a new element with key up and element
Oppo is added back and displayed. The next part creates a list with
dictionary audio, creates dictionary video, and adds the new dictionary
to the list. The final part uses a for loop to traverse the dictionary list
and display the two dictionaries. A very useful function that can be used
with a loop statement is enumerate(). It adds a counter to an iterable.
An iterable is an object that can be iterated. Function enumerate() is
very useful because a counter is automatically created and
incremented, which means less code .

Reading and Writing Data


The ability to read and write data is fundamental to any data science
endeavor. All data files are available on the website. The most basic
types of data are text and CSV (Comma Separated Values). So, this is
where we will start.
The following code example reads a text file and cleans it for
processing. It then reads the precleansed text file, saves it as a CSV file,
reads the CSV file, converts it to a list of OrderedDict elements, and
converts this list to a list of regular dictionary elements.

import csv
def read_txt(f):
with open(f, 'r') as f:
d = f.readlines()
return [x.strip() for x in d]

def conv_csv(t, c):


data = read_txt(t)
with open(c, 'w', newline='') as csv_file:
writer = csv.writer(csv_file)
for line in data:
ls = line.split()
writer.writerow(ls)

def read_csv(f):
contents = ''
with open(f, 'r') as f:
reader = csv.reader(f)
return list(reader)

def read_dict(f, h):


input_file = csv.DictReader(open(f),
fieldnames=h)
return input_file

def od_to_d(od):
return dict(od)

if __name__ == "__main__":
f = 'data/names.txt'
data = read_txt(f)
print ('text file data sample:')
for i, row in enumerate(data):
if i < 3:
print (row)
csv_f = 'data/names.csv'
conv_csv(f, csv_f)
r_csv = read_csv(csv_f)
print ('\ntext to csv sample:')
for i, row in enumerate(r_csv):
if i < 3:
print (row)
headers = ['first', 'last']
r_dict = read_dict(csv_f, headers)
dict_ls = []
print ('\ncsv to ordered dict sample:')
for i, row in enumerate(r_dict):
r = od_to_d(row)
dict_ls.append(r)
if i < 3:
print (row)
print ('\nlist of dictionary elements
sample:')
for i, row in enumerate(dict_ls):
if i < 3:
print (row)
Output:
The code begins by importing the csv library, which implements classes
to read and write tabular data in CSV format. It continues with five
functions. Function read_txt() reads a text (.txt) file and strips
(removes) extraneous characters with list comprehension, which is an
elegant way to define and create a list in Python. List comprehension is
covered later in the next section. Function conv_csv() converts a text to
a CSV file and saves it to disk. Function read_csv() reads a CSV file and
returns it as a list. Function read_dict() reads a CSV file and returns a
list of OrderedDict elements. An OrderedDict is a dictionary subclass
that remembers the order in which its contents are added, whereas a
regular dictionary doesn’t track insertion order. Finally, function
od_to_d() converts an OrderedDict element to a regular dictionary
element. Working with a regular dictionary element is much more
intuitive in my opinion. The main block begins by reading a text file and
cleaning it for processing. However, no processing is done with this
cleansed file in the code. It is only included in case you want to know
how to accomplish this task. The code continues by converting a text
file to CSV, which is saved to disk. The CSV file is then read from disk
and a few records are displayed. Next, a headers list is created to store
keys for a dictionary yet to be created. List dict_ls is created to hold
dictionary elements. The code continues by creating an OrderedDict list
r_dict. The OrderedDict list is then iterated so that each element can be
converted to a regular dictionary element and appended to dict_ls. A
few records are displayed during iteration. Finally, dict_ls is iterated
and a few records are displayed. I highly recommend that you take
some time to familiarize yourself with these data structures, as they are
used extensively in data science application.

List Comprehension
List comprehension provides a concise way to create lists. Its logic is
enclosed in square brackets that contain an expression followed by a
for clause and can be augmented by more for or if clauses.
The read_txt() function in the previous section included the following
list comprehension:

[x.strip() for x in d]
The logic strips extraneous characters from string in iterable d. In this
case, d is a list of strings.
The following code example converts miles to kilometers, manipulates
pets, and calculates bonuses with list comprehension:

if __name__ == "__main__":
miles = [100, 10, 9.5, 1000, 30]
kilometers = [x * 1.60934 for x in miles]
print ('miles to kilometers:')
for i, row in enumerate(kilometers):
print ('{:>4} {:>8}{:>8} {:>2}'.
format(miles[i],'miles is',
round(row,2), 'km'))
print ('\npet:')
pet = ['cat', 'dog', 'rabbit', 'parrot',
'guinea pig', 'fish']
print (pet)
print ('\npets:')
pets = [x + 's' if x != 'fish' else x for x in
pet]
print (pets)
subset = [x for x in pets if x != 'fish' and x
!= 'rabbits'
and x != 'parrots' and x != 'guinea
pigs']
print ('\nmost common pets:')
print (subset[1], 'and', subset[0])
sales = [9000, 20000, 50000, 100000]
print ('\nbonuses:')
bonus = [0 if x < 10000 else x * .02 if x >=
10000 and x <= 20000
else x * .03 for x in sales]
print (bonus)
print ('\nbonus dict:')
people = ['dave', 'sue', 'al', 'sukki']
d = {}
for i, row in enumerate(people):
d[row] = bonus[i]
print (d, '\n')
print ('{:<5} {:<5}'.format('emp', 'bonus'))
for k, y in d.items():
print ('{:<5} {:>6}'.format(k, y))
Output:

The main block begins by creating two lists—miles and kilometers. The
kilometers list is created with list comprehension , which multiplies
each mile value by 1.60934. At first, list comprehension may seem
confusing, but practice makes it easier over time. The main block
continues by printing miles and associated kilometers. Function
format() provides sophisticated formatting options. Each mile value is
({:>4}) with up to four characters right justified. Each string for miles
and kilometers is right justified ({:>8}) with up to eight characters .
Finally, each string for km is right justified ({:>2}) with up to two
characters. This may seem a bit complicated at first, but it is really quite
logical (and elegant) once you get used to it. The main block continues
by creating pet and pets lists. The pets list is created with list
comprehension, which makes a pet plural if it is not a fish. I advise you
to study this list comprehension before you go forward, because they
just get more complex. The code continues by creating a subset list with
list comprehension, which only includes dogs and cats. The next part
creates two lists—sales and bonus. Bonus is created with list
comprehension that calculates bonus for each sales value. If sales are
less than 10,000, no bonus is paid. If sales are between 10,000 and
20,000 (inclusive), the bonus is 2% of sales. Finally, if sales if greater
than 20,000, the bonus is 3% of sales. At first I was confused with this
list comprehension but it makes sense to me now. So, try some of your
own and you will get the gist of it. The final part creates a people list to
associate with each sales value, continues by creating a dictionary to
hold bonus for each person, and ends by iterating dictionary elements.
The formatting is quite elegant. The header left justifies emp and bonus
properly. Each item is formatted so that the person is left justified with
up to five characters ({:<5}) and the bonus is right justified with up to
six characters ({:>6}).

Generators
A generator is a special type of iterator, but much faster because values
are only produced as needed. This process is known as lazy (or
deferred) evaluation. Typical iterators are much slower because they
are fully built into memory. While regular functions return values,
generators yield them. The best way to traverse and access values from
a generator is to use a loop. Finally, a list comprehension can be
converted to a generator by replacing square brackets with
parentheses.
The following code example reads a CSV file and creates a list of
OrderedDict elements . It then converts the list elements into regular
dictionary elements. The code continues by simulating times for list
comprehension, generator comprehension, and generators. During
simulation, a list of times for each is created. Simulation is the imitation
of a real-world process or system over time, and it is used extensively in
data science.

import csv, time, numpy as np

def read_dict(f, h):


input_file = csv.DictReader(open(f),
fieldnames=h)
return (input_file)

def conv_reg_dict(d):
return [dict(x) for x in d]

def sim_times(d, n):


i = 0
lsd, lsgc = [], []
while i < n:
start = time.clock()
[x for x in d]
time_d = time.clock() - start
lsd.append(time_d)
start = time.clock()
(x for x in d)
time_gc = time.clock() - start
lsgc.append(time_gc)
i += 1
return (lsd, lsgc)

def gen(d):
yield (x for x in d)

def sim_gen(d, n):


i = 0
lsg = []
generator = gen(d)
while i < n:
start = time.clock()
for row in generator:
None
time_g = time.clock() - start
lsg.append(time_g)
i += 1
generator = gen(d)
return lsg

def avg_ls(ls):
return np.mean(ls)

if __name__ == '__main__':
f = 'data/names.csv'
headers = ['first', 'last']
r_dict = read_dict(f, headers)
dict_ls = conv_reg_dict(r_dict)
n = 1000
ls_times, gc_times = sim_times(dict_ls, n)
g_times = sim_gen(dict_ls, n)
avg_ls = np.mean(ls_times)
avg_gc = np.mean(gc_times)
avg_g = np.mean(g_times)
gc_ls = round((avg_ls / avg_gc), 2)
g_ls = round((avg_ls / avg_g), 2)
print ('generator comprehension:')
print (gc_ls, 'times faster than list
comprehension\n')
print ('generator:')
print (g_ls, 'times faster than list
comprehension')
Output:
Another Random Document on
Scribd Without Any Related Topics
collecting the Scots, and after very hard fighting the garrison was
driven in. Bruce presently came up with large reinforcements, but
the castle held out tenaciously, and surrendered only to famine. The
town was taken on March 28 (Fordun), or April 2 (Lanercost); the
castle held out gallantly till past the middle of July, and even then
Horsley marched out his famished garrison with the honours of war.
Bruce installed as warden Sir Walter the Steward. Peter of Spalding,
says John of Tynmouth, proved troublesome in insisting upon his
promised reward; and, on an accusation of plotting against the life
of King Robert, was put to death. The allegation recalls the case of
Sir Peter de Lubaud.
Edward was extremely incensed at the Mayor and burgesses of
Berwick, who had undertaken, for 6000 marks, to defend the town
for a year from June 15, 1317. He ascribed the loss of it to their
carelessness, and in the middle of April he ordered that their goods
and chattels, wheresoever found, should be confiscated, and that
such of them as had escaped into England should be imprisoned. On
June 10, 1318, he summoned his army to meet him at York on July
26, to proceed against the Scots.
Meantime the Scots were proceeding with vigour against him.
For soon after the capture of Berwick town, Bruce detached a strong
force to ravage the northern counties. They laid waste
Northumberland to the gates of Newcastle, starved the castles of
Harbottle and Wark into surrender, and took Mitford Castle by
stratagem. They sold immunity to the episcopate of Durham,
excepting Hartlepool, which Bruce threatened to burn and destroy
because some of its inhabitants had captured a ship freighted with
his 'armeours' and provisions. Northallerton, Ripon, Boroughbridge,
Knaresborough, Otley and Skipton were guiding-points in the
desolating track of the invaders. Ripon and Otley suffered most
severely, and Ripon paid 1000 marks for a cessation of destruction.
Fountains Abbey also paid ransom; Bolton Abbey was plundered;
Knaresborough Parish Church bears to this day the marks of the fire
that burnt out the fugitives. The expedition returned to Scotland
laden with spoils, and bringing numerous captives and great droves
of cattle. The Archbishop of York postponed misfortune by being too
late with measures of resistance. But he energetically
excommunicated the depredators, all and sundry.
On hearing of Bruce's reception of the envoys, the Pope had
authorised the Cardinals, on December 29, to put in execution the
two Bulls of excommunication prepared in the previous March. The
Cardinals, however, would seem to have delayed. On June 28, 1318,
when the Pope heard of the woeful adventures of Adam de Newton
and of the capture of Berwick despite his truce, he ordered them to
proceed. For Bruce, he said, had 'grievously' (dampnabiliter) 'abused
his patience and long-suffering.' In September accordingly they
excommunicated and laid under interdict Bruce himself, his brother
Edward, and all their aiders and abettors in the invasion of England
and Ireland. 'But,' says the Lanercost chronicler, 'the Scots cared not
a jot for any excommunication, and declined to pay any observance
to the interdict.' In October, Edward followed up his diplomatic
success by pressing hard for the deposition of the Bishop of St
Andrews, but the Pope easily found good technical pleas whereby to
avoid compliance.
The Irish expedition came to a disastrous close on the fatal field
of Faughart, near Dundalk, on October 5 (or 14), 1318. A vastly
superior English army, under Sir John de Bermingham, moved
against the Scots; and King Edward the Bruce, wrathfully overruling
the counsels of his staff, disdaining to wait for the approaching
reinforcements from Scotland, and despising the hesitations of his
Irish allies, dashed against the tremendous odds with his native
impetuosity.
'Now help quha will, for sekirly
This day, but mair baid, fecht vill I.
Sall na man say, quhill I may dre,
That strynth of men sall ger me fle!
God scheld that ony suld vs blame
That we defoull our nobill name!'
Barbour gives the numbers at 2000 against 40,000, no doubt
with generous exaggeration. King Edward fell at the first onset, killed
by a gigantic Anglo-Irish knight, Sir John de Maupas, who was found
lying dead across his body. Sir John the Steward, Sir John de Soulis,
and other officers were slain. Barbour tells how Sir Philip de
Mowbray, stunned in action, was led captive by two men towards
Dundalk; how he recovered his senses sufficiently to realise his
position, shook off his captors, drew his sword and turned back
towards the battle-field, and how he cleared a hundred men out of
his way as he went. John Thomasson, the leader of the Carrick men,
took him in charge, and hurried him away towards Carrickfergus. But
the brave defender of Stirling had received a mortal wound. King
Edward's body was dismembered, the trunk buried at Faughart, and
the limbs exposed in Irish towns held by the English. The head is
said to have been sent to England to Edward; but Barbour tells how
King Edward the Bruce had that day exchanged armour with Gilbert
the Harper, as he had done before at Connor, and how it was
Gilbert's head that had been mistakenly struck off and despatched to
England. The remnants of the Scots army reached Carrickfergus with
the utmost difficulty, and hastily took ship for Scotland, where the
news was received with great lamentation. Bermingham was created
Earl of Louth for his victory. It is curious to observe that his wife was
a sister of the Queen of Scotland.
The death of Edward Bruce disturbed the settlement of the
succession, which was again brought under consideration of
Parliament, on December 3, at Scone. Robert, the son of Sir Walter
the Steward and the late Princess Marjory, was recognised as heir,
with a proviso saving the right of any subsequent male issue of King
Robert. In case of a minority, Randolph was to be guardian; and
failing Randolph, Douglas.
No sooner had the sentences of excommunication been
promulgated than King Robert took measures to have them revoked
or mitigated. He had good friends at Rome. Letters from these had
fallen accidentally into the hands of Edward, who, on January 12,
1318–19, sent them to the Pope by the hands of Sir John de Neville,
and asked His Holiness to deal suitably with the writers. A few days
before, he had urged the two Cardinals to press the Pope to reject
the applications that he heard were being made on behalf of Bruce
and his friends, and stated that he would presently send envoys to
the Pope himself. Neville was graciously received, and the Pope
ordered the Scots and their abettors at his court to prison. On April
24, the Pope granted Edward's request for a Bull permitting him to
negotiate for peace with the Scots notwithstanding their
excommunication. But the pressure was not all on one side; the
nuncios in England boldly exercised their powers, and had often to
be restrained even by royal menace, while every ecclesiastical office
was steadily claimed for the papal nominee. Bruce appears to have
deemed it prudent to raise little formal objection to the papal
appointment of ecclesiastics up and down Scotland, though some of
them evidently had but a seat of thorns.
From March to May there was an interesting correspondence
between Edward and some minor states and municipalities on the
other side of the North Sea, whose people, Edward understood, had
harboured, or even assisted, his Scots enemies. They all denied the
allegation. The statesmanlike answer of the Count of Flanders,
however, is peculiarly notable. 'Our land of Flanders,' he wrote, 'is
common to all men, of whatever country, and freely open to all
comers; and we cannot deny admission to merchants doing their
business as they have hitherto been accustomed, for thereby we
should bring our land to desolation and ruin.'
But Berwick must be recaptured. On the loss of Berwick town,
Edward had angrily summoned his forces to muster at York on July
26, 1318. So few of them appeared, however, that he was forced to
postpone the expedition. On June 4, 1319, he ordered the Welsh
levies to be at Newcastle by July 24 at latest; and, two days after, he
wrote to the Pope that he hoped now 'to put a bit in the jaws of the
Scots.' But another postponement was forced on him. On July 20,
however, he issued a peremptory order for a muster at Michaelmas.
His May parliament at York had granted him certain taxes, his
treasury being 'exhausted more than is believed'; and his good
friend the Pope had added a material contribution. But the levy
could not be collected till Michaelmas, and meantime the King
appealed for an advance. There must have been a favourable
response, for early in September he encamped before Berwick with
some 10,000 or 12,000 men, his fleet occupying the harbour. Having
entrenched his lines, he delivered a general assault on September 7.
The besiegers hastily filled the dykes and placed their scaling-
ladders, but the garrison threw them down as fast as they were
raised. The lowness of the wall was not altogether in favour of the
assailants, for the besieged on the top could easily thrust their
spears in their faces. In the course of the afternoon the English
brought a ship on the flood-tide up to the wall, with a boat lashed to
midmast, whence a bridge was to be let down for landing a storming
party. They were embarrassed in their efforts, however, and the ship,
being left aground by the ebb-tide, was burned by the Scots, the
sallying party with difficulty regaining the town. The fight went on
briskly till night, when the combatants agreed to postpone its
renewal for five days.
Though King Robert had mustered a considerable force,
probably as large as Edward's, he deemed it more prudent to
despatch it on a raid into England than to launch it directly against
the English entrenchments. He had, indeed, good reason to rely
upon the skill and energy of the Steward. The five days' truce over,
the English, on September 13, moved forward on wheels an
immense sow, not only covering a mining party, but carrying
scaffolds for throwing a storming party on the wall. By this time,
John Crab, whom we have already met as a sea-captain or pirate,
and whom the Count of Flanders presently assured Edward he would
break on the wheel, if he could only get hold of him, had proved
himself engineer enough to devise a 'crane,' which must have been
of the nature of a catapult; and this engine he ran along the wall on
wheels to encounter the sow. The first shot passed over the
monster; the second just fell short; the third crashed through the
main beam, and frightened the men out. 'Your sow has farrowed,'
cried the Scots. Crab now lowered blazing faggots of combustible
stuff upon the sow, and burnt it up. But presently another attempt
was made from the harbour, and Crab's engine was hurried up to
fight ships with top-castles full of men, and with fall-bridges ready at
midmast. The first shot demolished the top gear of one of the ships,
bringing down the men; and the other ships kept a safe distance.
Meantime the general attack raged all along the wall. Sir Walter
the Steward rode from point to point, supplying here and there men
from his own bodyguard, till it was reduced from a hundred to a
single man-at-arms. The severest pressure was at Mary Gate. The
besiegers forced the advance barricade, burned the drawbridge, and
fired the gate. Sir Walter drew reinforcements from the castle, which
had not been attacked, threw open Mary Gate and sallied upon the
foe, driving them back after a very hard struggle, and saving the
gate. Night separated the combatants. Barbour tells how the women
and children of the town had carried arrows to the men on the walls,
and regards it as a miracle that not one of them was slain or
wounded. But clearly the Steward could not sustain many days of
such heavy fighting.
The Scots army under Randolph and Douglas had meanwhile
followed the familiar track through Ripon and Boroughbridge,
harrying and burning and slaying. They appear to have made a
serious attempt to capture Edward's Queen, who was then staying
near York; but the Archbishop, learning this intention from a Scots
spy that had been taken prisoner, sallied forth and brought her into
the city, and sent her by water to Nottingham. Trokelowe speaks of
certain 'false Englishmen' that had been bribed by the Scots, and
Robert of Reading specifies Sir Edmund Darel as the guide of the
invaders in the attempt. Next day the Archbishop, with Bishop
Hotham of Ely, the Chancellor of England, and an unwieldy multitude
of clergy and townspeople numbering some 10,000, advanced
against the Scots between Myton and Thornton-on-Swale, about
twelve miles north of York. 'These,' said the Scots, 'are not soldiers,
but hunters; they will not do much good.' For the English 'came
through the fields in scattered fashion, and not in united order.' The
Scots formed a schiltron, and set fire to some hay in front, the
smoke from which was blown into the faces of the English. As they
met, the Scots raised a great shout, and the enemy, 'more intent on
fleeing than on fighting,' took to their heels. The Scots mounted in
pursuit, killing (says the Lanercost chronicle) clergy and laymen,
about 4000, including Nicholas Fleming, the Mayor of York, while
about 1000, 'as was said,' were drowned in the Swale. Many were
captured and held to heavy ransom. The Archbishop lost, not only
his men, his carriages, and his equipment generally, but all his plate,
'silver and bronze as well,' which his servants had 'thoughtlessly'
taken to the field; and yet the blame may rest elsewhere, for the
York host appears to have fully anticipated that the Scots would flee
at sight of them. The Primate's official cross was saved by the
bearer, who dashed on horseback through the Swale and carefully
hid it, escaping himself in the dusk of the evening. Then a
countryman, who had observed the cross and watched the bearer's
retreat, discovered it, wound wisps of hay about it, and kept it in his
hut till search was made for it, whereupon he restored it to the
Archbishop. Such is John of Bridlington's story. The whole episode
contrasts markedly with the exploit of Bishop Sinclair in Fife. It was
contemptuously designated, from the number of ecclesiastics, 'the
Chapter of Myton.'
The Myton disaster occurred on September 20, and on
September 24 Edward raised the siege of Berwick. Certain
chroniclers speak of intestine dissensions, and particularly of a
quarrel with Lancaster over the appointment of wardens of town and
castle once Berwick was taken. The Lanercost chronicler says
Edward desired to detach a body to intercept the Scots, and with the
rest to carry on the siege; but his magnates would not hear of it. He
accordingly abandoned the siege, and marched westward to cut off
the retreat of the Scots. Randolph had penetrated to Castleford
Bridge, near Pontefract, and swept up Airedale and Wharfdale; and,
passing by Stainmoor and Gilsland, he eluded Edward's army, and
carried into Scotland many captives and immense plunder. It
remained for Edward but to disband his troops, and go home, as
usual, with empty hands.
About a month later (November 1), when the crops were
harvested in northern England, Randolph and Douglas returned with
fire and sword. They burnt Gilsland, and passed down to Brough
(Burgh) under Stainmoor; turned back on Westmorland, which they
ravaged for ten or twelve days, and went home through
Cumberland. They mercilessly burnt barns and the stored crops, and
swept the country of men and cattle.
Edward began to think of truce. In his letter of December 4 to
the Pope, he represents that urgent proposals for peace had come
to him from Bruce and his friends. In any case, the step was a most
sensible one. On December 21, terms were agreed on, and next day
Bruce confirmed them. This truce was to run for two years and the
odd days to Christmas. Bruce agreed to raise no new fortresses
within the counties of Berwick, Roxburgh, and Dumfries. He
delivered the castle of Harbottle to Edward's commissioners, 'as
private persons,' with the proviso that, unless a final peace were
made by Michaelmas, it should be either redelivered to him or
demolished. On August 25, 1321, Edward commanded that it should
be destroyed 'as secretly as possible.'
In autumn 1319, the Pope, at the instance of Edward, had given
orders for a revival of the excommunications against Bruce and his
friends; but on January 8, 1319–20, he cited Bruce and the Bishops
of St Andrews, Dunkeld, Aberdeen, and Moray, to compear before
him by May 1. The summons went unheeded; he had not addressed
Bruce as King. Excommunications were again hurled at Bruce and
his bishops, and Scotland was laid under ecclesiastical interdict.
Meanwhile, however, the Scots 'barons, freeholders, and all the
community of the realm'—no churchmen, be it observed—assembled
at Arbroath Abbey on April 6, and addressed to his Holiness a
memorable word in season. First, as to their kingdom and their King:

Our nation continued to enjoy freedom and peace under


the protection of the Papal See, till Edward, the late King of
the English, in the guise of a friend and ally, attacked our
realm, then without a head, and our people, then thinking no
evil or deceit, and unaccustomed to war or aggression. The
acts of injury, murder, violence, burning, imprisonment of
prelates, burning of abbeys, spoliation and slaying of
ecclesiastics, and other enormities besides, which he
practised on our people, sparing no age or sex, creed or rank,
no man could describe or fully understand without the
teaching of experience. From such countless evils, by the help
of Him that woundeth and maketh whole, we have been
delivered by the strenuous exertions of our Sovereign Lord,
King Robert, who, for the deliverance of his people and his
inheritance from the hands of the enemy, like another
Maccabeus or Joshua, cheerfully endured toils and perils,
distress and want. Him the Divine Providence, that legal
succession in accordance with our laws and customs, which
we are resolved to uphold even to death, and the due
consent of us all, made our Prince and King. To him, as the
man that has worked out the salvation of the people, we, in
maintenance of our freedom, by reason as well of his merits
as of his right, hold and are resolved to adhere in all things. If
he should abandon our cause, with the intention of subjecting
us or our realm to the King of England or to the English, we
should instantly strain every nerve to expel him as our enemy
and the subverter of both his own rights and ours, and
choose another for our King, such a one as should suffice for
our defence; for, so long as a hundred of us remain alive,
never will we be reduced to any sort of subjection to the
dominion of the English. For it is not for glory, or riches, or
honours, that we contend, but for freedom alone, which no
man worthy of the name loses but with his life.

With this noble and resolute declaration, they appealed to the


Pope to 'admonish' Edward, who ought to be content with his own
dominions, anciently held enough for seven kings, and 'to leave in
peace us Scotsmen, dwelling in our poor and remote country, and
desiring nothing but our own,' for which 'we are ready and willing to
do anything we can consistently with our national interests.' But,
further, as to the Pope himself:

If, however, your Holiness, yielding too credulous an ear


to the reports of our English enemies, do not give sincere
credit to what we now say, or do not cease from showing
them favour to our confusion, it is on you, we believe, that in
the sight of the Most High, must be charged the loss of lives,
the perdition of souls, and all the other miseries that they will
inflict on us and we on them.

This memorable declaration was not without effect. On August


13, the Pope earnestly impressed Edward with the duty of keeping
on good terms with Bruce. And on August 18, he wrote that, on the
prayer of Bruce by his envoys, Sir Edward de Mambuisson and Sir
Adam de Gordon, he had granted suspension of the personal citation
and of the publication of the sentences till the 1st of April next year.
CHAPTER XII

PEACE AT THE SWORD'S POINT

The Scots manifesto of April 6, 1320, presented a united and


firm front to English pretensions and Papal intrigues. Yet there were
traitors in the camp. Little more than four months had elapsed when
the Black Parliament, held at Scone on August 20, was investigating
a conspiracy to kill King Robert and elevate to the throne Sir William
de Soulis. Sir William was a brother of Sir John, and a grandson of
Sir Nicholas, one of the Competitors in 1292. Edward's emissaries
had been tampering with the fidelity of King Robert's barons.
The plot still remains involved in obscurity. It was discovered to
the King, Barbour heard, by a lady. Gray, however, as well as John of
Tynmouth, states that the informant was Sir Murdoch de Menteith,
who had come over to Bruce in 1316–17, and remained on the Scots
side till his death some sixteen years later; but, apart from his name,
there seems no reason to suppose that he was in Edward's pay. Sir
William was arrested at Berwick, with 360 squires in his livery (says
Barbour), to say nothing of 'joly' knights. He openly confessed his
guilt, and was interned for life in Dumbarton Castle. The Countess of
Strathearn was also imprisoned for life. Sir David de Brechin, Sir
John de Logie, and Richard Brown a squire, were drawn, hanged,
and beheaded. Sir Roger de Mowbray opportunely died; but his body
was brought up and condemned to be drawn, hanged, and
beheaded—a ghastly sentence considerately remitted by the King.
Sir Eustace de Maxwell, Sir Walter de Barclay, Sheriff of Aberdeen,
Sir Patrick de Graham, and two squires, Hamelin de Troupe and
Eustace de Rattray, were fully acquitted. Soulis, Brechin, Mowbray,
Maxwell, and Graham had all attended the Arbroath parliament, and
put their seals to the loyal manifesto.
It is far from evident why Soulis escaped with imprisonment
while Brechin and others were sent to the gallows. Robert may have
judged that Soulis was a tool rather than prime mover of the plot;
he may have regarded the long service of the culprit; he may have
softened at the recollection of his brother Sir John's death by his
own brother Edward's side. Brechin, no doubt, had considerable
services to his credit. But his record shows grievous instability, and
Robert probably had sound reasons for putting a period to his
dubieties. His fate aroused painful regrets. Barbour narrates that Sir
Ingram de Umfraville openly censured the sight-seers at his friend's
execution, obtained leave to give the body honourable burial, and
prepared to quit Scotland, telling the King he had no heart to remain
after seeing so good a knight meet with such a fate. This story of
Barbour's has been too hastily discredited.
The position of Bruce remained unshaken. On November 17,
Edward instructed various high officers to receive to his peace, 'as
secretly as they could,' such Scots as felt their consciences troubled
by the papal excommunication; and, on December 11, the
Archbishop of York was empowered to release all such renegades
from the censure of the Church. Sir Ingram de Umfraville was re-
established in his Northumberland estates (January 26), and Sir
Alexander de Mowbray (February 18) and Sir William de Mohaut
(May 20) obtained Edward's pardon. But Bruce was practically
unaffected by Edward's subterranean diplomacy.
Openly, Edward maintained due observance of the truce, and by
the middle of September 1320, had taken steps towards a final
peace. The negotiations begun at Carlisle at Michaelmas were
resumed at Newcastle on February 2, and continued for nine weeks;
papal commissioners being present, and French envoys fostering the
cause of peace. But the deliberations were fruitless. The Earl of
Richmond's production of a mass of old parchments to demonstrate
Edward's overlordship of Scotland indicates how little the English
King and commissioners realised the facts of the situation.
Throughout the summer and autumn of 1321, Edward was in
hot water with the barons of the Welsh border. At the July
parliament at Westminster, he was compelled to banish the
Despensers, and to send home the turbulent lords with pardon.
These troubles prevented him from sending the promised envoys to
'enlighten the consciences' of the Pope and his Cardinals as to the
wickedness of the Scots. On August 25, however, he wrote the usual
denunciatory generalities, and yet again impressed on his Holiness
the necessity of dealing severely with Bruce and his adherents. The
summons of Bruce and his four Bishops had meanwhile been
postponed to September 1; but even then they did not compear.
Edward's envoys, at last despatched on December 8, were still in
very good time. Having taken Leeds Castle in Kent and driven back
the marauding Marchers to the Welsh border, he informed the Pope
that his domestic troubles were settling down, and, in view of an
expedition on the expiry of the Scots truce at Christmas, he
appealed for a subsidy from Rome. But already Lancaster was
stretching one hand to Bruce and the other to the malcontents of
the Welsh March.
The Marchers rose, but Edward proved himself the stronger, and
by the third week of January received the submission of the
Mortimers. On February 8, he tried conciliation with Lancaster, and
also authorised Harcla to treat with Bruce for 'some sort of final
peace.' Lancaster, however, received the Welsh insurgents, and
harassed Edward's advance, but was compelled to fall back on his
castle of Pontefract.
Lancaster's negotiations with the Scots had begun as early as
December. His emissary, Richard de Topcliffe, an ecclesiastic, had
obtained a safe-conduct from Douglas (December 11) to visit
Jedburgh, and one from Randolph (January 15) to come to him
wherever he could find him. Randolph was then at Corbridge on a
swift raid, while Douglas and the Steward advanced, the one
towards Hartlepool and the other towards Richmond, harrying or
taking ransom. Immediately on the junction of Hereford and his
Marchers with Lancaster at Pontefract, in the beginning of February,
before they went south to oppose Edward's advance, the rebel chiefs
despatched John de Denum with a letter to Bruce, Randolph, and
Douglas, 'or which of them he shall soonest find,' asking an
appointment for a final agreement. The precise terms proposed were
presently found on the dead body of Hereford at Boroughbridge.
Bruce, if not detained by illness or other serious cause, and
Randolph and Douglas, with their power, shall join the Earls in their
enterprise 'in England, Wales and Ireland, and with them live and die
in the maintenance of their quarrel, without claiming conquest or
dominion in the said lands of England, Wales, and Ireland.' The
Earls, on their part, shall never aid Edward against the Scots, and,
their quarrel ended, shall do their best to establish and maintain
peace between the two countries on the footing of independence.
Fortunately for Edward, John de Denum lost ten days in his
peregrinations. He missed Douglas on February 7, and was unable to
obtain his reply till February 17. On February 16, Randolph, then at
Cavers, near Hawick, had issued a safe-conduct for Sir John de
Mowbray and Sir Roger de Clifford to come to him in Scotland. In
either case, the ten days were gone. But for this accident, the
history of the English crown would probably have been turned into
another channel.
The approach of the royal troops decided the insurgents to retire
towards the Scots, to Lancaster's castle of Dunstanburgh. At
Boroughbridge, however, they were confronted by Harcla on March
16, and disastrously defeated. Hereford was slain on the bridge;
Lancaster was captured, tried, and beheaded. Harcla was created
Earl of Carlisle. 'Do not trouble yourself,' wrote Edward to the Pope
(March 25), 'to proclaim a truce between me and the Scots.
Formerly some exigencies inclined me to a truce, but now, thank
God, these no longer exist, and I am constrained, by God's help, to
war them down for their broken faith.'
Edward at once summoned his army to muster at Newcastle by
the second week in June; but early in May he postponed the
assembly till July 24. By that time, however, the Scots had
completed another destructive raid. Before mid June, a force had
crossed the western March; and in the beginning of July, Robert
himself, with Randolph and Douglas, penetrated beyond Preston and
ravaged the length and breadth of Lancashire and the archdeaconry
of Richmond, burning Lancaster town and castle 'so entirely that
nothing is left,' and carrying off what cattle had not been driven for
safety into the remoter parts of Yorkshire. They do not seem to have
encountered local opposition. As they returned, they lay five days
before Carlisle, without drawing forth the prudent Harcla; and on
July 24, they struck their tents for home.
The English army followed them, entering Scotland by the
eastern March in the first days of August. Robert withdrew both men
and cattle from the Merse and the Lothians, either to the
strongholds or beyond the Forth, and lay with his army at Culross.
Barbour tells how an English foraging party found but one lame cow
at Tranent: 'It is the dearest beef I ever saw yet,' remarked
Warenne, 'it must have cost £1000 and more.' Edward himself
subsequently wrote that he had 'found neither man nor beast' in the
Lothians. The English fleet failed to bring up provisions, and, on
August 23, Edward found himself with some 7000 men at Leith, in
like predicament with his father before the battle of Falkirk. He was
starved into retreat. Immediately the Scots hung upon his rear, and
Douglas cut up an advance company of 300 men near Melrose. The
English had sacked Holyrood; they now sacked Melrose Abbey, killing
the prior and others; and they burnt to the ground Dryburgh and
other monasteries. 'But,' says Fordun, 'God rewarded them therefor.'
Bruce instantly followed up his advantage. By the middle of
September, the Scots were before Bamborough and Norham.
Bamborough bought off the invaders; and on September 26, Sir
Roger de Horsley, the constable, as well as the constables of
Warkworth, Dunstanburgh, and Alnwick castles, received a severe
wigging from Edward for not showing fight against such an inferior
force. Norham was defended by Sir Thomas Gray the elder against
an inadequate body of 200 Scots. Edward displayed great energy of
rebuke and counsel, while Robert steadily advanced southwards. On
October 14, the English army barred the way on the ridge of
Blackhowe Moor between Biland and Rievaulx; but Bruce's rapid
action enabled him to strike a decisive blow before the Earl of
Carlisle, who was at Boroughbridge with 2000 (surely not, as some
say, 20,000) horse and foot, could effect a junction, if indeed he
really meant to do so.
Douglas at once offered to storm the English position, and
Randolph, leaving his own division, led the way up the hill as a
volunteer. The Scots were strongly opposed by Sir Ralph de Cobham,
who was held to be the best knight of his day in England, and by Sir
Thomas Ughtred, constable of Pickering, whose gallantry in the fight
raised him to a higher position than even Cobham. The assailants
were grievously embarrassed by stones rolled down upon them and
by the fire of the archers. Robert supported them by sending 'the
Irishry,' the Argyll Highlanders, and the men of the Isles to scramble
up the crags in flank. At the top they were confronted by the main
body under the Earl of Richmond, but they charged with such
impetuosity as broke the English ranks and scattered them in flight;
Gray even uses the conventional expression, 'like a hare before
hounds.' 'In these days,' says John of Bridlington, 'the Lord took
away the hearts of the English.' Richmond was captured and held to
heavy ransom (14,000 marks). Lord Henri de Sully and other French
knights surrendered to Douglas; by arrangement with whom, King
Robert soon released them by way of diplomatic compliment to the
King of France. Edward narrowly escaped from Biland Abbey and
fled through the night to Bridlington, whence the prior conducted
him to Burstwick. Sir Walter the Steward pursued as far as York.
Robert occupied the abbeys of Biland and Rievaulx and divided the
spoils of the English camp and the king's baggage. Then, making
Malton his headquarters, he wasted Yorkshire at his will, taking
ransoms from Ripon, Beverley, and other towns, and despoiling
religious houses; and he returned, with immense booty, to keep
Christmas in Scotland.
Three calamitous invasions in one year might well have induced
reflection in a statesmanlike mind. They merely excited Edward's
impotent eagerness for revenge. But the Earl of Carlisle, as doughty
a warrior as the best, saw that the contest was both hopeless and
ruinous; and on January 3, 1322–23, he was closeted with Randolph
at Lochmaben. There and then they drafted an agreement. The
fundamental provisions were: (1) that each realm should have its
own national King; (2) that the Earl should aid King Robert in
maintaining Scotland against all gainsayers; and (3) that King Robert
and the Earl should maintain the realm of England under the
direction of a council of twelve, six to be chosen by each party.
Then, if the King of England should assent to these conditions within
a year, King Robert was to found an abbey in Scotland, of 500 marks
rent, for the souls of the men slain in war, and to pay an indemnity
of 40,000 marks within ten years; and the King of England was to
have the marriage of the heir male of the King of Scotland under
advice of the council of twelve.
Harcla at once published the terms of the agreement, and they
were received with intense satisfaction on the Border. He appears to
have acted in concert with the chief officers in these parts, and to
have believed, or at least professed, that he acted within the terms
of his commission. Edward, however, on January 8, ordered that no
truce be made without his knowledge, and summoned Harcla to his
presence; and on January 19, he sent a copy of the Lochmaben
indenture to his Council at York, with the comment that it appeared
to him 'fraught with great danger.' He had already (January 13)
instituted a search of the Chancery rolls for any authorisation to
Harcla to treat with the Scots. On February 25, Harcla was arrested
in Carlisle Castle; and on March 3, he was tried, condemned, and
barbarously executed. The charge of treason, though formally too
well grounded, was essentially baseless; otherwise it is unintelligible
that Harcla should have limited his measures of self-defence to the
procurement of the formal oaths of the northern sheriffs to stand by
him 'in all things touching the common good of England and the said
peace.' His action was simply the action of a strong, business-like,
and patriotic man, forgetful of finesse. His mistake lay in omitting to
obtain express authority to treat, and in neglecting either to veil his
contempt for the King, or to provide against his natural resentment,
inflamed as it was sure to be by the envy of personal enemies.
The death of Harcla, the keenest and ablest warrior in England,
did not remove the difficulties from Edward's path. In a fortnight he
was treating for peace—'was frightened, and begged for peace,'
according to the Flores Historiarum—though in his own perversely
maladroit fashion. On March 21, Robert wrote to Lord Henri de Sully,
Edward's envoy, in substance this:

The King of England's letter, of which you sent me a copy


yesterday, bears that he has granted a cessation of arms to
the people of Scotland at war with him. This language is very
strange to me. In former truces taken between us, I was
named principal of the one part, as he was of the other part,
although he did not vouchsafe to me the title of King. But on
this occasion, no more mention is made of me than of the
least person in my realm; so that, in case of a breach, I
should be no more entitled than another to demand redress.
Do not be surprised, then, that I do not agree to this truce. If,
however, it were put before me in the proper way, I should
willingly sanction it, as I promised you. I send you a copy of
the King's letter; for I imagine you have not seen it, or, if you
have, you have paid but scant attention to its terms.

After some futile negotiations at Newcastle, a truce was at last


concluded at Bishopsthorpe, near York, to last till June 12, and for
thirteen years thereafter. On May 30, 1323, Edward ordered it to be
proclaimed throughout England; and on June 7, Robert ratified it at
Berwick. Each party was to evacuate all lands of the other by June
12; neither party was to build or repair fortresses on the March,
excepting constructions in progress; and Edward was to interpose no
obstacle to any attempt of Robert and his friends to obtain
absolution at Rome. During the negotiations, Edward had been
summoning his forces in England, Ireland, and Gascony, in the belief
that the Scots were really purposing another invasion; but in the first
days of June he countermanded the muster.
King Robert was sincerely anxious to set himself and his people
right with the Church. He despatched Randolph as his ambassador.
On his way south, Randolph, with the Bishop of St Andrews, treated
with Edward's commissioners for a final peace; and, at any rate, on
November 25, he got Edward to write to the Pope and the Cardinals
in favour of a grant of absolution to the Scots during the peace
negotiations. How Randolph fared at Rome we learn from a letter of
the Pope's to Edward, dated January 1, 1323–24. First, he begged
for the usual indulgences necessary to enable him to fulfil his vow to
go on a crusade. The Pope refused: there would be little good to the
Holy Land or to his own soul, while he lay under the Church's
censure; but the request might be reconsidered if he would effect a
permanent peace with England and satisfy the Church. Secondly,
Randolph prayed for safe conducts for Bruce's envoys, presently to
be sent to procure reconciliation with the Church. The Pope refused,
for the present, but he agreed to direct the usual application to the
princes on the line of route. Thirdly, Randolph put forward Robert's
readiness to join the King of France in his proposed crusade, or, if
the King of France did not go, then to proceed himself or send
Randolph instead. The Pope replied that reconciliation with the
Church was an indispensable condition precedent. Fourthly,
Randolph declared that King Robert and himself desired above all
things to obtain peace and reconciliation, and that it really lay with
His Holiness to bring their ardent desires to fruition. Let him address
himself to Robert as King, and Robert would readily respond to his
wishes; it was the reservation of the royal title that blocked the way.
The Pope consented to address Robert by the royal title.
Edward was keenly annoyed. The Pope, after setting forth the
facts of Randolph's interview, had earnestly begged Edward not to
take it ill that he had consented to address Robert as King. It could
do him no harm; it could do Robert no good. He was intensely
anxious for peace, and, if he did not give Robert the royal title,
Robert would not look at his letters any more than he had done
before. But Edward did not agree. He bluntly urged that the
concession would prejudice his right and his honour, bring discredit
on the Church, and enable Bruce to make capital of his wrong-doing.
He recapitulated his claims to Scotland, contended that no change
should be introduced during the truce, and pointed out that the
concession would be popularly construed as a papal confirmation of
Bruce's title. Let the title therefore be reserved as before.
Then Edward played another card: he invited Edward de Balliol,
son of ex-King John, to come over to England. The safe-conduct was
issued on July 2; and it was not Edward's fault that Balliol postponed
his visit. Meantime, in the midst of conflict with France over
Aquitaine, Edward continued negotiations with Robert for final
peace. But no agreement could be reached. The true cause appears
in Edward's letter of March 8, 1324–25, to the Pope. There had
recently been a meeting of envoys at York, but the Scots would not
yet budge from their old position, and 'I could not meet their wishes
without manifest disherison of my royal crown.' His envoys had
proposed to refer the knotty point to the decision of His Holiness;
but 'this they absolutely declined.' The Scots, indeed, had apparently
stiffened their demands. According to the Monk of Malmesbury, they
had claimed not only the independence of Scotland, but also the
north of England down to the gates of York (by right of conquest),
and the restoration of Bruce's manor of Writtle in Essex, as well as
of the famous coronation stone.
In May, Scots envoys were again on the road to Rome, and
Edward wrote to the Pope, informing him that he was sending
ambassadors to guard his own interests. Again, on September 23,
he wrote to the Pope and the Cardinals urging them not to recall the
sentences of excommunication till the Scots should surrender
Berwick to him—Berwick, captured treacherously in defiance of the
papal truce. The Pope consented, and on October 18 Edward
expressed effusive thanks. But he reaped no advantage from the
diplomatic victory: in three months he was deposed by his
Parliament for notorious incompetence.
On January 25, 1326–27, Edward, Prince of Wales, a boy of
fifteen, was proclaimed King. He presently confirmed the thirteen
years' truce (February 15), and appointed envoys to treat for final
peace (March 4). The meeting was to take place on the March on
May 17. But, on April 5, Edward III. summoned his power to be at
Newcastle by May 18, averring that he had sure information that
Robert was massing his troops on the Border with the intention of
invading England if his own terms of peace were not conceded. It
seems much more likely that Robert's action was purely
precautionary in view of the disturbed condition of the English
March; but a hostile construction was favoured by the fact that many
of the most turbulent fellows in Northumberland were Scots. On the
other hand, Barbour is likely enough to be right in asserting that
Robert was unable to obtain redress for the seizure of Scots vessels
in English and Flemish waters; and it may be, as he says, that for
this reason Robert openly renounced the truce. At the same time,
Robert must have heard of Edward's warlike preparations by land
and sea. This may be what Fordun has in view when he says that
the duplicity of the English was at length laid bare. Edward's
summons was issued on April 5, and Froissart places Robert's formal
defiance 'about Easter' (April 12); but this date must be nearly two
months too early. One thing is certain: Robert was in no aggressive
mood, and would not have resumed hostilities without really serious
provocation.
About the middle of June a body of Scots crossed the Border,
and on July 4 they were at Appleby, almost in touch with the Earl
Marshal. Edward was at York, where he had been joined by Sir John
of Hainault, Lord of Beaumont, with a body of heavy cavalry,
between whom and the English archers much bad blood had been
spilt in the streets of York. His army was very large—Barbour says
50,000; Froissart says upwards of 40,000 men-at-arms; Murimuth
says three times as large and strong as the Scots army—a force
difficult alike to handle and to feed in a rough and wasted country,
especially in face of the Scots veterans. On July 13, Edward had
reached Northallerton, and had learned that the Scots intended to
mass their forces near Carlisle.
By this time the Scots army, under Randolph and Douglas, had
ravaged Coquetdale and penetrated into the Episcopate of Durham.
When Edward reached Durham city, he was apprised of the passage
of the Scots by a track of smoking ruins and devastated fields. He
decided to bar their return. Advancing with his cavalry, he crossed
the Tyne at Haydon Bridge (July 26), leaving his infantry on the
south side. But the Scots did not come, and between drenching rains
and lack of provisions his troops were worn out in body and in
temper. The men, says Froissart, 'tore the meat out of each other's
hands'; and 'great murmurs arose in the army.' After a week's
distressful experience, he determined to seek the enemy
southwards, and offered a reward of £100 a year in land, as well as
knighthood, to the man that should bring him in sight of them 'on
hard and dry ground' fit for battle. He crossed the Tyne at
Haltwhistle fords, losing many men in the swollen river. On the
fourth day, Thomas de Rokeby reported the Scots, and brought
Edward face to face with them on the Wear.
The Scots were strongly posted on a rising ground on the south
bank: Froissart numbers them 24,000; Barbour, much more
probably, 10,000. Douglas made a reconnaissance, and reported a
strong army in seven divisions. 'We will fight them,' cried Randolph,
'were they more'; but Douglas counselled patience. Presently Edward
sent heralds, offering to retire far enough to allow the Scots room to
array themselves for battle on the north side on the morrow; or, if
the Scots preferred, to accept like terms on the south side. It was an
unconscious repetition of the offer of Tomyris, Queen of Massagetai,
to Cyrus, on the Araxes river. But the Scots, evidently too weak to
fight in a plain field, replied that they would do neither the one thing
nor the other; that the King and his barons saw they were in his
kingdom and had burnt and pillaged wherever they had passed, and
that, if this displeased the King, he might come and amend it; for
they would tarry there as long as they pleased.' That night the
English lay on their arms. Part of the Scots also kept themselves in
readiness, while the rest retired to their huts, 'where they made
marvellously great fires, and, about midnight, such a blasting and
noise with their horns that it seemed as if all the great devils from
hell had been come there.'
The next two days the Scots and English lay watching each other
across the Wear. On the first day, a thousand English archers,
supported by men-at-arms, attempted to draw the Scots. Douglas,
planting an ambush under the Earl of Mar (who had at length joined
the Scots) and his own son Archibald of Douglas, rode forward, with
a cloak over his armour, and gradually gave way to their onset, till he
had enticed them within reach of the ambush. At Douglas's signal,
the ambush broke upon the pursuers, and slew 300 of them. Next
day, the English put 1000 horsemen in ambush in a valley behind the
Scots position, and delivered a front attack. Douglas was advancing
to repel the assailants when he was informed of the force in rear,
and instantly drew back his men. 'They flee,' cried some Englishmen;
but John of Hainault explained the manœuvre, and, according to
Barbour, pronounced the Scots captain fit 'to govern the Empire of
Rome.'
On the following morning—probably August 3—the Scots were
gone. They had moved about two miles along the river, and
occupied a still stronger position in Stanhope Park. In the afternoon
the English were again facing them. About midnight, Douglas, with
200 horsemen—Barbour says 500—crossed the Wear, and rode
boldly into the English camp. 'No guard, by St George!' he
exclaimed, on being discovered, as if he were an English officer. He
made right for the King's pavilion, and, shouting his war-cry, actually
'cut two or three of its cords.' The King most narrowly escaped
capture or death. Douglas got clear with but insignificant loss, and,
collecting his men by a prearranged note of his horn, he returned to
camp. Randolph, who was waiting under arms, ready for rescue or
aid, eagerly asked the news. 'Sir,' replied Douglas, 'we have drawn
blood.'
The success of Douglas suggested to Randolph that a larger
party might have inflicted defeat on the English. Douglas had his
grave doubts. Randolph again proposed a pitched battle. Douglas
objected, in view of the disastrous effects in case of defeat. No;
better treat the English as the fox treated the fisherman. The fox
had entered the fisherman's cottage and was eating a salmon. The
fisherman discovered him, and stood on the threshold with a drawn
sword in his hand. The fox, seeing the fisherman's cloak on the bed,
dragged it into the fire. Thereupon the fisherman rushed to save his
cloak, and the fox bolted out at the unguarded door. Douglas, in
fact, had planned a mode of escape, and, though somewhat wet
('sumdele wat'), it would serve. Randolph gave way. So the Scots
made merry in the day time, burnt great fires at night, and blew
their horns 'as if all the world were theirs.' Occasional skirmishes
took place, and the English drew round the Scots on both sides,
leaving their rear open on a morass believed to be impassable.
Meantime Douglas made his preparations.
It was probably on the night of August 6–7 that Douglas led the
Scots army out of Stanhope Park. He took them across the morass,
about a mile wide, over a causeway of branches, which the rear
demolished as they passed. The men led their horses, and only a
few baggage animals stuck fast. By daybreak the Scots were far on
the way homewards. The English had been completely outwitted. On
the day before, they had captured a Scots knight, who told them
that orders had been issued 'for all to be armed by vespers and to
follow the banner of Douglas,' he did not know where. The English
lords suspected a night attack, and remained under arms. In the
morning, two Scots trumpeters, who had been left to blow
misleading blasts, were brought into camp. 'The Scots,' they said,
'are on the march home, since midnight; they left us behind to give
you the information.' The English, fearing a ruse, continued to stand
to their arms till their scouts confirmed the mortifying intelligence.
The Scots were soon met by a considerable body of their
countrymen under the Earl of March and Sir John the Steward. They
all hurried back to Scotland by the western march. The English
retired to Durham, and then to York, where the army was disbanded
on August 15. Edward is said to have shed bitter tears over the
collapse of his expedition. Some of the chroniclers allege
unsupported charges of treachery, and mistakenly accuse Mortimer
of accepting a heavy bribe to wink at the escape of the Scots. But
the plain fact is that the English were outgeneralled at every turn.
It was neither age nor sickness, as the chroniclers allege, that
prevented King Robert from leading the Weardale foray. He was
away in Ireland, creating a diversion. On July 12, at Glendun in
Antrim, he granted a truce for a year to Henry de Maundeville, the
English seneschal of Ulster, and his people, on condition of their
delivering a certain quantity of wheat and barley at Lough Larne.
The expedition does not seem to have been directly prosperous; the
Irish, whom he had expected to rise and join him in Ulster, having
apparently broken faith.
Immediately on the return of the Scots from Weardale, King
Robert passed into Northumberland. He sent Randolph and Douglas
to besiege Alnwick Castle; set down another division before Norham
Castle; and, with a third body, himself overran the neighbourhood.
He even granted away the English lands to his chief followers. The
attempt on Alnwick was unsuccessful, and, the open country having
bought a truce, the leaders concentrated on Norham. On October 1,
while Bruce still lay before Norham, Edward appointed
commissioners to treat with him for final peace. After negotiations at
Newcastle and York, the treaty was signed by Robert at Edinburgh
on March 17; confirmed by the English Parliament on April 24; and
finally, on May 4, signed by Edward at Northampton. Edward
conceded in the fullest terms the absolute independence of Scotland
as the marches stood in the days of Alexander III., and agreed to
deliver up all extant documents relating to the overlordship, and in
any case to annul them; and he consented to aid Robert to obtain
the revocation of the papal processes. Robert agreed to pay £20,000
sterling in three years. And the peace was to be cemented by the
marriage of David, the Scots heir-apparent, a boy of four, with Joan,
King Edward's sister, a girl of six. In England, the peace was freely
stigmatised as 'shameful,' and the marriage as 'base'; partly on
patriotic grounds, partly from dislike of Queen Isabella and Mortimer,
who guided the policy of the King. The news of the death of the
King of France no doubt gave an impulse to the English decision, for
it would be necessary for Edward to have his hands free to assert his
claim to the succession. The conditions were alike 'honourable for
the Scots and necessary for England.'
CHAPTER XIII

THE HEART OF THE BRUCE

King Robert the Bruce died at Cardross on the Clyde, on June 7,


1329, a little more than a month before the completion of his fifty-
fifth year. The cause of his death is said to have been leprosy.
Barbour says it was the development of a severe cold, a
benumbment contracted in the hardships of his early wanderings.
Apart from specific disease, the strain of his laborious reign of nearly
a quarter of a century would have shaken the strongest constitution
of man.
In the last three years he had been struck by two severe
bereavements: the death of his son-in-law, Sir Walter the Steward, a
knight of great promise, on April 9, 1326; and the death of the
queen, at Cullen, on October 26, 1327. In the latter year, indeed, in
spite of increasing illness, he had taken the field in Ireland and in
Northumberland. But he had been unable to attend the marriage of
David and Joan at Berwick in July 1328. Still he continued to move
about quietly. When, however, Douglas brought him back from a visit
to Galloway in the end of March 1329, it was not to be concealed
that 'there was no way for him but death.' And, accordingly, he set
his house in order.
On October 15, 1328, the Pope had at last granted absolution to
Robert from the excommunication pronounced by the cardinals, and,
on November 5, authorised his confessor to give him plenary
remission in the hour of death.
At a parliament held on November 14, 1328, at Scone, it had
been settled that, in the event of David's dying without heir male of
his body begotten, Robert the Steward, son of Marjory, should
succeed; and that, if King Robert died during David's minority,
Randolph should be regent, and, failing Randolph, Douglas. David
and Joan were crowned, and David received homage and fealty.
On May 11, 1329, the King assembled his prelates and barons to
hear his last wishes. He gave directions for liberal largess to religious
houses, with special consideration for Melrose Abbey, where he
desired his heart to be buried. He declared his long-cherished
intention—Froissart says his 'solemn vow'—after bringing his realm
to peace, 'to go forth and war with the enemies of Christ, the
adversaries of our holy Christian faith.' As he had been unable to
carry out his fixed purpose, he wished his heart to be taken and
borne against the foes of God. On Douglas was laid this great and
noble charge. Froissart mentions a specific instruction: 'I wish that
you convey my heart to the Holy Sepulchre where our Lord lay, and
present it there, seeing my body cannot go thither. And wherever
you come,' added the King, 'let it be known that you carry with you
the heart of King Robert of Scotland, at his own instance and desire,
to be presented at the Holy Sepulchre.' Douglas solemnly pledged
himself to this last faithful service.
On the death of King Robert, his heart was embalmed, and
enclosed in a silver casket 'cunningly enamelled,' which Douglas bore
always about his neck. Strangely enough, even in death, the King
came in conflict with Rome; for the excision of his heart was a
breach of a Papal Bull of 1299, involving excommunication of the
mutilators, and excluding the body from ecclesiastical burial. On
August 13, 1331, the Pope, at the prayer of Randolph, granted
absolution to all that had taken part 'in the inhuman and cruel
treatment' of the King's body.
The body was embalmed, and carried through the Lennox, and
by Dunipace and Cambuskenneth, to repose with the body of the
Queen in Dunfermline Abbey—since Malcolm Canmore, the last
resting-place of the Kings of Scotland. Over the King's grave was
erected a marble monument, which he had ordered from Paris a
twelvemonth before his death. It might have been supposed that
never in time would any Scotsman lay a rude hand on the sepulchre
of the greatest of Scottish kings; yet on March 28, 1560, an
insensate rabble of 'Reformers' razed the abbey to the ground, and
broke in pieces the royal monument. In 1818, when foundations for
a new church were being cleared, there were found, in a grave in
front of the spot where the high altar of the Abbey Church had
stood, the bones of a man whose breast-bone had been sawn
asunder, and who had been buried in fine linen shot with gold
thread. The probability that these were the bones of Bruce was
enhanced by the surrounding fragments of black and white marble,
well-polished, carved, and gilt. There lay also a mouldering skull,
which five centuries agone may have held the powerful brain that
dominated the field of Bannockburn.
Douglas set about his preparations. Now that peace with
England was established, and Randolph held the reins of State, there
was no national reason why Douglas could not be spared for a time.
Nor would warriors like Bruce and his paladins have ever weighed
for a moment the risks of the sacred mission. It seems a
misapprehension to suggest either selfishness or ingratitude on the
part of the dying King. Nor is there any substantial ground for
imagining that Robert feared any lack of harmony between his two
great lieutenants. Barbour's casual suggestion of petty rivalry
between them cannot weigh for a moment against their constant
association in scores of enterprises. Their rivalry was of noble
quality. The King had made a knightly vow, and that vow he must,
as far as might be, perform; it was hardly less a national than a
personal obligation.
On September 1, Douglas obtained from Edward III. letters of
protection for seven years, and a letter of commendation to Alfonso
XI., King of Castile and Leon. On February 1, 1329–30, the day of
the patron saint of his house, St Bride, he bestowed lands on the
Abbey of Newbattle to secure her special intercession in his spiritual
interests. Shortly thereafter he set out on his mission, with 'a noble
company'—one knight banneret, seven other knights, twenty-six
squires, and a large retinue. According to Froissart, he sailed from
Montrose to Sluys, where he lay twelve days, thinking he might be
joined by other knights 'going beyond the sea to Jerusalem'; and
then to Valencia in Spain. According to Barbour he sailed from
Berwick direct to Seville. In any case, he proceeded to the camp of
Alfonso, then on his frontier warring against Osmyn, the Moorish
King of Granada, and was received with honour befitting his fame
and his mission. The knights with Alfonso were eagerly curious to
see the famous Scot; and one notable warrior expressed his great
surprise that Douglas's face was not seamed with scars like his own.
'Praised be God!' said Douglas, 'I always had hands to defend my
head.'
On August 25, 1330, the Christian and Moorish armies faced
each other near Theba on the Andalusian frontier. Froissart states
that Douglas mistook a forward movement of the Spanish troops for
the onset of battle, and charged the Moors furiously; but the
Spaniards had halted and left him unsupported. The story seems
little consonant with Douglas's warlike intelligence. Barbour says that
Alfonso assigned to Douglas the command of the van—which is very
unlikely, unless he also assigned him an interpreter. He also asserts
that Douglas hurled the precious casket 'a stone-cast and well more'
into the ranks of the enemy, exclaiming—
'"Now pass thou forth before
As thou wast wont in field to be,
And I shall follow, or else dee"';

and that he fought his way to it and recovered it, 'taking it up with
great daintie.' This, too, is but a fantastic embellishment of the
cloister. Barbour, of course, proceeds to rout the Moors and to make
Douglas press on ahead of his company, attended by only ten men.
Seeing Sir William de St Clair surrounded, however, Douglas spurred
to his friend's rescue, but was overpowered by numbers and slain.
Among those that fell with him were Sir William de St Clair and Sir
Robert and Sir Walter Logan.
The bones of Douglas were brought home by Sir William de
Keith, who had been kept out of the battle by a broken arm, and
were buried in the church of St Bride of Douglas. The silver casket
with the heart of Bruce was buried by Randolph, 'with great
worship,' in Melrose Abbey.
Douglas has been charged with breach of trust. It is argued that
he ought not to have gone to Spain, but to have crossed the
continent to Venice or the south of France, and made direct for
Jerusalem. It is hardly worth while to remark that this is just what
Boece says he did, his death taking place in Spain on his way home.
It is more to the purpose that the Holy Sepulchre was then in the
hands of the Saracens, and that Spain was the central point of
opposition to the infidels. But what Douglas ought or ought not to
have done depends solely on the precise terms of his trust; and it
may be taken as certain that he knew King Robert's mind better than
either Barbour or Froissart, or even their critics, and that he decided
on his course in consultation with Randolph and the other magnates,
prelates as well as barons. Edward's safe conduct and
commendatory letter show by their terms that his going to Spain
was no afterthought, but his original intention. To attribute to
Douglas lack of 'strength of purpose' is to miss the whole
significance of his career.
* * * * *

King Robert must obviously have been a man of powerful


physique and iron constitution. The early hardships and continuous
toils of his reign could not have been sustained by any ordinary
frame; and his recorded feats of strength, such as in the case of
Wallace have been scouted as fabulous, have always been accepted
without question. The Merton MS. of the 'Flores Historiarum' calls
him 'a very powerful man,' on the occasion of his striking down
Comyn. The killing of Sir Henry de Bohun in face of both armies
speaks convincingly of muscle as well as of nerve. If the bones
discovered in 1818 were his, they indicate that he stood about six
feet in height. 'In figure,' says Major, 'he was graceful and athletic,
with broad shoulders. His features were handsome, and he had the
yellow hair of the northern race, and blue and sparkling eyes.'
Bruce's outstanding characteristic, in Barbour's analysis, was his
'hardiment:' he 'hardy was of head and hand.' That is to say, he was
a strong, bold, and resolute soldier. But with hardiment he joined
'wit'—judgment, prudence, measure; and the union of the two is
'worship.' This 'worship' was undoubtedly the fundamental cause of
Bruce's great career; and the most simple and conspicuous
illustration of it is seen in the dramatic episode of De Bohun's death.
Fordun pronounces that he 'was, beyond all living men of his day, a
valiant knight.' And Barbour sums up—
'To whom, into gude chevelry,
I dar peir nane, wes in his day.
For he led hym with mesure ay.'

It was this splendid hardiment controlled and directed by cool


judgment, and supported by untiring industry in details, that ranked
King Robert not merely as the second knight in Christendom, but as
one of the most renowned generals of the age. His patient drudgery
of preparation, his wary dispositions, his firmness of resolution, his
promptitude to mark and remedy a weakness of his own and to
strike hard at a weakness of the enemy, were superbly illustrated on
the field of Bannockburn. King Robert's military renown does not
need the false attribution of tactical discoveries that he certainly did
not make. It was not Bannockburn that showed him what infantry
could do against mailed cavalry; nor was it the example of the
Flemings at Courtrai. Sir William Wallace had proved the power of
the schiltron before Bannockburn and before Courtrai; and he is not
to be deprived of the honour by the imperfect historical knowledge
of Sir Thomas Gray. If the tactic was known in these islands before
the time of Wallace, or if Wallace gained the knowledge of it from
elsewhere, the fact yet remains to be historically demonstrated. King
Robert and his generals simply practised the lesson of Wallace with
notable ability. Nor did they advance beyond Wallace in the still more
important principles of large strategy. But, apart from this, the
Bruce's capacity as a military commander stands forth pre-eminent.
And though many painful incidents inevitably stain the records of his
campaigns, they are attributable more to the age than to the man. It
is impossible to charge on his memory any reckless or wanton
cruelty. His mind with all its sternness ever tended to clemency, and
his constitutional prudence, or measure, forbade purposeless excess.
The incessant demands of war left Robert but scant leisure for
internal administration, notwithstanding the diligent service of his
eminently capable lieutenants. Apart from necessary inference and
from incidental indications, his care for civil order and good
government is conspicuously manifested in the legislation of the
Scone Parliament, December 3, 1318; and there is abundant
evidence of his fostering watchfulness over the commercial traffic
with Continental countries. The Cambuskenneth Parliament, July 15,
1326, has a constitutional interest, as the first great council where
burgesses are known to have sat with the baronage. The trading
communities were worth consultation when a heavy war tax was to
be levied, and the country was so cruelly impoverished. There can
be no doubt that Robert's management of home affairs was
watchful, energetic, and liberal.
In the conduct of his foreign relations, the Bruce proved himself
an adept in diplomacy. His dealings with the Continental princes,
mainly in regard to shipping and commerce, were conciliatory and
businesslike. His political transactions with the English sovereign and
with the Pope were uniformly characterised by astute perception,
reasonableness to the point of generosity, courteous but rigid
firmness on every essential point, and fidelity to engagements.
The occupations of the King's late and brief leisure may be read
between the lines of the Exchequer Rolls: how he kept open house
at Cardross, dispensed gifts and charities, pottered (with Randolph)
at shipbuilding, sailed his great ship between Cardross and Tarbet,
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